kikocis/freqtrade-strategies public
Changesets · Branches · Tags · Compare
| Changeset | 3bc96bad5b80c612d8b8e326b3d0c7081073ed0b6f81cb3a2adda18a467ab620 |
|---|---|
| Author | Bryan Chain <bryan.chain@cerner.com> · 2021-03-27 19:37 -04:00 |
| Committer | Bryan Chain <bryan.chain@cerner.com> · 2021-03-27 19:37 -04:00 |
| Parents | f358d6d8a67e |
124 files changed
modified .gitignore +21 −0
| @@ -1,3 +1,24 @@ | ||
| 1 | +# Freqtrade Excludes | |
| 2 | + | |
| 3 | +# Private configs | |
| 4 | +config-pairs*.json | |
| 5 | +config-trade*.json | |
| 6 | +config-dry*.json | |
| 7 | + | |
| 8 | +# Data | |
| 9 | +data/ | |
| 10 | + | |
| 11 | +# Live or Private Strategies | |
| 12 | +live/ | |
| 13 | +private/ | |
| 14 | + | |
| 15 | +# Strategies that are not mine | |
| 16 | +other/ | |
| 17 | +sample/ | |
| 18 | + | |
| 19 | +######################################## | |
| 20 | +# General Python .gitignore below | |
| 21 | + | |
| 1 | 22 | # Byte-compiled / optimized / DLL files |
| 2 | 23 | __pycache__/ |
| 3 | 24 | *.py[cod] |
modified README.md +5 −2
| @@ -1,2 +1,5 @@ | ||
| 1 | -# freqtrade-strategies | |
| 2 | - Trading Strategies for Freqtrade | |
| 1 | +# Freqtrade Strategies | |
| 2 | + | |
| 3 | +Strategies for Freqtrade, developed primarily as a partnership between @werkkrew and @JimmyNixx from the Freqtrade Discord. | |
| 4 | + | |
| 5 | +Use these strategies at your own risk. We are not responsible for anything. |
added config-backtest-BTC.json +131 −0
| @@ -0,0 +1,131 @@ | ||
| 1 | +{ | |
| 2 | + "max_open_trades": 20, | |
| 3 | + "stake_currency": "BTC", | |
| 4 | + "stake_amount": "unlimited", | |
| 5 | + "tradable_balance_ratio": 0.95, | |
| 6 | + "fiat_display_currency": "USD", | |
| 7 | + "dry_run": true, | |
| 8 | + "dry_run_wallet": 0.020, | |
| 9 | + "cancel_open_orders_on_exit": false, | |
| 10 | + "order_types": { | |
| 11 | + "buy": "limit", | |
| 12 | + "sell": "limit", | |
| 13 | + "emergencysell": "market", | |
| 14 | + "stoploss": "market", | |
| 15 | + "stoploss_on_exchange": true, | |
| 16 | + "stoploss_on_exchange_interval": 60, | |
| 17 | + "stoploss_on_exchange_limit_ratio": 0.99 | |
| 18 | + }, | |
| 19 | + "order_time_in_force": { | |
| 20 | + "buy": "gtc", | |
| 21 | + "sell": "gtc" | |
| 22 | + }, | |
| 23 | + "bid_strategy": { | |
| 24 | + "price_side": "bid", | |
| 25 | + "ask_last_balance": 0.0, | |
| 26 | + "use_order_book": false, | |
| 27 | + "order_book_top": 1, | |
| 28 | + "check_depth_of_market": { | |
| 29 | + "enabled": false, | |
| 30 | + "bids_to_ask_delta": 1 | |
| 31 | + } | |
| 32 | + }, | |
| 33 | + "ask_strategy": { | |
| 34 | + "price_side": "ask", | |
| 35 | + "use_order_book": false, | |
| 36 | + "order_book_min": 1, | |
| 37 | + "order_book_max": 1 | |
| 38 | + }, | |
| 39 | + "download_trades": true, | |
| 40 | + "exchange": { | |
| 41 | + "name": "kraken", | |
| 42 | + "key": "", | |
| 43 | + "secret": "", | |
| 44 | + "ccxt_config": {"enableRateLimit": true}, | |
| 45 | + "ccxt_async_config": { | |
| 46 | + "enableRateLimit": true, | |
| 47 | + "rateLimit": 3100 | |
| 48 | + }, | |
| 49 | + "pair_whitelist": [ | |
| 50 | + "ADA/BTC", | |
| 51 | + "DOT/BTC", | |
| 52 | + "FLOW/BTC", | |
| 53 | + "MANA/BTC", | |
| 54 | + "LTC/BTC", | |
| 55 | + "UNI/BTC", | |
| 56 | + "KSM/BTC", | |
| 57 | + "LINK/BTC", | |
| 58 | + "XMR/BTC", | |
| 59 | + "ATOM/BTC", | |
| 60 | + "XLM/BTC", | |
| 61 | + "XTZ/BTC", | |
| 62 | + "ALGO/BTC", | |
| 63 | + "GRT/BTC", | |
| 64 | + "BCH/BTC", | |
| 65 | + "NANO/BTC", | |
| 66 | + "AAVE/BTC", | |
| 67 | + "EOS/BTC", | |
| 68 | + "BAT/BTC", | |
| 69 | + "ICX/BTC", | |
| 70 | + "KEEP/BTC", | |
| 71 | + "REP/BTC", | |
| 72 | + "DASH/BTC", | |
| 73 | + "SC/BTC", | |
| 74 | + "YFI/BTC", | |
| 75 | + "OXT/BTC", | |
| 76 | + "CRV/BTC", | |
| 77 | + "EWT/BTC", | |
| 78 | + "COMP/BTC", | |
| 79 | + "TRX/BTC", | |
| 80 | + "SNX/BTC", | |
| 81 | + "KAVA/BTC", | |
| 82 | + "LSK/BTC", | |
| 83 | + "BAL/BTC", | |
| 84 | + "ZEC/BTC", | |
| 85 | + "WAVES/BTC", | |
| 86 | + "KNC/BTC", | |
| 87 | + "OMG/BTC", | |
| 88 | + "FIL/BTC", | |
| 89 | + "ANT/BTC", | |
| 90 | + "GNO/BTC", | |
| 91 | + "REPV1/BTC", | |
| 92 | + "ETC/BTC", | |
| 93 | + "QTUM/BTC", | |
| 94 | + "STORJ/BTC", | |
| 95 | + "MLN/BTC", | |
| 96 | + "OCEAN/BTC" | |
| 97 | + ], | |
| 98 | + "pair_blacklist": [ | |
| 99 | + "DOGE/BTC", | |
| 100 | + "XRP/BTC", | |
| 101 | + "DAI/BTC", | |
| 102 | + "PAXG/BTC", | |
| 103 | + "TBTC/BTC", | |
| 104 | + "ETH/BTC" | |
| 105 | + ] | |
| 106 | + }, | |
| 107 | + "pairlists": [ | |
| 108 | + {"method": "StaticPairList"} | |
| 109 | + ], | |
| 110 | + "telegram": { | |
| 111 | + "enabled": true, | |
| 112 | + "token": "", | |
| 113 | + "chat_id": "" | |
| 114 | + }, | |
| 115 | + "api_server": { | |
| 116 | + "enabled": false, | |
| 117 | + "listen_ip_address": "127.0.0.1", | |
| 118 | + "listen_port": 8080, | |
| 119 | + "verbosity": "info", | |
| 120 | + "jwt_secret_key": "somethingrandom", | |
| 121 | + "CORS_origins": [], | |
| 122 | + "username": "", | |
| 123 | + "password": "" | |
| 124 | + }, | |
| 125 | + "bot_name": "freqtrade", | |
| 126 | + "initial_state": "running", | |
| 127 | + "forcebuy_enable": false, | |
| 128 | + "internals": { | |
| 129 | + "process_throttle_secs": 5 | |
| 130 | + } | |
| 131 | +} |
added config-backtest-ETH.json +124 −0
| @@ -0,0 +1,124 @@ | ||
| 1 | +{ | |
| 2 | + "max_open_trades": 20, | |
| 3 | + "stake_currency": "ETH", | |
| 4 | + "stake_amount": "unlimited", | |
| 5 | + "tradable_balance_ratio": 0.95, | |
| 6 | + "fiat_display_currency": "USD", | |
| 7 | + "dry_run": true, | |
| 8 | + "dry_run_wallet": 0.25, | |
| 9 | + "cancel_open_orders_on_exit": false, | |
| 10 | + "order_types": { | |
| 11 | + "buy": "limit", | |
| 12 | + "sell": "limit", | |
| 13 | + "emergencysell": "market", | |
| 14 | + "stoploss": "market", | |
| 15 | + "stoploss_on_exchange": true, | |
| 16 | + "stoploss_on_exchange_interval": 60, | |
| 17 | + "stoploss_on_exchange_limit_ratio": 0.99 | |
| 18 | + }, | |
| 19 | + "order_time_in_force": { | |
| 20 | + "buy": "gtc", | |
| 21 | + "sell": "gtc" | |
| 22 | + }, | |
| 23 | + "bid_strategy": { | |
| 24 | + "price_side": "bid", | |
| 25 | + "ask_last_balance": 0.0, | |
| 26 | + "use_order_book": false, | |
| 27 | + "order_book_top": 1, | |
| 28 | + "check_depth_of_market": { | |
| 29 | + "enabled": false, | |
| 30 | + "bids_to_ask_delta": 1 | |
| 31 | + } | |
| 32 | + }, | |
| 33 | + "ask_strategy": { | |
| 34 | + "price_side": "ask", | |
| 35 | + "use_order_book": false, | |
| 36 | + "order_book_min": 1, | |
| 37 | + "order_book_max": 1 | |
| 38 | + }, | |
| 39 | + "download_trades": true, | |
| 40 | + "exchange": { | |
| 41 | + "name": "kraken", | |
| 42 | + "key": "", | |
| 43 | + "secret": "", | |
| 44 | + "ccxt_config": {"enableRateLimit": true}, | |
| 45 | + "ccxt_async_config": { | |
| 46 | + "enableRateLimit": true, | |
| 47 | + "rateLimit": 3100 | |
| 48 | + }, | |
| 49 | + "pair_whitelist": [ | |
| 50 | + "ADA/ETH", | |
| 51 | + "DOT/ETH", | |
| 52 | + "LINK/ETH", | |
| 53 | + "KSM/ETH", | |
| 54 | + "AAVE/ETH", | |
| 55 | + "MANA/ETH", | |
| 56 | + "ALGO/ETH", | |
| 57 | + "LTC/ETH", | |
| 58 | + "UNI/ETH", | |
| 59 | + "XTZ/ETH", | |
| 60 | + "GRT/ETH", | |
| 61 | + "ATOM/ETH", | |
| 62 | + "KEEP/ETH", | |
| 63 | + "GNO/ETH", | |
| 64 | + "COMP/ETH", | |
| 65 | + "SNX/ETH", | |
| 66 | + "EOS/ETH", | |
| 67 | + "TRX/ETH", | |
| 68 | + "NANO/ETH", | |
| 69 | + "BCH/ETH", | |
| 70 | + "OXT/ETH", | |
| 71 | + "KAVA/ETH", | |
| 72 | + "REP/ETH", | |
| 73 | + "SC/ETH", | |
| 74 | + "ICX/ETH", | |
| 75 | + "BAT/ETH", | |
| 76 | + "YFI/ETH", | |
| 77 | + "FIL/ETH", | |
| 78 | + "KNC/ETH", | |
| 79 | + "MLN/ETH", | |
| 80 | + "BAL/ETH", | |
| 81 | + "OMG/ETH", | |
| 82 | + "ANT/ETH", | |
| 83 | + "WAVES/ETH", | |
| 84 | + "LSK/ETH", | |
| 85 | + "REPV1/ETH", | |
| 86 | + "STORJ/ETH", | |
| 87 | + "FLOW/ETH", | |
| 88 | + "CRV/ETH", | |
| 89 | + "QTUM/ETH", | |
| 90 | + "ETC/ETH" | |
| 91 | + ], | |
| 92 | + "pair_blacklist": [ | |
| 93 | + "XRP/ETH", | |
| 94 | + "ETH2/ETH", | |
| 95 | + "ETH2.S/ETH", | |
| 96 | + "PAXG/ETH", | |
| 97 | + "TBTC/ETH" | |
| 98 | + ] | |
| 99 | + }, | |
| 100 | + "pairlists": [ | |
| 101 | + {"method": "StaticPairList"} | |
| 102 | + ], | |
| 103 | + "telegram": { | |
| 104 | + "enabled": true, | |
| 105 | + "token": "", | |
| 106 | + "chat_id": "" | |
| 107 | + }, | |
| 108 | + "api_server": { | |
| 109 | + "enabled": false, | |
| 110 | + "listen_ip_address": "127.0.0.1", | |
| 111 | + "listen_port": 8080, | |
| 112 | + "verbosity": "info", | |
| 113 | + "jwt_secret_key": "somethingrandom", | |
| 114 | + "CORS_origins": [], | |
| 115 | + "username": "", | |
| 116 | + "password": "" | |
| 117 | + }, | |
| 118 | + "bot_name": "freqtrade", | |
| 119 | + "initial_state": "running", | |
| 120 | + "forcebuy_enable": false, | |
| 121 | + "internals": { | |
| 122 | + "process_throttle_secs": 5 | |
| 123 | + } | |
| 124 | +} |
added config-backtest-USD-pruned.json +106 −0
| @@ -0,0 +1,106 @@ | ||
| 1 | +{ | |
| 2 | + "max_open_trades": 20, | |
| 3 | + "stake_currency": "USD", | |
| 4 | + "stake_amount": "unlimited", | |
| 5 | + "tradable_balance_ratio": 0.95, | |
| 6 | + "fiat_display_currency": "USD", | |
| 7 | + "dry_run": true, | |
| 8 | + "dry_run_wallet": 1000.00, | |
| 9 | + "cancel_open_orders_on_exit": false, | |
| 10 | + "order_types": { | |
| 11 | + "buy": "limit", | |
| 12 | + "sell": "limit", | |
| 13 | + "emergencysell": "market", | |
| 14 | + "stoploss": "market", | |
| 15 | + "stoploss_on_exchange": true, | |
| 16 | + "stoploss_on_exchange_interval": 60, | |
| 17 | + "stoploss_on_exchange_limit_ratio": 0.99 | |
| 18 | + }, | |
| 19 | + "order_time_in_force": { | |
| 20 | + "buy": "gtc", | |
| 21 | + "sell": "gtc" | |
| 22 | + }, | |
| 23 | + "bid_strategy": { | |
| 24 | + "price_side": "bid", | |
| 25 | + "ask_last_balance": 0.0, | |
| 26 | + "use_order_book": false, | |
| 27 | + "order_book_top": 1, | |
| 28 | + "check_depth_of_market": { | |
| 29 | + "enabled": false, | |
| 30 | + "bids_to_ask_delta": 1 | |
| 31 | + } | |
| 32 | + }, | |
| 33 | + "ask_strategy": { | |
| 34 | + "price_side": "ask", | |
| 35 | + "use_order_book": false, | |
| 36 | + "order_book_min": 1, | |
| 37 | + "order_book_max": 1 | |
| 38 | + }, | |
| 39 | + "download_trades": true, | |
| 40 | + "exchange": { | |
| 41 | + "name": "kraken", | |
| 42 | + "key": "", | |
| 43 | + "secret": "", | |
| 44 | + "ccxt_config": {"enableRateLimit": true}, | |
| 45 | + "ccxt_async_config": { | |
| 46 | + "enableRateLimit": true, | |
| 47 | + "rateLimit": 3100 | |
| 48 | + }, | |
| 49 | + "pair_whitelist": [ | |
| 50 | + "KNC/USD", | |
| 51 | + "OXT/USD", | |
| 52 | + "QTUM/USD", | |
| 53 | + "YFI/USD", | |
| 54 | + "BAL/USD", | |
| 55 | + "WAVES/USD", | |
| 56 | + "FIL/USD", | |
| 57 | + "ANT/USD", | |
| 58 | + "REPV1/USD", | |
| 59 | + "ETC/USD", | |
| 60 | + "MANA/USD", | |
| 61 | + "LSK/USD", | |
| 62 | + "CRV/USD", | |
| 63 | + "MLN/USD" | |
| 64 | + ], | |
| 65 | + "pair_blacklist": [ | |
| 66 | + "DOGE/USD", | |
| 67 | + "TBTC/USD", | |
| 68 | + "XRP/USD", | |
| 69 | + "DAI/USD", | |
| 70 | + "PAXG/USD", | |
| 71 | + "USDT/USD", | |
| 72 | + "USDC/USD", | |
| 73 | + "EUR/USD", | |
| 74 | + "GBP/USD", | |
| 75 | + "AUD/USD", | |
| 76 | + "CAD/USD", | |
| 77 | + "CHF/USD", | |
| 78 | + "JPY/USD", | |
| 79 | + "BTC/USD" | |
| 80 | + ] | |
| 81 | + }, | |
| 82 | + "pairlists": [ | |
| 83 | + {"method": "StaticPairList"} | |
| 84 | + ], | |
| 85 | + "telegram": { | |
| 86 | + "enabled": true, | |
| 87 | + "token": "", | |
| 88 | + "chat_id": "" | |
| 89 | + }, | |
| 90 | + "api_server": { | |
| 91 | + "enabled": false, | |
| 92 | + "listen_ip_address": "127.0.0.1", | |
| 93 | + "listen_port": 8080, | |
| 94 | + "verbosity": "info", | |
| 95 | + "jwt_secret_key": "somethingrandom", | |
| 96 | + "CORS_origins": [], | |
| 97 | + "username": "", | |
| 98 | + "password": "" | |
| 99 | + }, | |
| 100 | + "bot_name": "freqtrade", | |
| 101 | + "initial_state": "running", | |
| 102 | + "forcebuy_enable": false, | |
| 103 | + "internals": { | |
| 104 | + "process_throttle_secs": 5 | |
| 105 | + } | |
| 106 | +} |
added config-backtest-USD.json +140 −0
| @@ -0,0 +1,140 @@ | ||
| 1 | +{ | |
| 2 | + "max_open_trades": 20, | |
| 3 | + "stake_currency": "USD", | |
| 4 | + "stake_amount": "unlimited", | |
| 5 | + "tradable_balance_ratio": 0.95, | |
| 6 | + "fiat_display_currency": "USD", | |
| 7 | + "dry_run": true, | |
| 8 | + "dry_run_wallet": 1000.00, | |
| 9 | + "cancel_open_orders_on_exit": false, | |
| 10 | + "order_types": { | |
| 11 | + "buy": "limit", | |
| 12 | + "sell": "limit", | |
| 13 | + "emergencysell": "market", | |
| 14 | + "stoploss": "market", | |
| 15 | + "stoploss_on_exchange": true, | |
| 16 | + "stoploss_on_exchange_interval": 60, | |
| 17 | + "stoploss_on_exchange_limit_ratio": 0.99 | |
| 18 | + }, | |
| 19 | + "order_time_in_force": { | |
| 20 | + "buy": "gtc", | |
| 21 | + "sell": "gtc" | |
| 22 | + }, | |
| 23 | + "bid_strategy": { | |
| 24 | + "price_side": "bid", | |
| 25 | + "ask_last_balance": 0.0, | |
| 26 | + "use_order_book": false, | |
| 27 | + "order_book_top": 1, | |
| 28 | + "check_depth_of_market": { | |
| 29 | + "enabled": false, | |
| 30 | + "bids_to_ask_delta": 1 | |
| 31 | + } | |
| 32 | + }, | |
| 33 | + "ask_strategy": { | |
| 34 | + "price_side": "ask", | |
| 35 | + "use_order_book": false, | |
| 36 | + "order_book_min": 1, | |
| 37 | + "order_book_max": 1 | |
| 38 | + }, | |
| 39 | + "download_trades": true, | |
| 40 | + "exchange": { | |
| 41 | + "name": "kraken", | |
| 42 | + "key": "", | |
| 43 | + "secret": "", | |
| 44 | + "ccxt_config": {"enableRateLimit": true}, | |
| 45 | + "ccxt_async_config": { | |
| 46 | + "enableRateLimit": true, | |
| 47 | + "rateLimit": 3100 | |
| 48 | + }, | |
| 49 | + "pair_whitelist": [ | |
| 50 | + "ETH/USD", | |
| 51 | + "ADA/USD", | |
| 52 | + "DOT/USD", | |
| 53 | + "LINK/USD", | |
| 54 | + "LTC/USD", | |
| 55 | + "BCH/USD", | |
| 56 | + "FLOW/USD", | |
| 57 | + "MANA/USD", | |
| 58 | + "XLM/USD", | |
| 59 | + "XMR/USD", | |
| 60 | + "KSM/USD", | |
| 61 | + "UNI/USD", | |
| 62 | + "ALGO/USD", | |
| 63 | + "ATOM/USD", | |
| 64 | + "XTZ/USD", | |
| 65 | + "GRT/USD", | |
| 66 | + "OCEAN/USD", | |
| 67 | + "FIL/USD", | |
| 68 | + "EOS/USD", | |
| 69 | + "DASH/USD", | |
| 70 | + "OXT/USD", | |
| 71 | + "KEEP/USD", | |
| 72 | + "NANO/USD", | |
| 73 | + "OMG/USD", | |
| 74 | + "TRX/USD", | |
| 75 | + "COMP/USD", | |
| 76 | + "BAT/USD", | |
| 77 | + "SNX/USD", | |
| 78 | + "CRV/USD", | |
| 79 | + "ZEC/USD", | |
| 80 | + "ICX/USD", | |
| 81 | + "QTUM/USD", | |
| 82 | + "SC/USD", | |
| 83 | + "KAVA/USD", | |
| 84 | + "BAL/USD", | |
| 85 | + "WAVES/USD", | |
| 86 | + "REP/USD", | |
| 87 | + "EWT/USD", | |
| 88 | + "STORJ/USD", | |
| 89 | + "LSK/USD", | |
| 90 | + "MLN/USD", | |
| 91 | + "REPV1/USD", | |
| 92 | + "ANT/USD", | |
| 93 | + "GNO/USD", | |
| 94 | + "YFI/USD", | |
| 95 | + "AAVE/USD", | |
| 96 | + "ETC/USD", | |
| 97 | + "KNC/USD" | |
| 98 | + ], | |
| 99 | + "pair_blacklist": [ | |
| 100 | + "DOGE/USD", | |
| 101 | + "TBTC/USD", | |
| 102 | + "XRP/USD", | |
| 103 | + "DAI/USD", | |
| 104 | + "PAXG/USD", | |
| 105 | + "USDT/USD", | |
| 106 | + "USDC/USD", | |
| 107 | + "EUR/USD", | |
| 108 | + "GBP/USD", | |
| 109 | + "AUD/USD", | |
| 110 | + "CAD/USD", | |
| 111 | + "CHF/USD", | |
| 112 | + "JPY/USD", | |
| 113 | + "BTC/USD" | |
| 114 | + ] | |
| 115 | + }, | |
| 116 | + "pairlists": [ | |
| 117 | + {"method": "StaticPairList"} | |
| 118 | + ], | |
| 119 | + "telegram": { | |
| 120 | + "enabled": true, | |
| 121 | + "token": "", | |
| 122 | + "chat_id": "" | |
| 123 | + }, | |
| 124 | + "api_server": { | |
| 125 | + "enabled": false, | |
| 126 | + "listen_ip_address": "127.0.0.1", | |
| 127 | + "listen_port": 8080, | |
| 128 | + "verbosity": "info", | |
| 129 | + "jwt_secret_key": "somethingrandom", | |
| 130 | + "CORS_origins": [], | |
| 131 | + "username": "", | |
| 132 | + "password": "" | |
| 133 | + }, | |
| 134 | + "bot_name": "freqtrade", | |
| 135 | + "initial_state": "running", | |
| 136 | + "forcebuy_enable": false, | |
| 137 | + "internals": { | |
| 138 | + "process_throttle_secs": 5 | |
| 139 | + } | |
| 140 | +} |
added config-download-ALL.json +239 −0
| @@ -0,0 +1,239 @@ | ||
| 1 | +{ | |
| 2 | + "max_open_trades": 3, | |
| 3 | + "stake_currency": "BTC", | |
| 4 | + "stake_amount": 0.001, | |
| 5 | + "tradable_balance_ratio": 0.95, | |
| 6 | + "fiat_display_currency": "USD", | |
| 7 | + "dry_run": true, | |
| 8 | + "dry_run_wallet": 0.005, | |
| 9 | + "cancel_open_orders_on_exit": false, | |
| 10 | + "order_types": { | |
| 11 | + "buy": "limit", | |
| 12 | + "sell": "limit", | |
| 13 | + "emergencysell": "market", | |
| 14 | + "stoploss": "market", | |
| 15 | + "stoploss_on_exchange": true, | |
| 16 | + "stoploss_on_exchange_interval": 60, | |
| 17 | + "stoploss_on_exchange_limit_ratio": 0.99 | |
| 18 | + }, | |
| 19 | + "order_time_in_force": { | |
| 20 | + "buy": "gtc", | |
| 21 | + "sell": "gtc" | |
| 22 | + }, | |
| 23 | + "bid_strategy": { | |
| 24 | + "price_side": "bid", | |
| 25 | + "ask_last_balance": 0.0, | |
| 26 | + "use_order_book": false, | |
| 27 | + "order_book_top": 1, | |
| 28 | + "check_depth_of_market": { | |
| 29 | + "enabled": false, | |
| 30 | + "bids_to_ask_delta": 1 | |
| 31 | + } | |
| 32 | + }, | |
| 33 | + "ask_strategy": { | |
| 34 | + "price_side": "ask", | |
| 35 | + "use_order_book": false, | |
| 36 | + "order_book_min": 1, | |
| 37 | + "order_book_max": 1 | |
| 38 | + }, | |
| 39 | + "download_trades": true, | |
| 40 | + "exchange": { | |
| 41 | + "name": "kraken", | |
| 42 | + "key": "", | |
| 43 | + "secret": "", | |
| 44 | + "ccxt_config": {"enableRateLimit": true}, | |
| 45 | + "ccxt_async_config": { | |
| 46 | + "enableRateLimit": true, | |
| 47 | + "rateLimit": 3100 | |
| 48 | + }, | |
| 49 | + "pair_whitelist": [ | |
| 50 | + "ETH/BTC", | |
| 51 | + "ADA/BTC", | |
| 52 | + "DOT/BTC", | |
| 53 | + "FLOW/BTC", | |
| 54 | + "MANA/BTC", | |
| 55 | + "LTC/BTC", | |
| 56 | + "UNI/BTC", | |
| 57 | + "KSM/BTC", | |
| 58 | + "LINK/BTC", | |
| 59 | + "XMR/BTC", | |
| 60 | + "ATOM/BTC", | |
| 61 | + "XLM/BTC", | |
| 62 | + "XTZ/BTC", | |
| 63 | + "ALGO/BTC", | |
| 64 | + "GRT/BTC", | |
| 65 | + "BCH/BTC", | |
| 66 | + "NANO/BTC", | |
| 67 | + "AAVE/BTC", | |
| 68 | + "EOS/BTC", | |
| 69 | + "BAT/BTC", | |
| 70 | + "ICX/BTC", | |
| 71 | + "OCEAN/BTC", | |
| 72 | + "KEEP/BTC", | |
| 73 | + "REP/BTC", | |
| 74 | + "DASH/BTC", | |
| 75 | + "SC/BTC", | |
| 76 | + "YFI/BTC", | |
| 77 | + "OXT/BTC", | |
| 78 | + "CRV/BTC", | |
| 79 | + "EWT/BTC", | |
| 80 | + "COMP/BTC", | |
| 81 | + "TRX/BTC", | |
| 82 | + "SNX/BTC", | |
| 83 | + "KAVA/BTC", | |
| 84 | + "LSK/BTC", | |
| 85 | + "BAL/BTC", | |
| 86 | + "ZEC/BTC", | |
| 87 | + "WAVES/BTC", | |
| 88 | + "KNC/BTC", | |
| 89 | + "OMG/BTC", | |
| 90 | + "FIL/BTC", | |
| 91 | + "ANT/BTC", | |
| 92 | + "GNO/BTC", | |
| 93 | + "REPV1/BTC", | |
| 94 | + "ETC/BTC", | |
| 95 | + "QTUM/BTC", | |
| 96 | + "STORJ/BTC", | |
| 97 | + "MLN/BTC", | |
| 98 | + "ADA/ETH", | |
| 99 | + "DOT/ETH", | |
| 100 | + "FLOW/ETH", | |
| 101 | + "LINK/ETH", | |
| 102 | + "KSM/ETH", | |
| 103 | + "AAVE/ETH", | |
| 104 | + "MANA/ETH", | |
| 105 | + "ALGO/ETH", | |
| 106 | + "LTC/ETH", | |
| 107 | + "UNI/ETH", | |
| 108 | + "XTZ/ETH", | |
| 109 | + "GRT/ETH", | |
| 110 | + "ATOM/ETH", | |
| 111 | + "KEEP/ETH", | |
| 112 | + "GNO/ETH", | |
| 113 | + "COMP/ETH", | |
| 114 | + "SNX/ETH", | |
| 115 | + "EOS/ETH", | |
| 116 | + "TRX/ETH", | |
| 117 | + "NANO/ETH", | |
| 118 | + "BCH/ETH", | |
| 119 | + "OXT/ETH", | |
| 120 | + "KAVA/ETH", | |
| 121 | + "REP/ETH", | |
| 122 | + "CRV/ETH", | |
| 123 | + "SC/ETH", | |
| 124 | + "QTUM/ETH", | |
| 125 | + "ICX/ETH", | |
| 126 | + "BAT/ETH", | |
| 127 | + "YFI/ETH", | |
| 128 | + "FIL/ETH", | |
| 129 | + "KNC/ETH", | |
| 130 | + "MLN/ETH", | |
| 131 | + "ETC/ETH", | |
| 132 | + "BAL/ETH", | |
| 133 | + "OMG/ETH", | |
| 134 | + "ANT/ETH", | |
| 135 | + "WAVES/ETH", | |
| 136 | + "LSK/ETH", | |
| 137 | + "REPV1/ETH", | |
| 138 | + "STORJ/ETH", | |
| 139 | + "BTC/USD", | |
| 140 | + "ETH/USD", | |
| 141 | + "ADA/USD", | |
| 142 | + "DOT/USD", | |
| 143 | + "LINK/USD", | |
| 144 | + "LTC/USD", | |
| 145 | + "BCH/USD", | |
| 146 | + "FLOW/USD", | |
| 147 | + "MANA/USD", | |
| 148 | + "XLM/USD", | |
| 149 | + "XMR/USD", | |
| 150 | + "KSM/USD", | |
| 151 | + "UNI/USD", | |
| 152 | + "ALGO/USD", | |
| 153 | + "ATOM/USD", | |
| 154 | + "XTZ/USD", | |
| 155 | + "GRT/USD", | |
| 156 | + "AAVE/USD", | |
| 157 | + "OCEAN/USD", | |
| 158 | + "FIL/USD", | |
| 159 | + "EOS/USD", | |
| 160 | + "DASH/USD", | |
| 161 | + "YFI/USD", | |
| 162 | + "OXT/USD", | |
| 163 | + "KEEP/USD", | |
| 164 | + "NANO/USD", | |
| 165 | + "OMG/USD", | |
| 166 | + "TRX/USD", | |
| 167 | + "COMP/USD", | |
| 168 | + "BAT/USD", | |
| 169 | + "SNX/USD", | |
| 170 | + "CRV/USD", | |
| 171 | + "ZEC/USD", | |
| 172 | + "ICX/USD", | |
| 173 | + "QTUM/USD", | |
| 174 | + "ETC/USD", | |
| 175 | + "KNC/USD", | |
| 176 | + "SC/USD", | |
| 177 | + "KAVA/USD", | |
| 178 | + "BAL/USD", | |
| 179 | + "WAVES/USD", | |
| 180 | + "REP/USD", | |
| 181 | + "EWT/USD", | |
| 182 | + "STORJ/USD", | |
| 183 | + "LSK/USD", | |
| 184 | + "MLN/USD", | |
| 185 | + "REPV1/USD", | |
| 186 | + "ANT/USD", | |
| 187 | + "GNO/USD" | |
| 188 | + ], | |
| 189 | + "pair_blacklist": [ | |
| 190 | + "DOGE/BTC", | |
| 191 | + "XRP/BTC", | |
| 192 | + "DAI/BTC", | |
| 193 | + "PAXG/BTC", | |
| 194 | + "TBTC/BTC", | |
| 195 | + "XRP/ETH", | |
| 196 | + "ETH2/ETH", | |
| 197 | + "ETH2.S/ETH", | |
| 198 | + "PAXG/ETH", | |
| 199 | + "TBTC/ETH", | |
| 200 | + "DOGE/USD", | |
| 201 | + "TBTC/USD", | |
| 202 | + "XRP/USD", | |
| 203 | + "DAI/USD", | |
| 204 | + "PAXG/USD", | |
| 205 | + "USDT/USD", | |
| 206 | + "USDC/USD", | |
| 207 | + "EUR/USD", | |
| 208 | + "GBP/USD", | |
| 209 | + "AUD/USD", | |
| 210 | + "CAD/USD", | |
| 211 | + "CHF/USD", | |
| 212 | + "JPY/USD" | |
| 213 | + ] | |
| 214 | + }, | |
| 215 | + "pairlists": [ | |
| 216 | + {"method": "StaticPairList"} | |
| 217 | + ], | |
| 218 | + "telegram": { | |
| 219 | + "enabled": true, | |
| 220 | + "token": "", | |
| 221 | + "chat_id": "" | |
| 222 | + }, | |
| 223 | + "api_server": { | |
| 224 | + "enabled": false, | |
| 225 | + "listen_ip_address": "127.0.0.1", | |
| 226 | + "listen_port": 8080, | |
| 227 | + "verbosity": "info", | |
| 228 | + "jwt_secret_key": "somethingrandom", | |
| 229 | + "CORS_origins": [], | |
| 230 | + "username": "", | |
| 231 | + "password": "" | |
| 232 | + }, | |
| 233 | + "bot_name": "freqtrade", | |
| 234 | + "initial_state": "running", | |
| 235 | + "forcebuy_enable": false, | |
| 236 | + "internals": { | |
| 237 | + "process_throttle_secs": 5 | |
| 238 | + } | |
| 239 | +} |
added hyperopts/SolipsisHyp_v3.py +220 −0
| @@ -0,0 +1,220 @@ | ||
| 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 | + # Base Timeframe | |
| 72 | + conditions.append( | |
| 73 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 74 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 75 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 76 | + (dataframe['mp'] <= params['base-mp']) | |
| 77 | + ) | |
| 78 | + | |
| 79 | + if stake_currency in ('BTC', 'ETH'): | |
| 80 | + conditions.append( | |
| 81 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 82 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 83 | + ) | |
| 84 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 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 | + @staticmethod | |
| 154 | + def generate_dynamic_roi(params: Dict) -> Dict[int, float]: | |
| 155 | + | |
| 156 | + dynamic_roi = { | |
| 157 | + 'enabled': params['droi_enabled'], | |
| 158 | + 'profit-factor': params['droi_profit_factor'], | |
| 159 | + 'rmi-start': params['droi_rmi_start'], | |
| 160 | + 'rmi-end': params['droi_rmi_end'], | |
| 161 | + 'grow-delay': params['droi_grow_delay'], | |
| 162 | + 'grow-time': params['droi_grow_time'], | |
| 163 | + 'fallback': params['droi_fallback'], | |
| 164 | + 'min-roc-atr': params['droi_min_roc_atr'] | |
| 165 | + } | |
| 166 | + | |
| 167 | + return dynamic_roi | |
| 168 | + | |
| 169 | + @staticmethod | |
| 170 | + def dynamic_roi_space() -> List[Dimension]: | |
| 171 | + | |
| 172 | + return [ | |
| 173 | + Categorical([True], name='droi_enabled'), | |
| 174 | + Integer(200, 500, name='droi_profit_factor'), | |
| 175 | + Integer(0, 50, name='droi_rmi_start'), | |
| 176 | + Integer(50, 90, name='droi_rmi_end'), | |
| 177 | + Integer(0, 180, name='droi_grow_delay'), | |
| 178 | + Integer(360, 1440, name='droi_grow_time'), | |
| 179 | + Categorical(['table', 'atr', 'roc', 'roc-table', 'atr-table'], name='droi_fallback'), | |
| 180 | + Real(0.0, 0.015, name='droi_min_roc_atr') | |
| 181 | + ] | |
| 182 | + | |
| 183 | + | |
| 184 | + @staticmethod | |
| 185 | + def generate_custom_stop(params: Dict) -> Dict[int, float]: | |
| 186 | + | |
| 187 | + custom_stop = { | |
| 188 | + 'decay-time': params['cstp_decay_time'], | |
| 189 | + 'decay-delay': params['cstp_decay_delay'], | |
| 190 | + 'decay-start': params['cstp_decay_start'], | |
| 191 | + 'decay-end': params['cstp_decay_end'], | |
| 192 | + 'cur-min-diff': params['cstp_cur_min_diff'], | |
| 193 | + 'cur-threshold': params['cstp_cur_threshold'], | |
| 194 | + 'roc-bail': params['cstp_roc_bail'], | |
| 195 | + 'rmi-trend': params['cstp_rmi_trend'], | |
| 196 | + 'bail-how': params['cstp_bail_how'], | |
| 197 | + 'pos-trail': params['cstp_pos_trail'], | |
| 198 | + 'pos-threshold': params['cstp_pos_threshold'], | |
| 199 | + 'pos-trail-dist': params['cstp_trail_dist'] | |
| 200 | + } | |
| 201 | + | |
| 202 | + return custom_stop | |
| 203 | + | |
| 204 | + @staticmethod | |
| 205 | + def custom_stoploss_space() -> List[Dimension]: | |
| 206 | + | |
| 207 | + return [ | |
| 208 | + Integer(500, 1440, name='cstp_decay_time'), | |
| 209 | + Integer(0, 360, name='cstp_decay_delay'), | |
| 210 | + Real(-0.30, -0.20, name='cstp_decay_start'), | |
| 211 | + Real(-0.05, 0, name='cstp_decay_end'), | |
| 212 | + Real(0.01, 0.04, name='cstp_cur_min_diff'), | |
| 213 | + Real(-0.05, 0, name='cstp_cur_threshold'), | |
| 214 | + Real(-0.05, 0, name='cstp_roc_bail'), | |
| 215 | + Integer(30, 70, name='cstp_rmi_trend'), | |
| 216 | + Categorical(['atr', 'immediate'], name='cstp_bail_how'), | |
| 217 | + Categorical([True, False], name='cstp_pos_trail'), | |
| 218 | + Real(0.0, 0.03, name='cstp_pos_threshold'), | |
| 219 | + Real(0.005, 0.03, name='cstp_trail_dist') | |
| 220 | + ] | |
| No newline at the end of the file |
added hyperopts/old/BinHV45HyperOpt.py +97 −0
| @@ -0,0 +1,97 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | + | |
| 20 | +class BinHV45HyperOpt(IHyperOpt): | |
| 21 | + """ | |
| 22 | + Hyperopt file for optimizing BinHV45Strategy. | |
| 23 | + Uses ranges to find best parameter combination for bbdelta, closedelta and tail | |
| 24 | + of the buy strategy. | |
| 25 | + | |
| 26 | + Sell strategy is ignored, because it's ignored in BinHV45Strategy as well. | |
| 27 | + This strategy therefor works without explicit sell signal therefor hyperopting | |
| 28 | + for 'roi' is recommend as well | |
| 29 | + | |
| 30 | + Also, this is just ONE way to optimize this strategy - others might also include | |
| 31 | + disabling certain conditions completely. This file is just a starting point, feel free | |
| 32 | + to improve and PR. | |
| 33 | + """ | |
| 34 | + | |
| 35 | + @staticmethod | |
| 36 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 37 | + """ | |
| 38 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 39 | + """ | |
| 40 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 41 | + """ | |
| 42 | + Buy strategy Hyperopt will build and use. | |
| 43 | + """ | |
| 44 | + conditions = [] | |
| 45 | + | |
| 46 | + conditions.append(dataframe['lower'].shift().gt(0)) | |
| 47 | + conditions.append(dataframe['bbdelta'].gt( | |
| 48 | + dataframe['close'] * params['bbdelta'] / 1000)) | |
| 49 | + conditions.append(dataframe['closedelta'].gt( | |
| 50 | + dataframe['close'] * params['closedelta'] / 1000)) | |
| 51 | + conditions.append(dataframe['tail'].lt(dataframe['bbdelta'] * params['tail'] / 1000)) | |
| 52 | + conditions.append(dataframe['close'].lt(dataframe['lower'].shift())) | |
| 53 | + conditions.append(dataframe['close'].le(dataframe['close'].shift())) | |
| 54 | + | |
| 55 | + # Check that the candle had volume | |
| 56 | + conditions.append(dataframe['volume'] > 0) | |
| 57 | + | |
| 58 | + if conditions: | |
| 59 | + dataframe.loc[ | |
| 60 | + reduce(lambda x, y: x & y, conditions), | |
| 61 | + 'buy'] = 1 | |
| 62 | + | |
| 63 | + return dataframe | |
| 64 | + | |
| 65 | + return populate_buy_trend | |
| 66 | + | |
| 67 | + @staticmethod | |
| 68 | + def indicator_space() -> List[Dimension]: | |
| 69 | + """ | |
| 70 | + Define your Hyperopt space for searching buy strategy parameters. | |
| 71 | + """ | |
| 72 | + return [ | |
| 73 | + Integer(1, 15, name='bbdelta'), | |
| 74 | + Integer(15, 20, name='closedelta'), | |
| 75 | + Integer(20, 30, name='tail'), | |
| 76 | + ] | |
| 77 | + | |
| 78 | + @staticmethod | |
| 79 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 80 | + """ | |
| 81 | + Define the sell strategy parameters to be used by Hyperopt. | |
| 82 | + """ | |
| 83 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 84 | + """ | |
| 85 | + no sell signal | |
| 86 | + """ | |
| 87 | + dataframe['sell'] = 0 | |
| 88 | + return dataframe | |
| 89 | + | |
| 90 | + return populate_sell_trend | |
| 91 | + | |
| 92 | + @staticmethod | |
| 93 | + def sell_indicator_space() -> List[Dimension]: | |
| 94 | + """ | |
| 95 | + Define your Hyperopt space for searching sell strategy parameters. | |
| 96 | + """ | |
| 97 | + return [] |
added hyperopts/old/Cluc4werkHyperopt.py +257 −0
| @@ -0,0 +1,257 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class Cluc4werkHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + OVERRIDE THESE AT THE BOTTOM FOR SPECIFIC STAKES | |
| 25 | + """ | |
| 26 | + | |
| 27 | + # Buy hyperspace params: | |
| 28 | + buy_params = { | |
| 29 | + 'bbdelta-close': 0.00793, | |
| 30 | + 'bbdelta-tail': 0.83802, | |
| 31 | + 'close-bblower': 0.0034, | |
| 32 | + 'closedelta-close': 0.00613, | |
| 33 | + 'rocr-1h': 0.64081, | |
| 34 | + 'volume': 21 | |
| 35 | + } | |
| 36 | + | |
| 37 | + # Sell hyperspace params: | |
| 38 | + sell_params = { | |
| 39 | + 'sell-bbmiddle-close': 0.97703 | |
| 40 | + } | |
| 41 | + | |
| 42 | + @staticmethod | |
| 43 | + def indicator_space() -> List[Dimension]: | |
| 44 | + return [ | |
| 45 | + Real(0.5, 1.0, name='rocr-1h'), | |
| 46 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 47 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 48 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 49 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 50 | + Integer(15, 40, name='volume') | |
| 51 | + ] | |
| 52 | + | |
| 53 | + @staticmethod | |
| 54 | + def sell_indicator_space() -> List[Dimension]: | |
| 55 | + return [ | |
| 56 | + Real(0.97, 1.1, name='sell-bbmiddle-close') | |
| 57 | + ] | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + """ | |
| 62 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 63 | + """ | |
| 64 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 65 | + """ | |
| 66 | + Buy strategy Hyperopt will build and use. | |
| 67 | + """ | |
| 68 | + dataframe.loc[ | |
| 69 | + ( | |
| 70 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 71 | + ) & | |
| 72 | + (( | |
| 73 | + dataframe['lower'].shift().gt(0) & | |
| 74 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 75 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 76 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 77 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 78 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 79 | + ) | | |
| 80 | + ( | |
| 81 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 82 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 83 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 84 | + )), | |
| 85 | + 'buy' | |
| 86 | + ] = 1 | |
| 87 | + return dataframe | |
| 88 | + | |
| 89 | + return populate_buy_trend | |
| 90 | + | |
| 91 | + @staticmethod | |
| 92 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 93 | + """ | |
| 94 | + Define the sell strategy parameters to be used by hyperopt | |
| 95 | + """ | |
| 96 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 97 | + | |
| 98 | + dataframe.loc[ | |
| 99 | + (dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 100 | + (dataframe['high'].shift(1).le(dataframe['high'].shift(2))) & | |
| 101 | + (dataframe['close'].le(dataframe['close'].shift(1))) & | |
| 102 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 103 | + (dataframe['volume'] > 0) | |
| 104 | + , | |
| 105 | + 'sell' | |
| 106 | + ] = 1 | |
| 107 | + | |
| 108 | + """ | |
| 109 | + dataframe.loc[ | |
| 110 | + #(dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 111 | + #(dataframe['close'] > dataframe['bb_middleband']) & | |
| 112 | + (qtpylib.crossed_above((dataframe['close'] * params['sell-bbmiddle-close']),dataframe['bb_middleband'])) & | |
| 113 | + #(qtpylib.crossed_above(dataframe['close'],dataframe['bb_middleband'])) & | |
| 114 | + (dataframe['volume'] > 0) | |
| 115 | + , | |
| 116 | + 'sell' | |
| 117 | + ] = 1 | |
| 118 | + """ | |
| 119 | + | |
| 120 | + return dataframe | |
| 121 | + | |
| 122 | + return populate_sell_trend | |
| 123 | + | |
| 124 | + | |
| 125 | + @staticmethod | |
| 126 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 127 | + | |
| 128 | + roi_table = {} | |
| 129 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 130 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 131 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 132 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 133 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 134 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 135 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 136 | + | |
| 137 | + return roi_table | |
| 138 | + | |
| 139 | + @staticmethod | |
| 140 | + def roi_space() -> List[Dimension]: | |
| 141 | + | |
| 142 | + return [ | |
| 143 | + Integer(1, 300, name='roi_t6'), | |
| 144 | + Integer(1, 300, name='roi_t5'), | |
| 145 | + Integer(1, 300, name='roi_t4'), | |
| 146 | + Integer(1, 300, name='roi_t3'), | |
| 147 | + Integer(1, 300, name='roi_t2'), | |
| 148 | + Integer(1, 300, name='roi_t1'), | |
| 149 | + | |
| 150 | + Real(0.001, 0.005, name='roi_p6'), | |
| 151 | + Real(0.001, 0.005, name='roi_p5'), | |
| 152 | + Real(0.001, 0.005, name='roi_p4'), | |
| 153 | + Real(0.001, 0.005, name='roi_p3'), | |
| 154 | + Real(0.0001, 0.005, name='roi_p2'), | |
| 155 | + Real(0.0001, 0.005, name='roi_p1'), | |
| 156 | + ] | |
| 157 | + | |
| 158 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 159 | + params = self.buy_params | |
| 160 | + | |
| 161 | + dataframe.loc[ | |
| 162 | + ( | |
| 163 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 164 | + ) & | |
| 165 | + (( | |
| 166 | + dataframe['lower'].shift().gt(0) & | |
| 167 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 168 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 169 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 170 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 171 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 172 | + ) | | |
| 173 | + ( | |
| 174 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 175 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 176 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 177 | + )), | |
| 178 | + 'buy' | |
| 179 | + ] = 1 | |
| 180 | + return dataframe | |
| 181 | + | |
| 182 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 183 | + params = self.sell_params | |
| 184 | + | |
| 185 | + dataframe.loc[ | |
| 186 | + (dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 187 | + (dataframe['high'].shift(1).le(dataframe['high'].shift(2))) & | |
| 188 | + (dataframe['close'].le(dataframe['close'].shift(1))) & | |
| 189 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 190 | + (dataframe['volume'] > 0) | |
| 191 | + , | |
| 192 | + 'sell' | |
| 193 | + ] = 1 | |
| 194 | + | |
| 195 | + """ | |
| 196 | + dataframe.loc[ | |
| 197 | + #(dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 198 | + #(dataframe['close'] > dataframe['bb_middleband']) & | |
| 199 | + (qtpylib.crossed_above((dataframe['close'] * params['sell-bbmiddle-close']),dataframe['bb_middleband'])) & | |
| 200 | + #(qtpylib.crossed_above(dataframe['close'],dataframe['bb_middleband'])) & | |
| 201 | + (dataframe['volume'] > 0) | |
| 202 | + , | |
| 203 | + 'sell' | |
| 204 | + ] = 1 | |
| 205 | + """ | |
| 206 | + return dataframe | |
| 207 | + | |
| 208 | +class Cluc4werkHyperopt_ETH(Cluc4werkHyperopt): | |
| 209 | + | |
| 210 | + # Buy hyperspace params: | |
| 211 | + buy_params = { | |
| 212 | + 'bbdelta-close': 0.00793, | |
| 213 | + 'bbdelta-tail': 0.83802, | |
| 214 | + 'close-bblower': 0.0034, | |
| 215 | + 'closedelta-close': 0.00613, | |
| 216 | + 'rocr-1h': 0.64081, | |
| 217 | + 'volume': 21 | |
| 218 | + } | |
| 219 | + | |
| 220 | + # Sell hyperspace params: | |
| 221 | + sell_params = { | |
| 222 | + 'sell-bbmiddle-close': 0.97703 | |
| 223 | + } | |
| 224 | + | |
| 225 | +class Cluc4werkHyperopt_BTC(Cluc4werkHyperopt): | |
| 226 | + | |
| 227 | + # Buy hyperspace params: | |
| 228 | + buy_params = { | |
| 229 | + 'bbdelta-close': 0.00793, | |
| 230 | + 'bbdelta-tail': 0.83802, | |
| 231 | + 'close-bblower': 0.0034, | |
| 232 | + 'closedelta-close': 0.00613, | |
| 233 | + 'rocr-1h': 0.64081, | |
| 234 | + 'volume': 21 | |
| 235 | + } | |
| 236 | + | |
| 237 | + # Sell hyperspace params: | |
| 238 | + sell_params = { | |
| 239 | + 'sell-bbmiddle-close': 0.97703 | |
| 240 | + } | |
| 241 | + | |
| 242 | +class Cluc4werkHyperopt_USD(Cluc4werkHyperopt): | |
| 243 | + | |
| 244 | + # Buy hyperspace params: | |
| 245 | + buy_params = { | |
| 246 | + 'bbdelta-close': 0.00793, | |
| 247 | + 'bbdelta-tail': 0.83802, | |
| 248 | + 'close-bblower': 0.0034, | |
| 249 | + 'closedelta-close': 0.00613, | |
| 250 | + 'rocr-1h': 0.64081, | |
| 251 | + 'volume': 21 | |
| 252 | + } | |
| 253 | + | |
| 254 | + # Sell hyperspace params: | |
| 255 | + sell_params = { | |
| 256 | + 'sell-bbmiddle-close': 0.97703 | |
| 257 | + } | |
| No newline at the end of the file |
added hyperopts/old/Cluc5werkHyperopt.py +256 −0
| @@ -0,0 +1,256 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class Cluc5werkHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + OVERRIDE THESE AT THE BOTTOM FOR SPECIFIC STAKES | |
| 25 | + """ | |
| 26 | + | |
| 27 | + # Buy hyperspace params: | |
| 28 | + buy_params = { | |
| 29 | + 'bbdelta-close': 0.01511, | |
| 30 | + 'bbdelta-tail': 0.90705, | |
| 31 | + 'close-bblower': 0.01972, | |
| 32 | + 'closedelta-close': 0.00099, | |
| 33 | + 'rocr-1h': 0.97131, | |
| 34 | + 'volume': 27 | |
| 35 | + } | |
| 36 | + | |
| 37 | + # Sell hyperspace params: | |
| 38 | + sell_params = { | |
| 39 | + 'sell-bbmiddle-close': 0.97906 | |
| 40 | + } | |
| 41 | + | |
| 42 | + @staticmethod | |
| 43 | + def indicator_space() -> List[Dimension]: | |
| 44 | + return [ | |
| 45 | + Real(0.5, 1.0, name='rocr-1h'), | |
| 46 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 47 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 48 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 49 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 50 | + Integer(15, 40, name='volume') | |
| 51 | + ] | |
| 52 | + | |
| 53 | + @staticmethod | |
| 54 | + def sell_indicator_space() -> List[Dimension]: | |
| 55 | + return [ | |
| 56 | + Real(0.97, 1.1, name='sell-bbmiddle-close') | |
| 57 | + ] | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + """ | |
| 62 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 63 | + """ | |
| 64 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 65 | + """ | |
| 66 | + Buy strategy Hyperopt will build and use. | |
| 67 | + """ | |
| 68 | + dataframe.loc[ | |
| 69 | + ( | |
| 70 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 71 | + ) & | |
| 72 | + (( | |
| 73 | + dataframe['lower'].shift().gt(0) & | |
| 74 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 75 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 76 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 77 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 78 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 79 | + ) | | |
| 80 | + ( | |
| 81 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 82 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 83 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 84 | + )), | |
| 85 | + 'fake_buy' | |
| 86 | + ] = 1 | |
| 87 | + | |
| 88 | + dataframe.loc[ | |
| 89 | + (dataframe['fake_buy'].shift(1).eq(1)) & | |
| 90 | + (dataframe['fake_buy'].eq(1)) & | |
| 91 | + (dataframe['volume'] > 0) | |
| 92 | + , | |
| 93 | + 'buy' | |
| 94 | + ] = 1 | |
| 95 | + return dataframe | |
| 96 | + | |
| 97 | + return populate_buy_trend | |
| 98 | + | |
| 99 | + @staticmethod | |
| 100 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 101 | + """ | |
| 102 | + Define the sell strategy parameters to be used by hyperopt | |
| 103 | + """ | |
| 104 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 105 | + | |
| 106 | + dataframe.loc[ | |
| 107 | + (dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 108 | + (dataframe['high'].shift(1).le(dataframe['high'].shift(2))) & | |
| 109 | + (dataframe['close'].le(dataframe['close'].shift(1))) & | |
| 110 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 111 | + (dataframe['volume'] > 0) | |
| 112 | + , | |
| 113 | + 'sell' | |
| 114 | + ] = 1 | |
| 115 | + return dataframe | |
| 116 | + | |
| 117 | + return populate_sell_trend | |
| 118 | + | |
| 119 | + | |
| 120 | + @staticmethod | |
| 121 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 122 | + | |
| 123 | + roi_table = {} | |
| 124 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 125 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 126 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 127 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 128 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 129 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 130 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 131 | + | |
| 132 | + return roi_table | |
| 133 | + | |
| 134 | + @staticmethod | |
| 135 | + def roi_space() -> List[Dimension]: | |
| 136 | + | |
| 137 | + return [ | |
| 138 | + Integer(1, 300, name='roi_t6'), | |
| 139 | + Integer(1, 300, name='roi_t5'), | |
| 140 | + Integer(1, 300, name='roi_t4'), | |
| 141 | + Integer(1, 300, name='roi_t3'), | |
| 142 | + Integer(1, 300, name='roi_t2'), | |
| 143 | + Integer(1, 300, name='roi_t1'), | |
| 144 | + | |
| 145 | + Real(0.001, 0.005, name='roi_p6'), | |
| 146 | + Real(0.001, 0.005, name='roi_p5'), | |
| 147 | + Real(0.001, 0.005, name='roi_p4'), | |
| 148 | + Real(0.001, 0.005, name='roi_p3'), | |
| 149 | + Real(0.0001, 0.005, name='roi_p2'), | |
| 150 | + Real(0.0001, 0.005, name='roi_p1'), | |
| 151 | + ] | |
| 152 | + | |
| 153 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 154 | + params = self.buy_params | |
| 155 | + | |
| 156 | + dataframe.loc[ | |
| 157 | + ( | |
| 158 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 159 | + ) & | |
| 160 | + (( | |
| 161 | + dataframe['lower'].shift().gt(0) & | |
| 162 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 163 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 164 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 165 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 166 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 167 | + ) | | |
| 168 | + ( | |
| 169 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 170 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 171 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 172 | + )), | |
| 173 | + 'fake_buy' | |
| 174 | + ] = 1 | |
| 175 | + | |
| 176 | + dataframe.loc[ | |
| 177 | + (dataframe['fake_buy'].shift(1).eq(1)) & | |
| 178 | + (dataframe['fake_buy'].eq(1)) & | |
| 179 | + (dataframe['volume'] > 0) | |
| 180 | + , | |
| 181 | + 'buy' | |
| 182 | + ] = 1 | |
| 183 | + | |
| 184 | + return dataframe | |
| 185 | + | |
| 186 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 187 | + params = self.sell_params | |
| 188 | + | |
| 189 | + dataframe.loc[ | |
| 190 | + (dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 191 | + (dataframe['high'].shift(1).le(dataframe['high'].shift(2))) & | |
| 192 | + (dataframe['close'].le(dataframe['close'].shift(1))) & | |
| 193 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 194 | + (dataframe['volume'] > 0) | |
| 195 | + , | |
| 196 | + 'sell' | |
| 197 | + ] = 1 | |
| 198 | + | |
| 199 | + return dataframe | |
| 200 | + | |
| 201 | +class Cluc5werkHyperopt_BTC(Cluc5werkHyperopt): | |
| 202 | + | |
| 203 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_BTC -e 500 --spaces all --timeframe 1m --timerange 20210101- | |
| 204 | + # 125/500: 422 trades. 369/14/39 Wins/Draws/Losses. Avg profit 0.97%. Median profit 2.18%. Total profit 0.00408737 BTC ( 408.13Σ%). Avg duration 307.8 min. Objective: -0.36043 | |
| 205 | + # Buy hyperspace params: | |
| 206 | + buy_params = { | |
| 207 | + 'bbdelta-close': 0.01511, | |
| 208 | + 'bbdelta-tail': 0.90705, | |
| 209 | + 'close-bblower': 0.01972, | |
| 210 | + 'closedelta-close': 0.00099, | |
| 211 | + 'rocr-1h': 0.97131, | |
| 212 | + 'volume': 27 | |
| 213 | + } | |
| 214 | + | |
| 215 | + # Sell hyperspace params: | |
| 216 | + sell_params = { | |
| 217 | + 'sell-bbmiddle-close': 0.97906 | |
| 218 | + } | |
| 219 | + | |
| 220 | +class Cluc5werkHyperopt_USD(Cluc5werkHyperopt): | |
| 221 | + | |
| 222 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_BTC -e 500 --spaces all --timeframe 1m --timerange 20210101- | |
| 223 | + # 125/500: 422 trades. 369/14/39 Wins/Draws/Losses. Avg profit 0.97%. Median profit 2.18%. Total profit 0.00408737 BTC ( 408.13Σ%). Avg duration 307.8 min. Objective: -0.36043 | |
| 224 | + # Buy hyperspace params: | |
| 225 | + buy_params = { | |
| 226 | + 'bbdelta-close': 0.01511, | |
| 227 | + 'bbdelta-tail': 0.90705, | |
| 228 | + 'close-bblower': 0.01972, | |
| 229 | + 'closedelta-close': 0.00099, | |
| 230 | + 'rocr-1h': 0.97131, | |
| 231 | + 'volume': 27 | |
| 232 | + } | |
| 233 | + | |
| 234 | + # Sell hyperspace params: | |
| 235 | + sell_params = { | |
| 236 | + 'sell-bbmiddle-close': 0.97906 | |
| 237 | + } | |
| 238 | + | |
| 239 | +class Cluc5werkHyperopt_ETH(Cluc5werkHyperopt): | |
| 240 | + | |
| 241 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_BTC -e 500 --spaces all --timeframe 1m --timerange 20210101- | |
| 242 | + # 125/500: 422 trades. 369/14/39 Wins/Draws/Losses. Avg profit 0.97%. Median profit 2.18%. Total profit 0.00408737 BTC ( 408.13Σ%). Avg duration 307.8 min. Objective: -0.36043 | |
| 243 | + # Buy hyperspace params: | |
| 244 | + buy_params = { | |
| 245 | + 'bbdelta-close': 0.01511, | |
| 246 | + 'bbdelta-tail': 0.90705, | |
| 247 | + 'close-bblower': 0.01972, | |
| 248 | + 'closedelta-close': 0.00099, | |
| 249 | + 'rocr-1h': 0.97131, | |
| 250 | + 'volume': 27 | |
| 251 | + } | |
| 252 | + | |
| 253 | + # Sell hyperspace params: | |
| 254 | + sell_params = { | |
| 255 | + 'sell-bbmiddle-close': 0.97906 | |
| 256 | + } | |
| No newline at the end of the file |
added hyperopts/old/Cluc6werkHyperopt.py +323 −0
| @@ -0,0 +1,323 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class Cluc6werkHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + OVERRIDE THESE AT THE BOTTOM FOR SPECIFIC STAKES | |
| 25 | + """ | |
| 26 | + # Buy hyperspace params: | |
| 27 | + buy_params = { | |
| 28 | + 'bbdelta-close': 0.00309, | |
| 29 | + 'bbdelta-tail': 0.83332, | |
| 30 | + 'close-bblower': 0.0019, | |
| 31 | + 'closedelta-close': 0.01889, | |
| 32 | + 'adx': 30, | |
| 33 | + 'aroon': 50, | |
| 34 | + 'volume': 22 | |
| 35 | + } | |
| 36 | + | |
| 37 | + # Sell hyperspace params: | |
| 38 | + sell_params = { | |
| 39 | + 'sell-bbmiddle-close': 1.00125, | |
| 40 | + 'sell-fisher': -1.37474, | |
| 41 | + 'sell-adx': 30, | |
| 42 | + 'sell-aroon': 50 | |
| 43 | + } | |
| 44 | + | |
| 45 | + @staticmethod | |
| 46 | + def indicator_space() -> List[Dimension]: | |
| 47 | + return [ | |
| 48 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 49 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 50 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 51 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 52 | + Integer(15, 40, name='volume'), | |
| 53 | + Integer(10, 50, name='adx'), | |
| 54 | + Integer(30, 70, name='aroon') | |
| 55 | + ] | |
| 56 | + | |
| 57 | + @staticmethod | |
| 58 | + def sell_indicator_space() -> List[Dimension]: | |
| 59 | + return [ | |
| 60 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 61 | + Integer(10, 50, name='sell-adx'), | |
| 62 | + Integer(30, 70, name='sell-aroon') | |
| 63 | + ] | |
| 64 | + | |
| 65 | + @staticmethod | |
| 66 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 67 | + | |
| 68 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 69 | + | |
| 70 | + conditions = [] | |
| 71 | + | |
| 72 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 73 | + conditions.append( | |
| 74 | + ( | |
| 75 | + ( | |
| 76 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 77 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 78 | + ) | | |
| 79 | + ( | |
| 80 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 81 | + ) | |
| 82 | + ) & | |
| 83 | + ( | |
| 84 | + ( | |
| 85 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 86 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 87 | + ) | | |
| 88 | + ( | |
| 89 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 90 | + ) | |
| 91 | + ) | |
| 92 | + ) | |
| 93 | + | |
| 94 | + conditions.append( | |
| 95 | + ( | |
| 96 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 97 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 98 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 99 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 100 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 101 | + ) | | |
| 102 | + ( | |
| 103 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 104 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 105 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 106 | + ) | |
| 107 | + ) | |
| 108 | + | |
| 109 | + conditions.append(dataframe['volume'].gt(0)) | |
| 110 | + | |
| 111 | + if conditions: | |
| 112 | + dataframe.loc[ | |
| 113 | + reduce(lambda x, y: x & y, conditions), | |
| 114 | + 'buy'] = 1 | |
| 115 | + | |
| 116 | + return dataframe | |
| 117 | + | |
| 118 | + return populate_buy_trend | |
| 119 | + | |
| 120 | + @staticmethod | |
| 121 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 122 | + | |
| 123 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 124 | + | |
| 125 | + conditions = [] | |
| 126 | + | |
| 127 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 128 | + conditions.append( | |
| 129 | + ( | |
| 130 | + ( | |
| 131 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 132 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 133 | + ) | | |
| 134 | + ( | |
| 135 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 136 | + ) | |
| 137 | + ) & | |
| 138 | + ( | |
| 139 | + ( | |
| 140 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 141 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 142 | + ) | | |
| 143 | + ( | |
| 144 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 145 | + ) | |
| 146 | + ) | |
| 147 | + ) | |
| 148 | + | |
| 149 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 150 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 151 | + conditions.append(dataframe['volume'].gt(0)) | |
| 152 | + | |
| 153 | + if conditions: | |
| 154 | + dataframe.loc[ | |
| 155 | + reduce(lambda x, y: x & y, conditions), | |
| 156 | + 'sell'] = 1 | |
| 157 | + | |
| 158 | + return dataframe | |
| 159 | + | |
| 160 | + return populate_sell_trend | |
| 161 | + | |
| 162 | + | |
| 163 | + @staticmethod | |
| 164 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 165 | + | |
| 166 | + roi_table = {} | |
| 167 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 168 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 169 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 170 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 171 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 172 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 173 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 174 | + | |
| 175 | + return roi_table | |
| 176 | + | |
| 177 | + @staticmethod | |
| 178 | + def roi_space() -> List[Dimension]: | |
| 179 | + | |
| 180 | + return [ | |
| 181 | + Integer(1, 15, name='roi_t6'), | |
| 182 | + Integer(1, 45, name='roi_t5'), | |
| 183 | + Integer(1, 90, name='roi_t4'), | |
| 184 | + Integer(45, 120, name='roi_t3'), | |
| 185 | + Integer(45, 180, name='roi_t2'), | |
| 186 | + Integer(90, 300, name='roi_t1'), | |
| 187 | + | |
| 188 | + Real(0.005, 0.10, name='roi_p6'), | |
| 189 | + Real(0.005, 0.07, name='roi_p5'), | |
| 190 | + Real(0.005, 0.05, name='roi_p4'), | |
| 191 | + Real(0.005, 0.025, name='roi_p3'), | |
| 192 | + Real(0.005, 0.01, name='roi_p2'), | |
| 193 | + Real(0.003, 0.007, name='roi_p1'), | |
| 194 | + ] | |
| 195 | + | |
| 196 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 197 | + params = self.buy_params | |
| 198 | + | |
| 199 | + conditions = [] | |
| 200 | + | |
| 201 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 202 | + conditions.append( | |
| 203 | + ( | |
| 204 | + ( | |
| 205 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 206 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 207 | + ) | | |
| 208 | + ( | |
| 209 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 210 | + ) | |
| 211 | + ) & | |
| 212 | + ( | |
| 213 | + ( | |
| 214 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 215 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 216 | + ) | | |
| 217 | + ( | |
| 218 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 219 | + ) | |
| 220 | + ) | |
| 221 | + ) | |
| 222 | + | |
| 223 | + conditions.append( | |
| 224 | + ( | |
| 225 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 226 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 227 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 228 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 229 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 230 | + ) | | |
| 231 | + ( | |
| 232 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 233 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 234 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 235 | + ) | |
| 236 | + ) | |
| 237 | + | |
| 238 | + conditions.append(dataframe['volume'].gt(0)) | |
| 239 | + | |
| 240 | + if conditions: | |
| 241 | + dataframe.loc[ | |
| 242 | + reduce(lambda x, y: x & y, conditions), | |
| 243 | + 'buy'] = 1 | |
| 244 | + | |
| 245 | + return dataframe | |
| 246 | + | |
| 247 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 248 | + params = self.sell_params | |
| 249 | + | |
| 250 | + conditions = [] | |
| 251 | + | |
| 252 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 253 | + conditions.append( | |
| 254 | + ( | |
| 255 | + ( | |
| 256 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 257 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 258 | + ) | | |
| 259 | + ( | |
| 260 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 261 | + ) | |
| 262 | + ) & | |
| 263 | + ( | |
| 264 | + ( | |
| 265 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 266 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 267 | + ) | | |
| 268 | + ( | |
| 269 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 270 | + ) | |
| 271 | + ) | |
| 272 | + ) | |
| 273 | + | |
| 274 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 275 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 276 | + conditions.append(dataframe['volume'].gt(0)) | |
| 277 | + | |
| 278 | + if conditions: | |
| 279 | + dataframe.loc[ | |
| 280 | + reduce(lambda x, y: x & y, conditions), | |
| 281 | + 'sell'] = 1 | |
| 282 | + | |
| 283 | + return dataframe | |
| 284 | + | |
| 285 | +class Cluc6werkHyperopt_ETH(Cluc6werkHyperopt): | |
| 286 | + | |
| 287 | + # Buy hyperspace params: | |
| 288 | + buy_params = { | |
| 289 | + 'adx': 41, | |
| 290 | + 'aroon': 31, | |
| 291 | + 'bbdelta-close': 0.00888, | |
| 292 | + 'bbdelta-tail': 0.91161, | |
| 293 | + 'close-bblower': 0.00511, | |
| 294 | + 'closedelta-close': 0.0181, | |
| 295 | + 'volume': 30 | |
| 296 | + } | |
| 297 | + | |
| 298 | + # Sell hyperspace params: | |
| 299 | + sell_params = { | |
| 300 | + 'sell-adx': 15, | |
| 301 | + 'sell-aroon': 63, | |
| 302 | + 'sell-bbmiddle-close': 0.97701 | |
| 303 | + } | |
| 304 | + | |
| 305 | +class Cluc6werkHyperopt_BTC(Cluc6werkHyperopt): | |
| 306 | + | |
| 307 | + # Buy hyperspace params: | |
| 308 | + buy_params = { | |
| 309 | + 'adx': 50, | |
| 310 | + 'aroon': 30, | |
| 311 | + 'bbdelta-close': 0.00621, | |
| 312 | + 'bbdelta-tail': 0.90672, | |
| 313 | + 'close-bblower': 0.0058, | |
| 314 | + 'closedelta-close': 0.01988, | |
| 315 | + 'volume': 34 | |
| 316 | + } | |
| 317 | + | |
| 318 | + # Sell hyperspace params: | |
| 319 | + sell_params = { | |
| 320 | + 'sell-adx': 17, | |
| 321 | + 'sell-aroon': 36, | |
| 322 | + 'sell-bbmiddle-close': 0.98147 | |
| 323 | + } | |
| No newline at the end of the file |
added hyperopts/old/Cluc7werkHyperopt.py +175 −0
| @@ -0,0 +1,175 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class Cluc7werkHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.00732, | |
| 28 | + 'bbdelta-tail': 0.94138, | |
| 29 | + 'close-bblower': 0.0199, | |
| 30 | + 'closedelta-close': 0.01825, | |
| 31 | + 'fisher': -0.22987, | |
| 32 | + 'volume': 16 | |
| 33 | + } | |
| 34 | + | |
| 35 | + # Sell hyperspace params: | |
| 36 | + sell_params = { | |
| 37 | + 'sell-bbmiddle-close': 0.99184, | |
| 38 | + 'sell-fisher': 0.26832 | |
| 39 | + } | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def indicator_space() -> List[Dimension]: | |
| 43 | + return [ | |
| 44 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 45 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 46 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 47 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 48 | + Integer(15, 40, name='volume'), | |
| 49 | + Real(-1.0, 0, name='fisher') | |
| 50 | + ] | |
| 51 | + | |
| 52 | + @staticmethod | |
| 53 | + def sell_indicator_space() -> List[Dimension]: | |
| 54 | + return [ | |
| 55 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 56 | + Real(0, 1.0, name='sell-fisher') | |
| 57 | + ] | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + | |
| 62 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + dataframe.loc[ | |
| 65 | + ( | |
| 66 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 67 | + ) & | |
| 68 | + (( | |
| 69 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 70 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 71 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 72 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 73 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 74 | + ) | | |
| 75 | + ( | |
| 76 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 77 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 78 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 79 | + )), | |
| 80 | + 'buy' | |
| 81 | + ] = 1 | |
| 82 | + | |
| 83 | + return dataframe | |
| 84 | + | |
| 85 | + return populate_buy_trend | |
| 86 | + | |
| 87 | + @staticmethod | |
| 88 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 89 | + | |
| 90 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 91 | + | |
| 92 | + dataframe.loc[ | |
| 93 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 94 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 95 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 96 | + dataframe['volume'].gt(0) | |
| 97 | + , | |
| 98 | + 'sell' | |
| 99 | + ] = 1 | |
| 100 | + | |
| 101 | + return dataframe | |
| 102 | + | |
| 103 | + return populate_sell_trend | |
| 104 | + | |
| 105 | + | |
| 106 | + @staticmethod | |
| 107 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 108 | + | |
| 109 | + roi_table = {} | |
| 110 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 111 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 112 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 113 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 114 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 115 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 116 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 117 | + | |
| 118 | + return roi_table | |
| 119 | + | |
| 120 | + @staticmethod | |
| 121 | + def roi_space() -> List[Dimension]: | |
| 122 | + | |
| 123 | + return [ | |
| 124 | + Integer(1, 15, name='roi_t6'), | |
| 125 | + Integer(1, 45, name='roi_t5'), | |
| 126 | + Integer(1, 90, name='roi_t4'), | |
| 127 | + Integer(45, 120, name='roi_t3'), | |
| 128 | + Integer(45, 180, name='roi_t2'), | |
| 129 | + Integer(90, 300, name='roi_t1'), | |
| 130 | + | |
| 131 | + Real(0.005, 0.10, name='roi_p6'), | |
| 132 | + Real(0.005, 0.07, name='roi_p5'), | |
| 133 | + Real(0.005, 0.05, name='roi_p4'), | |
| 134 | + Real(0.005, 0.025, name='roi_p3'), | |
| 135 | + Real(0.005, 0.01, name='roi_p2'), | |
| 136 | + Real(0.003, 0.007, name='roi_p1'), | |
| 137 | + ] | |
| 138 | + | |
| 139 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 140 | + params = self.buy_params | |
| 141 | + | |
| 142 | + dataframe.loc[ | |
| 143 | + ( | |
| 144 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 145 | + ) & | |
| 146 | + (( | |
| 147 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 148 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 149 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 150 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 151 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 152 | + ) | | |
| 153 | + ( | |
| 154 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 155 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 156 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 157 | + )), | |
| 158 | + 'buy' | |
| 159 | + ] = 1 | |
| 160 | + | |
| 161 | + return dataframe | |
| 162 | + | |
| 163 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 164 | + params = self.sell_params | |
| 165 | + | |
| 166 | + dataframe.loc[ | |
| 167 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 168 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 169 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 170 | + dataframe['volume'].gt(0) | |
| 171 | + , | |
| 172 | + 'sell' | |
| 173 | + ] = 1 | |
| 174 | + | |
| 175 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/ClucCrypROIHyperopt.py +270 −0
| @@ -0,0 +1,270 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class ClucCrypROIHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 25 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 26 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 27 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 28 | + Integer(15, 40, name='volume'), | |
| 29 | + Integer(10, 50, name='adx'), | |
| 30 | + Integer(30, 70, name='aroon') | |
| 31 | + ] | |
| 32 | + | |
| 33 | + @staticmethod | |
| 34 | + def sell_indicator_space() -> List[Dimension]: | |
| 35 | + return [ | |
| 36 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 37 | + Integer(10, 50, name='sell-adx'), | |
| 38 | + Integer(30, 70, name='sell-aroon') | |
| 39 | + ] | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 43 | + | |
| 44 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 45 | + | |
| 46 | + conditions = [] | |
| 47 | + | |
| 48 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 49 | + conditions.append( | |
| 50 | + (( | |
| 51 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 52 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 53 | + ) | ( | |
| 54 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 55 | + )) & (( | |
| 56 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 57 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 58 | + ) | ( | |
| 59 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 60 | + )) | |
| 61 | + ) | |
| 62 | + | |
| 63 | + conditions.append( | |
| 64 | + ( | |
| 65 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 66 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 67 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 68 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 69 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 70 | + ) | | |
| 71 | + ( | |
| 72 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 73 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 74 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 75 | + ) | |
| 76 | + ) | |
| 77 | + | |
| 78 | + conditions.append(dataframe['volume'].gt(0)) | |
| 79 | + | |
| 80 | + if conditions: | |
| 81 | + dataframe.loc[ | |
| 82 | + reduce(lambda x, y: x & y, conditions), | |
| 83 | + 'buy'] = 1 | |
| 84 | + | |
| 85 | + return dataframe | |
| 86 | + | |
| 87 | + return populate_buy_trend | |
| 88 | + | |
| 89 | + @staticmethod | |
| 90 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 91 | + | |
| 92 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 93 | + | |
| 94 | + conditions = [] | |
| 95 | + | |
| 96 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 97 | + conditions.append( | |
| 98 | + (( | |
| 99 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 100 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 101 | + ) | ( | |
| 102 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 103 | + )) & (( | |
| 104 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 105 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 106 | + ) | ( | |
| 107 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 108 | + )) | |
| 109 | + ) | |
| 110 | + | |
| 111 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 112 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 113 | + conditions.append(dataframe['volume'].gt(0)) | |
| 114 | + | |
| 115 | + if conditions: | |
| 116 | + dataframe.loc[ | |
| 117 | + reduce(lambda x, y: x & y, conditions), | |
| 118 | + 'sell'] = 1 | |
| 119 | + | |
| 120 | + return dataframe | |
| 121 | + | |
| 122 | + return populate_sell_trend | |
| 123 | + | |
| 124 | + @staticmethod | |
| 125 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 126 | + | |
| 127 | + roi_table = {} | |
| 128 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 129 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 130 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 131 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 132 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 133 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 134 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 135 | + | |
| 136 | + return roi_table | |
| 137 | + | |
| 138 | + @staticmethod | |
| 139 | + def roi_space() -> List[Dimension]: | |
| 140 | + | |
| 141 | + return [ | |
| 142 | + Integer(1, 5, name='roi_t6'), | |
| 143 | + Integer(1, 10, name='roi_t5'), | |
| 144 | + Integer(1, 15, name='roi_t4'), | |
| 145 | + Integer(15, 20, name='roi_t3'), | |
| 146 | + Integer(20, 25, name='roi_t2'), | |
| 147 | + Integer(25, 60, name='roi_t1'), | |
| 148 | + | |
| 149 | + Real(0.005, 0.10, name='roi_p6'), | |
| 150 | + Real(0.005, 0.07, name='roi_p5'), | |
| 151 | + Real(0.005, 0.05, name='roi_p4'), | |
| 152 | + Real(0.005, 0.025, name='roi_p3'), | |
| 153 | + Real(0.005, 0.01, name='roi_p2'), | |
| 154 | + Real(0.003, 0.007, name='roi_p1'), | |
| 155 | + ] | |
| 156 | + | |
| 157 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 158 | + params = self.buy_params | |
| 159 | + | |
| 160 | + conditions = [] | |
| 161 | + | |
| 162 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 163 | + conditions.append( | |
| 164 | + (( | |
| 165 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 166 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 167 | + ) | ( | |
| 168 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 169 | + )) & (( | |
| 170 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 171 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 172 | + ) | ( | |
| 173 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 174 | + )) | |
| 175 | + ) | |
| 176 | + | |
| 177 | + conditions.append( | |
| 178 | + ( | |
| 179 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 180 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 181 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 182 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 183 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 184 | + ) | | |
| 185 | + ( | |
| 186 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 187 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 188 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 189 | + ) | |
| 190 | + ) | |
| 191 | + | |
| 192 | + conditions.append(dataframe['volume'].gt(0)) | |
| 193 | + | |
| 194 | + if conditions: | |
| 195 | + dataframe.loc[ | |
| 196 | + reduce(lambda x, y: x & y, conditions), | |
| 197 | + 'buy'] = 1 | |
| 198 | + | |
| 199 | + return dataframe | |
| 200 | + | |
| 201 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 202 | + params = self.sell_params | |
| 203 | + | |
| 204 | + conditions = [] | |
| 205 | + | |
| 206 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 207 | + conditions.append( | |
| 208 | + (( | |
| 209 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 210 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 211 | + ) | ( | |
| 212 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 213 | + )) & (( | |
| 214 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 215 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 216 | + ) | ( | |
| 217 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 218 | + )) | |
| 219 | + ) | |
| 220 | + | |
| 221 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 222 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 223 | + conditions.append(dataframe['volume'].gt(0)) | |
| 224 | + | |
| 225 | + if conditions: | |
| 226 | + dataframe.loc[ | |
| 227 | + reduce(lambda x, y: x & y, conditions), | |
| 228 | + 'sell'] = 1 | |
| 229 | + | |
| 230 | + return dataframe | |
| 231 | + | |
| 232 | +class ClucCrypROIHyperopt_ETH(ClucCrypROIHyperopt): | |
| 233 | + | |
| 234 | + # Buy hyperspace params: | |
| 235 | + buy_params = { | |
| 236 | + 'adx': 46, | |
| 237 | + 'aroon': 51, | |
| 238 | + 'bbdelta-close': 0.01775, | |
| 239 | + 'bbdelta-tail': 0.84013, | |
| 240 | + 'close-bblower': 0.01096, | |
| 241 | + 'closedelta-close': 0.01068, | |
| 242 | + 'volume': 15 | |
| 243 | + } | |
| 244 | + | |
| 245 | + # Sell hyperspace params: | |
| 246 | + sell_params = { | |
| 247 | + 'sell-adx': 39, | |
| 248 | + 'sell-aroon': 65, | |
| 249 | + 'sell-bbmiddle-close': 0.98656 | |
| 250 | + } | |
| 251 | + | |
| 252 | +class ClucCrypROIHyperopt_BTC(ClucCrypROIHyperopt): | |
| 253 | + | |
| 254 | + # Buy hyperspace params: | |
| 255 | + buy_params = { | |
| 256 | + 'adx': 47, | |
| 257 | + 'aroon': 34, | |
| 258 | + 'bbdelta-close': 0.01957, | |
| 259 | + 'bbdelta-tail': 0.86961, | |
| 260 | + 'close-bblower': 0.00257, | |
| 261 | + 'closedelta-close': 0.01381, | |
| 262 | + 'volume': 27 | |
| 263 | + } | |
| 264 | + | |
| 265 | + # Sell hyperspace params: | |
| 266 | + sell_params = { | |
| 267 | + 'sell-adx': 20, | |
| 268 | + 'sell-aroon': 63, | |
| 269 | + 'sell-bbmiddle-close': 0.95563 | |
| 270 | + } | |
| No newline at the end of the file |
added hyperopts/old/ClucCrypSlowHyperopt.py +266 −0
| @@ -0,0 +1,266 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class ClucCrypSlowHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 25 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 26 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 27 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 28 | + Integer(15, 40, name='volume'), | |
| 29 | + Integer(10, 50, name='adx'), | |
| 30 | + Integer(30, 70, name='aroon') | |
| 31 | + ] | |
| 32 | + | |
| 33 | + @staticmethod | |
| 34 | + def sell_indicator_space() -> List[Dimension]: | |
| 35 | + return [ | |
| 36 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 37 | + Integer(10, 50, name='sell-adx'), | |
| 38 | + Integer(30, 70, name='sell-aroon') | |
| 39 | + ] | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 43 | + | |
| 44 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 45 | + | |
| 46 | + conditions = [] | |
| 47 | + | |
| 48 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 49 | + conditions.append((( | |
| 50 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 51 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 52 | + ) | ( | |
| 53 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 54 | + )) & (( | |
| 55 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 56 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 57 | + ) | ( | |
| 58 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 59 | + )) | |
| 60 | + ) | |
| 61 | + | |
| 62 | + conditions.append( | |
| 63 | + ( | |
| 64 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 65 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 66 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 67 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 68 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 69 | + ) | | |
| 70 | + ( | |
| 71 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 72 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 73 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 74 | + ) | |
| 75 | + ) | |
| 76 | + | |
| 77 | + conditions.append(dataframe['volume'].gt(0)) | |
| 78 | + | |
| 79 | + if conditions: | |
| 80 | + dataframe.loc[ | |
| 81 | + reduce(lambda x, y: x & y, conditions), | |
| 82 | + 'buy'] = 1 | |
| 83 | + | |
| 84 | + return dataframe | |
| 85 | + | |
| 86 | + return populate_buy_trend | |
| 87 | + | |
| 88 | + @staticmethod | |
| 89 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 90 | + | |
| 91 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 92 | + | |
| 93 | + conditions = [] | |
| 94 | + | |
| 95 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 96 | + conditions.append((( | |
| 97 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 98 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 99 | + ) | ( | |
| 100 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 101 | + )) & (( | |
| 102 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 103 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 104 | + ) | ( | |
| 105 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 106 | + )) | |
| 107 | + ) | |
| 108 | + | |
| 109 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 110 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 111 | + conditions.append(dataframe['volume'].gt(0)) | |
| 112 | + | |
| 113 | + if conditions: | |
| 114 | + dataframe.loc[ | |
| 115 | + reduce(lambda x, y: x & y, conditions), | |
| 116 | + 'sell'] = 1 | |
| 117 | + | |
| 118 | + return dataframe | |
| 119 | + | |
| 120 | + return populate_sell_trend | |
| 121 | + | |
| 122 | + @staticmethod | |
| 123 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 124 | + | |
| 125 | + roi_table = {} | |
| 126 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 127 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 128 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 129 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 130 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 131 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 132 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 133 | + | |
| 134 | + return roi_table | |
| 135 | + | |
| 136 | + @staticmethod | |
| 137 | + def roi_space() -> List[Dimension]: | |
| 138 | + | |
| 139 | + return [ | |
| 140 | + Integer(1, 15, name='roi_t6'), | |
| 141 | + Integer(1, 45, name='roi_t5'), | |
| 142 | + Integer(1, 90, name='roi_t4'), | |
| 143 | + Integer(45, 120, name='roi_t3'), | |
| 144 | + Integer(45, 180, name='roi_t2'), | |
| 145 | + Integer(90, 300, name='roi_t1'), | |
| 146 | + | |
| 147 | + Real(0.005, 0.10, name='roi_p6'), | |
| 148 | + Real(0.005, 0.07, name='roi_p5'), | |
| 149 | + Real(0.005, 0.05, name='roi_p4'), | |
| 150 | + Real(0.005, 0.025, name='roi_p3'), | |
| 151 | + Real(0.005, 0.01, name='roi_p2'), | |
| 152 | + Real(0.003, 0.007, name='roi_p1'), | |
| 153 | + ] | |
| 154 | + | |
| 155 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 156 | + params = self.buy_params | |
| 157 | + | |
| 158 | + conditions = [] | |
| 159 | + | |
| 160 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 161 | + conditions.append((( | |
| 162 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 163 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 164 | + ) | ( | |
| 165 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 166 | + )) & (( | |
| 167 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 168 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 169 | + ) | ( | |
| 170 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 171 | + )) | |
| 172 | + ) | |
| 173 | + | |
| 174 | + conditions.append( | |
| 175 | + ( | |
| 176 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 177 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 178 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 179 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 180 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 181 | + ) | | |
| 182 | + ( | |
| 183 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 184 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 185 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 186 | + ) | |
| 187 | + ) | |
| 188 | + | |
| 189 | + conditions.append(dataframe['volume'].gt(0)) | |
| 190 | + | |
| 191 | + if conditions: | |
| 192 | + dataframe.loc[ | |
| 193 | + reduce(lambda x, y: x & y, conditions), | |
| 194 | + 'buy'] = 1 | |
| 195 | + | |
| 196 | + return dataframe | |
| 197 | + | |
| 198 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 199 | + params = self.sell_params | |
| 200 | + | |
| 201 | + conditions = [] | |
| 202 | + | |
| 203 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 204 | + conditions.append((( | |
| 205 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 206 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 207 | + ) | ( | |
| 208 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 209 | + )) & (( | |
| 210 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 211 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 212 | + ) | ( | |
| 213 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 214 | + )) | |
| 215 | + ) | |
| 216 | + | |
| 217 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 218 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 219 | + conditions.append(dataframe['volume'].gt(0)) | |
| 220 | + | |
| 221 | + if conditions: | |
| 222 | + dataframe.loc[ | |
| 223 | + reduce(lambda x, y: x & y, conditions), | |
| 224 | + 'sell'] = 1 | |
| 225 | + | |
| 226 | + return dataframe | |
| 227 | + | |
| 228 | +class ClucCrypSlowHyperopt_ETH(ClucCrypSlowHyperopt): | |
| 229 | + | |
| 230 | + # Buy hyperspace params: | |
| 231 | + buy_params = { | |
| 232 | + 'adx': 46, | |
| 233 | + 'aroon': 51, | |
| 234 | + 'bbdelta-close': 0.01775, | |
| 235 | + 'bbdelta-tail': 0.84013, | |
| 236 | + 'close-bblower': 0.01096, | |
| 237 | + 'closedelta-close': 0.01068, | |
| 238 | + 'volume': 15 | |
| 239 | + } | |
| 240 | + | |
| 241 | + # Sell hyperspace params: | |
| 242 | + sell_params = { | |
| 243 | + 'sell-adx': 39, | |
| 244 | + 'sell-aroon': 65, | |
| 245 | + 'sell-bbmiddle-close': 0.98656 | |
| 246 | + } | |
| 247 | + | |
| 248 | +class ClucCrypSlowHyperopt_BTC(ClucCrypSlowHyperopt): | |
| 249 | + | |
| 250 | + # Buy hyperspace params: | |
| 251 | + buy_params = { | |
| 252 | + 'adx': 47, | |
| 253 | + 'aroon': 34, | |
| 254 | + 'bbdelta-close': 0.01957, | |
| 255 | + 'bbdelta-tail': 0.86961, | |
| 256 | + 'close-bblower': 0.00257, | |
| 257 | + 'closedelta-close': 0.01381, | |
| 258 | + 'volume': 27 | |
| 259 | + } | |
| 260 | + | |
| 261 | + # Sell hyperspace params: | |
| 262 | + sell_params = { | |
| 263 | + 'sell-adx': 20, | |
| 264 | + 'sell-aroon': 63, | |
| 265 | + 'sell-bbmiddle-close': 0.95563 | |
| 266 | + } | |
| No newline at the end of the file |
added hyperopts/old/ClucFiatROIHyperopt.py +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class ClucFiatROIHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.00642, | |
| 28 | + 'bbdelta-tail': 0.75559, | |
| 29 | + 'close-bblower': 0.01415, | |
| 30 | + 'closedelta-close': 0.00883, | |
| 31 | + 'fisher': -0.97101, | |
| 32 | + 'volume': 18 | |
| 33 | + } | |
| 34 | + | |
| 35 | + # Sell hyperspace params: | |
| 36 | + sell_params = { | |
| 37 | + 'sell-bbmiddle-close': 0.95153, | |
| 38 | + 'sell-fisher': 0.60924 | |
| 39 | + } | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def indicator_space() -> List[Dimension]: | |
| 43 | + return [ | |
| 44 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 45 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 46 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 47 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 48 | + Integer(15, 40, name='volume'), | |
| 49 | + Real(-1.0, 0, name='fisher') | |
| 50 | + ] | |
| 51 | + | |
| 52 | + @staticmethod | |
| 53 | + def sell_indicator_space() -> List[Dimension]: | |
| 54 | + return [ | |
| 55 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 56 | + Real(0, 1.0, name='sell-fisher') | |
| 57 | + ] | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + | |
| 62 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + dataframe.loc[ | |
| 65 | + ( | |
| 66 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 67 | + ) & | |
| 68 | + (( | |
| 69 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 70 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 71 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 72 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 73 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 74 | + ) | | |
| 75 | + ( | |
| 76 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 77 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 78 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 79 | + )), | |
| 80 | + 'buy' | |
| 81 | + ] = 1 | |
| 82 | + | |
| 83 | + return dataframe | |
| 84 | + | |
| 85 | + return populate_buy_trend | |
| 86 | + | |
| 87 | + @staticmethod | |
| 88 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 89 | + | |
| 90 | + roi_table = {} | |
| 91 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 92 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 93 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 94 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 95 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 96 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 97 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 98 | + | |
| 99 | + return roi_table | |
| 100 | + | |
| 101 | + @staticmethod | |
| 102 | + def roi_space() -> List[Dimension]: | |
| 103 | + | |
| 104 | + return [ | |
| 105 | + Integer(1, 15, name='roi_t6'), | |
| 106 | + Integer(1, 45, name='roi_t5'), | |
| 107 | + Integer(1, 90, name='roi_t4'), | |
| 108 | + Integer(45, 120, name='roi_t3'), | |
| 109 | + Integer(45, 180, name='roi_t2'), | |
| 110 | + Integer(90, 300, name='roi_t1'), | |
| 111 | + | |
| 112 | + Real(0.005, 0.10, name='roi_p6'), | |
| 113 | + Real(0.005, 0.07, name='roi_p5'), | |
| 114 | + Real(0.005, 0.05, name='roi_p4'), | |
| 115 | + Real(0.005, 0.025, name='roi_p3'), | |
| 116 | + Real(0.005, 0.01, name='roi_p2'), | |
| 117 | + Real(0.003, 0.007, name='roi_p1'), | |
| 118 | + ] | |
| 119 | + | |
| 120 | + @staticmethod | |
| 121 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 122 | + | |
| 123 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 124 | + | |
| 125 | + dataframe.loc[ | |
| 126 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 127 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 128 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 129 | + dataframe['volume'].gt(0) | |
| 130 | + , | |
| 131 | + 'sell' | |
| 132 | + ] = 1 | |
| 133 | + | |
| 134 | + return dataframe | |
| 135 | + | |
| 136 | + return populate_sell_trend | |
| 137 | + | |
| 138 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 139 | + params = self.buy_params | |
| 140 | + | |
| 141 | + dataframe.loc[ | |
| 142 | + ( | |
| 143 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 144 | + ) & | |
| 145 | + (( | |
| 146 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 147 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 148 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 149 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 150 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 151 | + ) | | |
| 152 | + ( | |
| 153 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 154 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 155 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 156 | + )), | |
| 157 | + 'buy' | |
| 158 | + ] = 1 | |
| 159 | + | |
| 160 | + return dataframe | |
| 161 | + | |
| 162 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 163 | + params = self.sell_params | |
| 164 | + | |
| 165 | + dataframe.loc[ | |
| 166 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 167 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 168 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 169 | + dataframe['volume'].gt(0) | |
| 170 | + , | |
| 171 | + 'sell' | |
| 172 | + ] = 1 | |
| 173 | + | |
| 174 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/ClucFiatSlowHyperopt.py +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class ClucFiatSlowHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.00642, | |
| 28 | + 'bbdelta-tail': 0.75559, | |
| 29 | + 'close-bblower': 0.01415, | |
| 30 | + 'closedelta-close': 0.00883, | |
| 31 | + 'fisher': -0.97101, | |
| 32 | + 'volume': 18 | |
| 33 | + } | |
| 34 | + | |
| 35 | + # Sell hyperspace params: | |
| 36 | + sell_params = { | |
| 37 | + 'sell-bbmiddle-close': 0.95153, | |
| 38 | + 'sell-fisher': 0.60924 | |
| 39 | + } | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def indicator_space() -> List[Dimension]: | |
| 43 | + return [ | |
| 44 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 45 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 46 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 47 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 48 | + Integer(15, 40, name='volume'), | |
| 49 | + Real(-1.0, 0, name='fisher') | |
| 50 | + ] | |
| 51 | + | |
| 52 | + @staticmethod | |
| 53 | + def sell_indicator_space() -> List[Dimension]: | |
| 54 | + return [ | |
| 55 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 56 | + Real(0, 1.0, name='sell-fisher') | |
| 57 | + ] | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + | |
| 62 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + dataframe.loc[ | |
| 65 | + ( | |
| 66 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 67 | + ) & | |
| 68 | + (( | |
| 69 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 70 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 71 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 72 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 73 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 74 | + ) | | |
| 75 | + ( | |
| 76 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 77 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 78 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 79 | + )), | |
| 80 | + 'buy' | |
| 81 | + ] = 1 | |
| 82 | + | |
| 83 | + return dataframe | |
| 84 | + | |
| 85 | + return populate_buy_trend | |
| 86 | + | |
| 87 | + @staticmethod | |
| 88 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 89 | + | |
| 90 | + roi_table = {} | |
| 91 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 92 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 93 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 94 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 95 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 96 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 97 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 98 | + | |
| 99 | + return roi_table | |
| 100 | + | |
| 101 | + @staticmethod | |
| 102 | + def roi_space() -> List[Dimension]: | |
| 103 | + | |
| 104 | + return [ | |
| 105 | + Integer(1, 15, name='roi_t6'), | |
| 106 | + Integer(1, 45, name='roi_t5'), | |
| 107 | + Integer(1, 90, name='roi_t4'), | |
| 108 | + Integer(45, 120, name='roi_t3'), | |
| 109 | + Integer(45, 180, name='roi_t2'), | |
| 110 | + Integer(90, 300, name='roi_t1'), | |
| 111 | + | |
| 112 | + Real(0.005, 0.10, name='roi_p6'), | |
| 113 | + Real(0.005, 0.07, name='roi_p5'), | |
| 114 | + Real(0.005, 0.05, name='roi_p4'), | |
| 115 | + Real(0.005, 0.025, name='roi_p3'), | |
| 116 | + Real(0.005, 0.01, name='roi_p2'), | |
| 117 | + Real(0.003, 0.007, name='roi_p1'), | |
| 118 | + ] | |
| 119 | + | |
| 120 | + @staticmethod | |
| 121 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 122 | + | |
| 123 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 124 | + | |
| 125 | + dataframe.loc[ | |
| 126 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 127 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 128 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 129 | + dataframe['volume'].gt(0) | |
| 130 | + , | |
| 131 | + 'sell' | |
| 132 | + ] = 1 | |
| 133 | + | |
| 134 | + return dataframe | |
| 135 | + | |
| 136 | + return populate_sell_trend | |
| 137 | + | |
| 138 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 139 | + params = self.buy_params | |
| 140 | + | |
| 141 | + dataframe.loc[ | |
| 142 | + ( | |
| 143 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 144 | + ) & | |
| 145 | + (( | |
| 146 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 147 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 148 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 149 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 150 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 151 | + ) | | |
| 152 | + ( | |
| 153 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 154 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 155 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 156 | + )), | |
| 157 | + 'buy' | |
| 158 | + ] = 1 | |
| 159 | + | |
| 160 | + return dataframe | |
| 161 | + | |
| 162 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 163 | + params = self.sell_params | |
| 164 | + | |
| 165 | + dataframe.loc[ | |
| 166 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 167 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 168 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 169 | + dataframe['volume'].gt(0) | |
| 170 | + , | |
| 171 | + 'sell' | |
| 172 | + ] = 1 | |
| 173 | + | |
| 174 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/ClucHAnixHyperopt.py +243 −0
| @@ -0,0 +1,243 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class ClucHAnixHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + OVERRIDE THESE AT THE BOTTOM FOR SPECIFIC STAKES | |
| 25 | + """ | |
| 26 | + | |
| 27 | + # Buy hyperspace params: | |
| 28 | + buy_params = { | |
| 29 | + 'bbdelta-close': 0.01965, | |
| 30 | + 'bbdelta-tail': 0.95089, | |
| 31 | + 'close-bblower': 0.00799, | |
| 32 | + 'closedelta-close': 0.00556, | |
| 33 | + 'rocr-1h': 0.54904 | |
| 34 | + } | |
| 35 | + | |
| 36 | + # Sell hyperspace params: | |
| 37 | + sell_params = { | |
| 38 | + 'sell-fisher': 0.38414, | |
| 39 | + 'sell-bbmiddle-close': 1.07634 | |
| 40 | + } | |
| 41 | + | |
| 42 | + @staticmethod | |
| 43 | + def indicator_space() -> List[Dimension]: | |
| 44 | + return [ | |
| 45 | + Real(0.5, 1.0, name='rocr-1h'), | |
| 46 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 47 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 48 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 49 | + Real(0.0005, 0.02, name='close-bblower') | |
| 50 | + #, Integer(15, 40, name='volume') | |
| 51 | + ] | |
| 52 | + | |
| 53 | + @staticmethod | |
| 54 | + def sell_indicator_space() -> List[Dimension]: | |
| 55 | + return [ | |
| 56 | + Real(0.1, 0.5, name='sell-fisher'), | |
| 57 | + Real(0.97, 1.1, name='sell-bbmiddle-close') | |
| 58 | + ] | |
| 59 | + | |
| 60 | + @staticmethod | |
| 61 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 62 | + """ | |
| 63 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 64 | + """ | |
| 65 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 66 | + """ | |
| 67 | + Buy strategy Hyperopt will build and use. | |
| 68 | + """ | |
| 69 | + dataframe.loc[ | |
| 70 | + ( | |
| 71 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 72 | + ) & | |
| 73 | + (( | |
| 74 | + (dataframe['lower'].shift().gt(0)) & | |
| 75 | + (dataframe['bbdelta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 76 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 77 | + (dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail'])) & | |
| 78 | + (dataframe['ha_close'].lt(dataframe['lower'].shift())) & | |
| 79 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift())) | |
| 80 | + ) | | |
| 81 | + ( | |
| 82 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 83 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['bb_lowerband']) | |
| 84 | + )), | |
| 85 | + 'buy' | |
| 86 | + ] = 1 | |
| 87 | + | |
| 88 | + return dataframe | |
| 89 | + | |
| 90 | + return populate_buy_trend | |
| 91 | + | |
| 92 | + @staticmethod | |
| 93 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 94 | + """ | |
| 95 | + Define the sell strategy parameters to be used by hyperopt | |
| 96 | + """ | |
| 97 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 98 | + | |
| 99 | + dataframe.loc[ | |
| 100 | + (dataframe['fisher'] > params['sell-fisher']) & | |
| 101 | + (dataframe['ha_high'].le(dataframe['ha_high'].shift(1))) & | |
| 102 | + (dataframe['ha_high'].shift(1).le(dataframe['ha_high'].shift(2))) & | |
| 103 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift(1))) & | |
| 104 | + (dataframe['ema_fast'] > dataframe['ha_close']) & | |
| 105 | + ((dataframe['ha_close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 106 | + (dataframe['volume'] > 0) | |
| 107 | + , | |
| 108 | + 'sell' | |
| 109 | + ] = 1 | |
| 110 | + | |
| 111 | + return dataframe | |
| 112 | + | |
| 113 | + return populate_sell_trend | |
| 114 | + | |
| 115 | + | |
| 116 | + @staticmethod | |
| 117 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 118 | + | |
| 119 | + roi_table = {} | |
| 120 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 121 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 122 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 123 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 124 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 125 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 126 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 127 | + | |
| 128 | + return roi_table | |
| 129 | + | |
| 130 | + @staticmethod | |
| 131 | + def roi_space() -> List[Dimension]: | |
| 132 | + | |
| 133 | + return [ | |
| 134 | + Integer(1, 15, name='roi_t6'), | |
| 135 | + Integer(1, 45, name='roi_t5'), | |
| 136 | + Integer(1, 90, name='roi_t4'), | |
| 137 | + Integer(45, 120, name='roi_t3'), | |
| 138 | + Integer(45, 180, name='roi_t2'), | |
| 139 | + Integer(90, 300, name='roi_t1'), | |
| 140 | + | |
| 141 | + Real(0.005, 0.10, name='roi_p6'), | |
| 142 | + Real(0.005, 0.07, name='roi_p5'), | |
| 143 | + Real(0.005, 0.05, name='roi_p4'), | |
| 144 | + Real(0.005, 0.025, name='roi_p3'), | |
| 145 | + Real(0.005, 0.01, name='roi_p2'), | |
| 146 | + Real(0.003, 0.007, name='roi_p1'), | |
| 147 | + ] | |
| 148 | + | |
| 149 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 150 | + params = self.buy_params | |
| 151 | + | |
| 152 | + dataframe.loc[ | |
| 153 | + ( | |
| 154 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 155 | + ) & | |
| 156 | + (( | |
| 157 | + (dataframe['lower'].shift().gt(0)) & | |
| 158 | + (dataframe['bbdelta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 159 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 160 | + (dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail'])) & | |
| 161 | + (dataframe['ha_close'].lt(dataframe['lower'].shift())) & | |
| 162 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift())) | |
| 163 | + ) | | |
| 164 | + ( | |
| 165 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 166 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['bb_lowerband']) | |
| 167 | + )), | |
| 168 | + 'buy' | |
| 169 | + ] = 1 | |
| 170 | + | |
| 171 | + return dataframe | |
| 172 | + | |
| 173 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 174 | + params = self.sell_params | |
| 175 | + | |
| 176 | + dataframe.loc[ | |
| 177 | + (dataframe['fisher'] > params['sell-fisher']) & | |
| 178 | + (dataframe['ha_high'].le(dataframe['ha_high'].shift(1))) & | |
| 179 | + (dataframe['ha_high'].shift(1).le(dataframe['ha_high'].shift(2))) & | |
| 180 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift(1))) & | |
| 181 | + (dataframe['ema_fast'] > dataframe['ha_close']) & | |
| 182 | + ((dataframe['ha_close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 183 | + (dataframe['volume'] > 0) | |
| 184 | + , | |
| 185 | + 'sell' | |
| 186 | + ] = 1 | |
| 187 | + | |
| 188 | + return dataframe | |
| 189 | + | |
| 190 | + | |
| 191 | +class ClucHAnixHyperopt_ETH(ClucHAnixHyperopt): | |
| 192 | + | |
| 193 | + # Buy hyperspace params: | |
| 194 | + buy_params = { | |
| 195 | + 'bbdelta-close': 0.01566, | |
| 196 | + 'bbdelta-tail': 0.8478, | |
| 197 | + 'close-bblower': 0.00998, | |
| 198 | + 'closedelta-close': 0.00614, | |
| 199 | + 'rocr-1h': 0.61579, | |
| 200 | + 'volume': 27 | |
| 201 | + } | |
| 202 | + | |
| 203 | + # Sell hyperspace params: | |
| 204 | + sell_params = { | |
| 205 | + 'sell-bbmiddle-close': 1.02894, | |
| 206 | + 'sell-fisher': 0.38414 | |
| 207 | + } | |
| 208 | + | |
| 209 | +class ClucHAnixHyperopt_BTC(ClucHAnixHyperopt): | |
| 210 | + | |
| 211 | + # Buy hyperspace params: | |
| 212 | + buy_params = { | |
| 213 | + 'bbdelta-close': 0.01192, | |
| 214 | + 'bbdelta-tail': 0.96183, | |
| 215 | + 'close-bblower': 0.01212, | |
| 216 | + 'closedelta-close': 0.01039, | |
| 217 | + 'rocr-1h': 0.53422, | |
| 218 | + 'volume': 27 | |
| 219 | + } | |
| 220 | + | |
| 221 | + # Sell hyperspace params: | |
| 222 | + sell_params = { | |
| 223 | + 'sell-bbmiddle-close': 0.98016, | |
| 224 | + 'sell-fisher': 0.38414 | |
| 225 | + } | |
| 226 | + | |
| 227 | +class ClucHAnixHyperopt_USD(ClucHAnixHyperopt): | |
| 228 | + | |
| 229 | + # Buy hyperspace params: | |
| 230 | + buy_params = { | |
| 231 | + 'bbdelta-close': 0.01806, | |
| 232 | + 'bbdelta-tail': 0.85912, | |
| 233 | + 'close-bblower': 0.01158, | |
| 234 | + 'closedelta-close': 0.01466, | |
| 235 | + 'rocr-1h': 0.51901, | |
| 236 | + 'volume': 26 | |
| 237 | + } | |
| 238 | + | |
| 239 | + # Sell hyperspace params: | |
| 240 | + sell_params = { | |
| 241 | + 'sell-bbmiddle-close': 0.96094, | |
| 242 | + 'sell-fisher': 0.38414 | |
| 243 | + } | |
| No newline at the end of the file |
added hyperopts/old/ClucHAwerkHyperopt.py +248 −0
| @@ -0,0 +1,248 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class ClucHAwerkHyperopt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + OVERRIDE THESE AT THE BOTTOM FOR SPECIFIC STAKES | |
| 25 | + """ | |
| 26 | + | |
| 27 | + buy_params = { | |
| 28 | + 'bbdelta-close': 0.01568, | |
| 29 | + 'bbdelta-tail': 0.7327, | |
| 30 | + 'close-bblower': 0.01376, | |
| 31 | + 'closedelta-close': 0.00614, | |
| 32 | + 'rocr-1h': 0.57548, | |
| 33 | + 'volume': 38 | |
| 34 | + } | |
| 35 | + | |
| 36 | + sell_params = { | |
| 37 | + 'sell-bbmiddle-close': 1.02888, | |
| 38 | + 'sell-rocr-1h': 0.94914 | |
| 39 | + } | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def indicator_space() -> List[Dimension]: | |
| 43 | + return [ | |
| 44 | + Real(0.5, 1.0, name='rocr-1h'), | |
| 45 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 46 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 47 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 48 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 49 | + Integer(15, 40, name='volume') | |
| 50 | + ] | |
| 51 | + | |
| 52 | + @staticmethod | |
| 53 | + def sell_indicator_space() -> List[Dimension]: | |
| 54 | + return [ | |
| 55 | + Real(0.95, 1.2, name='sell-bbmiddle-close'), | |
| 56 | + Real(0.5, 1.0, name='sell-rocr-1h') | |
| 57 | + | |
| 58 | + ] | |
| 59 | + | |
| 60 | + @staticmethod | |
| 61 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 62 | + """ | |
| 63 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 64 | + """ | |
| 65 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 66 | + """ | |
| 67 | + Buy strategy Hyperopt will build and use. | |
| 68 | + """ | |
| 69 | + dataframe.loc[ | |
| 70 | + ( | |
| 71 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 72 | + ) & | |
| 73 | + (( | |
| 74 | + dataframe['lower'].shift().gt(0) & | |
| 75 | + dataframe['bbdelta'].gt(dataframe['ha_close'] * params['bbdelta-close']) & | |
| 76 | + dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close']) & | |
| 77 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 78 | + dataframe['ha_close'].lt(dataframe['lower'].shift()) & | |
| 79 | + dataframe['ha_close'].le(dataframe['ha_close'].shift()) | |
| 80 | + ) | | |
| 81 | + ( | |
| 82 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 83 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 84 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 85 | + )), | |
| 86 | + 'buy' | |
| 87 | + ] = 1 | |
| 88 | + | |
| 89 | + return dataframe | |
| 90 | + | |
| 91 | + return populate_buy_trend | |
| 92 | + | |
| 93 | + @staticmethod | |
| 94 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 95 | + """ | |
| 96 | + Define the sell strategy parameters to be used by hyperopt | |
| 97 | + """ | |
| 98 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 99 | + | |
| 100 | + dataframe.loc[ | |
| 101 | + dataframe['rocr_1h'].lt(params['sell-rocr-1h']) & | |
| 102 | + ((dataframe['ha_close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 103 | + (dataframe['volume'] > 0) | |
| 104 | + , | |
| 105 | + 'sell' | |
| 106 | + ] = 1 | |
| 107 | + | |
| 108 | + return dataframe | |
| 109 | + | |
| 110 | + return populate_sell_trend | |
| 111 | + | |
| 112 | + | |
| 113 | + @staticmethod | |
| 114 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 115 | + | |
| 116 | + roi_table = {} | |
| 117 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 118 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 119 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 120 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 121 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 122 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 123 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 124 | + | |
| 125 | + return roi_table | |
| 126 | + | |
| 127 | + @staticmethod | |
| 128 | + def roi_space() -> List[Dimension]: | |
| 129 | + | |
| 130 | + return [ | |
| 131 | + Integer(1, 15, name='roi_t6'), | |
| 132 | + Integer(1, 45, name='roi_t5'), | |
| 133 | + Integer(1, 90, name='roi_t4'), | |
| 134 | + Integer(45, 120, name='roi_t3'), | |
| 135 | + Integer(45, 180, name='roi_t2'), | |
| 136 | + Integer(90, 300, name='roi_t1'), | |
| 137 | + | |
| 138 | + Real(0.005, 0.10, name='roi_p6'), | |
| 139 | + Real(0.005, 0.07, name='roi_p5'), | |
| 140 | + Real(0.005, 0.05, name='roi_p4'), | |
| 141 | + Real(0.005, 0.025, name='roi_p3'), | |
| 142 | + Real(0.005, 0.01, name='roi_p2'), | |
| 143 | + Real(0.003, 0.007, name='roi_p1'), | |
| 144 | + ] | |
| 145 | + | |
| 146 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 147 | + params = self.buy_params | |
| 148 | + | |
| 149 | + dataframe.loc[ | |
| 150 | + ( | |
| 151 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 152 | + ) & | |
| 153 | + (( | |
| 154 | + dataframe['lower'].shift().gt(0) & | |
| 155 | + dataframe['bbdelta'].gt(dataframe['ha_close'] * params['bbdelta-close']) & | |
| 156 | + dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close']) & | |
| 157 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 158 | + dataframe['ha_close'].lt(dataframe['lower'].shift()) & | |
| 159 | + dataframe['ha_close'].le(dataframe['ha_close'].shift()) | |
| 160 | + ) | | |
| 161 | + ( | |
| 162 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 163 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 164 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 165 | + )), | |
| 166 | + 'buy' | |
| 167 | + ] = 1 | |
| 168 | + | |
| 169 | + return dataframe | |
| 170 | + | |
| 171 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 172 | + params = self.sell_params | |
| 173 | + | |
| 174 | + dataframe.loc[ | |
| 175 | + dataframe['rocr_1h'].lt(params['sell-rocr-1h']) & | |
| 176 | + ((dataframe['ha_close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 177 | + (dataframe['volume'] > 0) | |
| 178 | + , | |
| 179 | + 'sell' | |
| 180 | + ] = 1 | |
| 181 | + | |
| 182 | + return dataframe | |
| 183 | + | |
| 184 | +class ClucHAwerkHyperopt_ETH(ClucHAwerkHyperopt): | |
| 185 | + | |
| 186 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_ETH -e 500 --spaces buy --timeframe 1m --timerange 20210101- | |
| 187 | + # 483/500: 1880 trades. 1054/0/826 Wins/Draws/Losses. Avg profit 0.76%. Median profit 1.12%. Total profit 0.14286503 ETH ( 1426.37Σ%). Avg duration 45.3 min. Objective: -623.10584 | |
| 188 | + # Buy hyperspace params: | |
| 189 | + buy_params = { | |
| 190 | + 'bbdelta-close': 0.01566, | |
| 191 | + 'bbdelta-tail': 0.8478, | |
| 192 | + 'close-bblower': 0.00998, | |
| 193 | + 'closedelta-close': 0.00614, | |
| 194 | + 'rocr-1h': 0.61579, | |
| 195 | + 'volume': 27 | |
| 196 | + } | |
| 197 | + | |
| 198 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_ETH -e 500 --spaces sell --timeframe 1m --timerange 20210101- | |
| 199 | + # 210/500: 1881 trades. 1055/0/826 Wins/Draws/Losses. Avg profit 0.76%. Median profit 1.12%. Total profit 0.14316974 ETH ( 1429.41Σ%). Avg duration 45.3 min. Objective: -624.58371 | |
| 200 | + # Sell hyperspace params: | |
| 201 | + sell_params = { | |
| 202 | + 'sell-bbmiddle-close': 1.02894, | |
| 203 | + 'sell-rocr-1h': 0.94925 | |
| 204 | + } | |
| 205 | + | |
| 206 | +class ClucHAwerkHyperopt_BTC(ClucHAwerkHyperopt): | |
| 207 | + | |
| 208 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_BTC -e 500 --spaces buy --timeframe 1m --timerange 20210101- | |
| 209 | + # 412/500: 572 trades. 505/17/50 Wins/Draws/Losses. Avg profit 1.80%. Median profit 2.27%. Total profit 0.01028714 BTC ( 1027.06Σ%). Avg duration 281.3 min. Objective: -152.09192 | |
| 210 | + # Buy hyperspace params: | |
| 211 | + buy_params = { | |
| 212 | + 'bbdelta-close': 0.01192, | |
| 213 | + 'bbdelta-tail': 0.96183, | |
| 214 | + 'close-bblower': 0.01212, | |
| 215 | + 'closedelta-close': 0.01039, | |
| 216 | + 'rocr-1h': 0.53422, | |
| 217 | + 'volume': 27 | |
| 218 | + } | |
| 219 | + | |
| 220 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_BTC -e 500 --spaces sell --timeframe 1m --timerange 20210101- | |
| 221 | + # 284/500: 575 trades. 508/17/50 Wins/Draws/Losses. Avg profit 1.80%. Median profit 2.25%. Total profit 0.01036281 BTC ( 1034.62Σ%). Avg duration 279.4 min. Objective: -100.84858 | |
| 222 | + # Sell hyperspace params: | |
| 223 | + sell_params = { | |
| 224 | + 'sell-bbmiddle-close': 0.98016, | |
| 225 | + 'sell-rocr-1h': 0.86823 | |
| 226 | + } | |
| 227 | + | |
| 228 | +class ClucHAwerkHyperopt_USD(ClucHAwerkHyperopt): | |
| 229 | + | |
| 230 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces buy --timeframe 1m --timerange 20210101- | |
| 231 | + # 470/500: 680 trades. 631/27/22 Wins/Draws/Losses. Avg profit 2.91%. Median profit 2.93%. Total profit 991.61804628 USD ( 1980.07Σ%). Avg duration 184.2 min. Objective: -186.95550 | |
| 232 | + # Buy hyperspace params: | |
| 233 | + buy_params = { | |
| 234 | + 'bbdelta-close': 0.01806, | |
| 235 | + 'bbdelta-tail': 0.85912, | |
| 236 | + 'close-bblower': 0.01158, | |
| 237 | + 'closedelta-close': 0.01466, | |
| 238 | + 'rocr-1h': 0.51901, | |
| 239 | + 'volume': 26 | |
| 240 | + } | |
| 241 | + | |
| 242 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces sell --timeframe 1m --timerange 20210101- | |
| 243 | + # 1/500: 679 trades. 630/27/22 Wins/Draws/Losses. Avg profit 2.90%. Median profit 2.93%. Total profit 986.25885773 USD ( 1969.37Σ%). Avg duration 184.6 min. Objective: -277.19845 | |
| 244 | + # Sell hyperspace params: | |
| 245 | + sell_params = { | |
| 246 | + 'sell-bbmiddle-close': 1.06163, | |
| 247 | + 'sell-rocr-1h': 0.63285 | |
| 248 | + } | |
| No newline at the end of the file |
added hyperopts/old/CluckieHyp.py +179 −0
| @@ -0,0 +1,179 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class Cluckie(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.00732, | |
| 28 | + 'bbdelta-tail': 0.94138, | |
| 29 | + 'close-bblower': 0.0199, | |
| 30 | + 'closedelta-close': 0.01825, | |
| 31 | + 'fisher': -0.22987, | |
| 32 | + 'volume': 16 | |
| 33 | + } | |
| 34 | + | |
| 35 | + # Sell hyperspace params: | |
| 36 | + sell_params = { | |
| 37 | + 'sell-adx': 70, | |
| 38 | + 'sell-fisher': 0.95954 | |
| 39 | + } | |
| 40 | + | |
| 41 | + @staticmethod | |
| 42 | + def indicator_space() -> List[Dimension]: | |
| 43 | + return [ | |
| 44 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 45 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 46 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 47 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 48 | + Integer(15, 40, name='volume'), | |
| 49 | + Real(-1.0, 0, name='fisher') | |
| 50 | + ] | |
| 51 | + | |
| 52 | + @staticmethod | |
| 53 | + def sell_indicator_space() -> List[Dimension]: | |
| 54 | + return [ | |
| 55 | + Integer(30, 90, name='sell-adx'), | |
| 56 | + Real(0, 1.0, name='sell-fisher') | |
| 57 | + ] | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + | |
| 62 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + dataframe.loc[ | |
| 65 | + ( | |
| 66 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 67 | + ) & | |
| 68 | + (( | |
| 69 | + (dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close'])) & | |
| 70 | + (dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close'])) & | |
| 71 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 72 | + (dataframe['close'].lt(dataframe['lower-bb1'].shift())) & | |
| 73 | + (dataframe['close'].le(dataframe['close'].shift())) | |
| 74 | + ) | | |
| 75 | + ( | |
| 76 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 77 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 78 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 79 | + )), | |
| 80 | + 'buy' | |
| 81 | + ] = 1 | |
| 82 | + | |
| 83 | + return dataframe | |
| 84 | + | |
| 85 | + return populate_buy_trend | |
| 86 | + | |
| 87 | + @staticmethod | |
| 88 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 89 | + | |
| 90 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 91 | + | |
| 92 | + dataframe.loc[ | |
| 93 | + ( | |
| 94 | + (dataframe['adx'] > params['sell-adx']) & | |
| 95 | + (dataframe['tema'] > dataframe['mid-bb2']) & | |
| 96 | + (dataframe['tema'] < dataframe['tema'].shift(1)) & | |
| 97 | + (dataframe['fisher-rsi'].gt(params['sell-fisher'])) | |
| 98 | + ) | |
| 99 | + , | |
| 100 | + 'sell' | |
| 101 | + ] = 1 | |
| 102 | + | |
| 103 | + return dataframe | |
| 104 | + | |
| 105 | + return populate_sell_trend | |
| 106 | + | |
| 107 | + | |
| 108 | + @staticmethod | |
| 109 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 110 | + | |
| 111 | + roi_table = {} | |
| 112 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 113 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 114 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 115 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 116 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 117 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 118 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 119 | + | |
| 120 | + return roi_table | |
| 121 | + | |
| 122 | + @staticmethod | |
| 123 | + def roi_space() -> List[Dimension]: | |
| 124 | + | |
| 125 | + return [ | |
| 126 | + Integer(1, 5, name='roi_t6'), | |
| 127 | + Integer(1, 10, name='roi_t5'), | |
| 128 | + Integer(1, 15, name='roi_t4'), | |
| 129 | + Integer(15, 20, name='roi_t3'), | |
| 130 | + Integer(20, 25, name='roi_t2'), | |
| 131 | + Integer(25, 60, name='roi_t1'), | |
| 132 | + | |
| 133 | + Real(0.005, 0.10, name='roi_p6'), | |
| 134 | + Real(0.005, 0.07, name='roi_p5'), | |
| 135 | + Real(0.005, 0.05, name='roi_p4'), | |
| 136 | + Real(0.005, 0.025, name='roi_p3'), | |
| 137 | + Real(0.005, 0.01, name='roi_p2'), | |
| 138 | + Real(0.003, 0.007, name='roi_p1'), | |
| 139 | + ] | |
| 140 | + | |
| 141 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 142 | + params = self.buy_params | |
| 143 | + | |
| 144 | + dataframe.loc[ | |
| 145 | + ( | |
| 146 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 147 | + ) & | |
| 148 | + (( | |
| 149 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 150 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 151 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 152 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 153 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 154 | + ) | | |
| 155 | + ( | |
| 156 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 157 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 158 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 159 | + )), | |
| 160 | + 'buy' | |
| 161 | + ] = 1 | |
| 162 | + | |
| 163 | + return dataframe | |
| 164 | + | |
| 165 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 166 | + params = self.sell_params | |
| 167 | + | |
| 168 | + dataframe.loc[ | |
| 169 | + ( | |
| 170 | + (dataframe['adx'] > params['sell-adx']) & | |
| 171 | + (dataframe['tema'] > dataframe['mid-bb2']) & | |
| 172 | + (dataframe['tema'] < dataframe['tema'].shift(1)) & | |
| 173 | + (dataframe['fisher-rsi'].gt(params['sell-fisher'])) | |
| 174 | + ) | |
| 175 | + , | |
| 176 | + 'sell' | |
| 177 | + ] = 1 | |
| 178 | + | |
| 179 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/FisherHullHyp.py +113 −0
| @@ -0,0 +1,113 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | +from technical.indicators import hull_moving_average | |
| 19 | + | |
| 20 | +class FisherHullHyp(IHyperOpt): | |
| 21 | + | |
| 22 | + @staticmethod | |
| 23 | + def indicator_space() -> List[Dimension]: | |
| 24 | + return [ | |
| 25 | + Real(-100.0, 100.0, name='cci-buy'), | |
| 26 | + Real(-1.0, 1.0, name='fisher-buy') | |
| 27 | + ] | |
| 28 | + | |
| 29 | + @staticmethod | |
| 30 | + def sell_indicator_space() -> List[Dimension]: | |
| 31 | + return [ | |
| 32 | + Real(-100.0, 100.0, name='cci-sell'), | |
| 33 | + Real(-1.0, 1.0, name='fisher-sell') | |
| 34 | + ] | |
| 35 | + | |
| 36 | + @staticmethod | |
| 37 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 38 | + """ | |
| 39 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 40 | + """ | |
| 41 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 42 | + """ | |
| 43 | + Buy strategy Hyperopt will build and use. | |
| 44 | + """ | |
| 45 | + dataframe.loc[ | |
| 46 | + ( | |
| 47 | + (dataframe['hma'] < dataframe['hma'].shift()) & | |
| 48 | + (dataframe['cci'] <= params['cci-buy']) & | |
| 49 | + (dataframe['fisher_rsi'] < params['fisher-buy']) | |
| 50 | + ) | |
| 51 | + , | |
| 52 | + 'buy' | |
| 53 | + ] = 1 | |
| 54 | + | |
| 55 | + return dataframe | |
| 56 | + | |
| 57 | + return populate_buy_trend | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + """ | |
| 62 | + Define the sell strategy parameters to be used by hyperopt | |
| 63 | + """ | |
| 64 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 65 | + | |
| 66 | + dataframe.loc[ | |
| 67 | + ( | |
| 68 | + (dataframe['hma'] > dataframe['hma'].shift()) & | |
| 69 | + (dataframe['cci'] >= params['cci-sell']) & | |
| 70 | + (dataframe['fisher_rsi'] > params['fisher-sell']) & | |
| 71 | + (dataframe['volume'] > 0) | |
| 72 | + ) | |
| 73 | + , | |
| 74 | + 'sell' | |
| 75 | + ] = 1 | |
| 76 | + | |
| 77 | + return dataframe | |
| 78 | + | |
| 79 | + return populate_sell_trend | |
| 80 | + | |
| 81 | + | |
| 82 | + @staticmethod | |
| 83 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 84 | + | |
| 85 | + roi_table = {} | |
| 86 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 87 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 88 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 89 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 90 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 91 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 92 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 93 | + | |
| 94 | + return roi_table | |
| 95 | + | |
| 96 | + @staticmethod | |
| 97 | + def roi_space() -> List[Dimension]: | |
| 98 | + | |
| 99 | + return [ | |
| 100 | + Integer(1, 15, name='roi_t6'), | |
| 101 | + Integer(1, 45, name='roi_t5'), | |
| 102 | + Integer(1, 90, name='roi_t4'), | |
| 103 | + Integer(45, 120, name='roi_t3'), | |
| 104 | + Integer(45, 180, name='roi_t2'), | |
| 105 | + Integer(90, 200, name='roi_t1'), | |
| 106 | + | |
| 107 | + Real(0.005, 0.10, name='roi_p6'), | |
| 108 | + Real(0.005, 0.07, name='roi_p5'), | |
| 109 | + Real(0.005, 0.05, name='roi_p4'), | |
| 110 | + Real(0.005, 0.025, name='roi_p3'), | |
| 111 | + Real(0.005, 0.01, name='roi_p2'), | |
| 112 | + Real(0.003, 0.007, name='roi_p1'), | |
| 113 | + ] | |
| No newline at the end of the file |
added hyperopts/old/GuacamoleHyp.py +104 −0
| @@ -0,0 +1,104 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class GuacamoleHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Real(-1.00, 1.00, name='macd'), | |
| 25 | + Integer(-1.00, 1.00, name='macdhist'), | |
| 26 | + Integer(40, 90, name='rmi') | |
| 27 | + ] | |
| 28 | + | |
| 29 | + @staticmethod | |
| 30 | + def sell_indicator_space() -> List[Dimension]: | |
| 31 | + return [] | |
| 32 | + | |
| 33 | + @staticmethod | |
| 34 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 35 | + | |
| 36 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 37 | + | |
| 38 | + conditions = [] | |
| 39 | + | |
| 40 | + conditions.append(dataframe['kama-3'] > dataframe['kama-21']) | |
| 41 | + conditions.append(dataframe['macd'] > dataframe['macdsignal']) | |
| 42 | + conditions.append(dataframe['macd'] > params['macd']) | |
| 43 | + conditions.append(dataframe['macdhist'] > params['macdhist']) | |
| 44 | + conditions.append(dataframe['rmi'] > dataframe['rmi'].shift()) | |
| 45 | + conditions.append(dataframe['rmi'] > params['rmi']) | |
| 46 | + conditions.append(dataframe['volume'] < (dataframe['volume_ma'] * 20)) | |
| 47 | + | |
| 48 | + conditions.append(dataframe['volume'] > 0) | |
| 49 | + | |
| 50 | + if conditions: | |
| 51 | + dataframe.loc[ | |
| 52 | + reduce(lambda x, y: x & y, conditions), | |
| 53 | + 'buy'] = 1 | |
| 54 | + | |
| 55 | + return dataframe | |
| 56 | + | |
| 57 | + return populate_buy_trend | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + | |
| 62 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + """ | |
| 64 | + no sell signal | |
| 65 | + """ | |
| 66 | + dataframe['sell'] = 0 | |
| 67 | + return dataframe | |
| 68 | + | |
| 69 | + return populate_sell_trend | |
| 70 | + | |
| 71 | + | |
| 72 | + @staticmethod | |
| 73 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 74 | + | |
| 75 | + roi_table = {} | |
| 76 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 77 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 78 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 79 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 80 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 81 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 82 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0.0025 | |
| 83 | + | |
| 84 | + return roi_table | |
| 85 | + | |
| 86 | + @staticmethod | |
| 87 | + def roi_space() -> List[Dimension]: | |
| 88 | + # min / max min / max | |
| 89 | + return [ # 0 : 0.100 / 0.200 | |
| 90 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.100 | |
| 91 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.050 | |
| 92 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.030 | |
| 93 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.015 | |
| 94 | + Integer(45, 90, name='roi_t2'), # 81 -> 180 : 0.003 / 0.005 | |
| 95 | + Integer(90, 180, name='roi_t1'), # 171 -> 360 : 0.0025 (should be 0 but I changed it above.) | |
| 96 | + | |
| 97 | + Real(0.05, 0.10, name='roi_p6'), | |
| 98 | + Real(0.02, 0.05, name='roi_p5'), | |
| 99 | + Real(0.015, 0.020, name='roi_p4'), | |
| 100 | + Real(0.005, 0.015, name='roi_p3'), | |
| 101 | + Real(0.007, 0.01, name='roi_p2'), | |
| 102 | + Real(0.003, 0.005, name='roi_p1'), | |
| 103 | + ] | |
| 104 | + |
added hyperopts/old/HackieHyp.py +189 −0
| @@ -0,0 +1,189 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class HackieHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.00732, | |
| 28 | + 'bbdelta-tail': 0.94138, | |
| 29 | + 'close-bblower': 0.0199, | |
| 30 | + 'closedelta-close': 0.01825, | |
| 31 | + 'fisher': -0.22987, | |
| 32 | + 'volume': 16, | |
| 33 | + 'buy-rmax1' : 0.99, | |
| 34 | + 'buy-rmax2' : 0.98 | |
| 35 | + } | |
| 36 | + | |
| 37 | + # Sell hyperspace params: | |
| 38 | + sell_params = { | |
| 39 | + 'sell-adx': 70, | |
| 40 | + 'sell-fisher': 0.95954 | |
| 41 | + } | |
| 42 | + | |
| 43 | + @staticmethod | |
| 44 | + def indicator_space() -> List[Dimension]: | |
| 45 | + return [ | |
| 46 | + Real(0.700, 1.110, name='buy-rmax1'), | |
| 47 | + Real(0.699, 1.099, name='buy-rmax2'), | |
| 48 | + Real(0.0005, 0.02, name='bbdelta-close'), | |
| 49 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 50 | + Real(0.7, 1.0, name='bbdelta-tail'), | |
| 51 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 52 | + Integer(15, 40, name='volume'), | |
| 53 | + Real(-1.0, 0, name='fisher') | |
| 54 | + ] | |
| 55 | + | |
| 56 | + @staticmethod | |
| 57 | + def sell_indicator_space() -> List[Dimension]: | |
| 58 | + return [ | |
| 59 | + Integer(30, 90, name='sell-adx'), | |
| 60 | + Real(0, 1.0, name='sell-fisher') | |
| 61 | + ] | |
| 62 | + | |
| 63 | + @staticmethod | |
| 64 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 65 | + | |
| 66 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 67 | + | |
| 68 | + dataframe.loc[ | |
| 69 | + ( (params['buy-rmax1']> params['buy-rmax2']) & | |
| 70 | + (dataframe['fisher-rsi'].lt(params['fisher'])) & | |
| 71 | + (dataframe['ha_high'] >= (dataframe['rmax'] * params['buy-rmax1'])) & | |
| 72 | + (dataframe['ha_high'].shift() >= (dataframe['rmax']) * params['buy-rmax2']) | |
| 73 | + ) & | |
| 74 | + (( | |
| 75 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 76 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 77 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 78 | + (dataframe['ha_close'].lt(dataframe['lower-bb1'].shift())) & | |
| 79 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift())) | |
| 80 | + ) | | |
| 81 | + ( | |
| 82 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 83 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 84 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 85 | + )), | |
| 86 | + 'buy' | |
| 87 | + ] = 1 | |
| 88 | + | |
| 89 | + return dataframe | |
| 90 | + | |
| 91 | + return populate_buy_trend | |
| 92 | + | |
| 93 | + @staticmethod | |
| 94 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 95 | + | |
| 96 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 97 | + | |
| 98 | + dataframe.loc[ | |
| 99 | + ( | |
| 100 | + #(dataframe['ha_close'] > dataframe['rmax']) & | |
| 101 | + (dataframe['adx'] > params['sell-adx']) & | |
| 102 | + #(dataframe['tema'] > dataframe['mid-bb2']) & | |
| 103 | + (dataframe['tema'] < dataframe['tema'].shift(1)) & | |
| 104 | + (dataframe['fisher-rsi'].gt(params['sell-fisher'])) | |
| 105 | + ) | |
| 106 | + , | |
| 107 | + 'sell' | |
| 108 | + ] = 1 | |
| 109 | + | |
| 110 | + return dataframe | |
| 111 | + | |
| 112 | + return populate_sell_trend | |
| 113 | + | |
| 114 | + | |
| 115 | + @staticmethod | |
| 116 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 117 | + | |
| 118 | + roi_table = {} | |
| 119 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 120 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 121 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 122 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 123 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 124 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 125 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 126 | + | |
| 127 | + return roi_table | |
| 128 | + | |
| 129 | + @staticmethod | |
| 130 | + def roi_space() -> List[Dimension]: | |
| 131 | + | |
| 132 | + return [ | |
| 133 | + Integer(1, 5, name='roi_t6'), | |
| 134 | + Integer(1, 10, name='roi_t5'), | |
| 135 | + Integer(1, 15, name='roi_t4'), | |
| 136 | + Integer(15, 20, name='roi_t3'), | |
| 137 | + Integer(20, 25, name='roi_t2'), | |
| 138 | + Integer(25, 60, name='roi_t1'), | |
| 139 | + | |
| 140 | + Real(0.005, 0.10, name='roi_p6'), | |
| 141 | + Real(0.005, 0.07, name='roi_p5'), | |
| 142 | + Real(0.005, 0.05, name='roi_p4'), | |
| 143 | + Real(0.005, 0.025, name='roi_p3'), | |
| 144 | + Real(0.005, 0.01, name='roi_p2'), | |
| 145 | + Real(0.003, 0.007, name='roi_p1'), | |
| 146 | + ] | |
| 147 | + | |
| 148 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 149 | + params = self.buy_params | |
| 150 | + | |
| 151 | + dataframe.loc[ | |
| 152 | + ( (params['buy-rmax1']> params['buy-rmax2']) & | |
| 153 | + (dataframe['fisher-rsi'].lt(params['fisher'])) & | |
| 154 | + (dataframe['ha_high'] >= (dataframe['rmax'] * params['buy-rmax1'])) & | |
| 155 | + (dataframe['ha_high'].shift() >= (dataframe['rmax']) * params['buy-rmax2']) | |
| 156 | + ) & | |
| 157 | + (( | |
| 158 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 159 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 160 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 161 | + (dataframe['ha_close'].lt(dataframe['lower-bb1'].shift())) & | |
| 162 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift())) | |
| 163 | + ) | | |
| 164 | + ( | |
| 165 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 166 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 167 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 168 | + )), | |
| 169 | + 'buy' | |
| 170 | + ] = 1 | |
| 171 | + | |
| 172 | + return dataframe | |
| 173 | + | |
| 174 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 175 | + params = self.sell_params | |
| 176 | + | |
| 177 | + dataframe.loc[ | |
| 178 | + ( | |
| 179 | + #(dataframe['ha_close'] > dataframe['rmax']) & | |
| 180 | + (dataframe['adx'] > params['sell-adx']) & | |
| 181 | + #(dataframe['tema'] > dataframe['mid-bb2']) & | |
| 182 | + (dataframe['tema'] < dataframe['tema'].shift(1)) & | |
| 183 | + (dataframe['fisher-rsi'].gt(params['sell-fisher'])) | |
| 184 | + ) | |
| 185 | + , | |
| 186 | + 'sell' | |
| 187 | + ] = 1 | |
| 188 | + | |
| 189 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/HacklemoreOpt.py +177 −0
| @@ -0,0 +1,177 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class HacklemoreOpt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.02514, | |
| 28 | + 'bbdelta-tail': 1.19782, | |
| 29 | + 'buy-rmi': 1, | |
| 30 | + 'closedelta-close': 0.01671, | |
| 31 | + 'volume': 9 | |
| 32 | + } | |
| 33 | + | |
| 34 | + # Sell hyperspace params: | |
| 35 | + sell_params = { | |
| 36 | + 'sell-adx': 5 | |
| 37 | + } | |
| 38 | + | |
| 39 | + @staticmethod | |
| 40 | + def indicator_space() -> List[Dimension]: | |
| 41 | + return [ | |
| 42 | + Integer(0, 50, name='buy-rmi'), | |
| 43 | + Real(0.0005, 0.03, name='bbdelta-close'), | |
| 44 | + Real(0.0005, 0.03, name='closedelta-close'), | |
| 45 | + Real(0.7, 1.2, name='bbdelta-tail'), | |
| 46 | + Integer(5, 40, name='volume') | |
| 47 | + ] | |
| 48 | + | |
| 49 | + @staticmethod | |
| 50 | + def sell_indicator_space() -> List[Dimension]: | |
| 51 | + return [ | |
| 52 | + Integer(0, 50, name='sell-adx'), | |
| 53 | + ] | |
| 54 | + | |
| 55 | + @staticmethod | |
| 56 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 57 | + | |
| 58 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 59 | + | |
| 60 | + conditions = [] | |
| 61 | + | |
| 62 | + conditions.append( | |
| 63 | + (dataframe['rmi'] >= params['buy-rmi']) & | |
| 64 | + (dataframe['rmi'].gt(dataframe['rmi'].shift(1))) & | |
| 65 | + (dataframe['ha_close'].gt(dataframe['sar'])) & | |
| 66 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 67 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 68 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 69 | + (dataframe['ha_close'].lt(dataframe['ema_slow'])) & | |
| 70 | + (dataframe['volume'].lt(dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 71 | + ) | |
| 72 | + | |
| 73 | + conditions.append(dataframe['volume'].gt(0)) | |
| 74 | + | |
| 75 | + if conditions: | |
| 76 | + dataframe.loc[ | |
| 77 | + reduce(lambda x, y: x & y, conditions), | |
| 78 | + 'buy'] = 1 | |
| 79 | + | |
| 80 | + return dataframe | |
| 81 | + | |
| 82 | + return populate_buy_trend | |
| 83 | + | |
| 84 | + @staticmethod | |
| 85 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 86 | + | |
| 87 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 88 | + | |
| 89 | + dataframe.loc[ | |
| 90 | + ( | |
| 91 | + (dataframe['adx'] < params['sell-adx']) & | |
| 92 | + (dataframe['tema'].lt(dataframe['tema'].shift(1))) & | |
| 93 | + (dataframe['rmi'].lt(dataframe['rmi'].shift(1))) & | |
| 94 | + (dataframe['rmi'].shift(1).gt(dataframe['rmi'].shift(2))) & | |
| 95 | + (dataframe['ha_close'].lt(dataframe['sar'])) | |
| 96 | + ), | |
| 97 | + 'sell' | |
| 98 | + ] = 1 | |
| 99 | + | |
| 100 | + return dataframe | |
| 101 | + | |
| 102 | + return populate_sell_trend | |
| 103 | + | |
| 104 | + | |
| 105 | + @staticmethod | |
| 106 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 107 | + | |
| 108 | + roi_table = {} | |
| 109 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 110 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 111 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 112 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 113 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 114 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 115 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0.0025 | |
| 116 | + | |
| 117 | + return roi_table | |
| 118 | + | |
| 119 | + @staticmethod | |
| 120 | + def roi_space() -> List[Dimension]: | |
| 121 | + # min / max min / max | |
| 122 | + return [ # 0 : 0.100 / 0.200 | |
| 123 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.100 | |
| 124 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.050 | |
| 125 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.030 | |
| 126 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.015 | |
| 127 | + Integer(45, 90, name='roi_t2'), # 81 -> 180 : 0.003 / 0.005 | |
| 128 | + Integer(90, 180, name='roi_t1'), # 171 -> 360 : 0.0025 (should be 0 but I changed it above.) | |
| 129 | + | |
| 130 | + Real(0.05, 0.10, name='roi_p6'), | |
| 131 | + Real(0.02, 0.05, name='roi_p5'), | |
| 132 | + Real(0.015, 0.020, name='roi_p4'), | |
| 133 | + Real(0.005, 0.015, name='roi_p3'), | |
| 134 | + Real(0.007, 0.01, name='roi_p2'), | |
| 135 | + Real(0.003, 0.005, name='roi_p1'), | |
| 136 | + ] | |
| 137 | + | |
| 138 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 139 | + params = self.buy_params | |
| 140 | + | |
| 141 | + conditions = [] | |
| 142 | + | |
| 143 | + conditions.append( | |
| 144 | + (dataframe['rmi'] >= params['buy-rmi']) & | |
| 145 | + (dataframe['rmi'].gt(dataframe['rmi'].shift(1))) & | |
| 146 | + (dataframe['ha_close'].gt(dataframe['sar'])) & | |
| 147 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 148 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 149 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 150 | + (dataframe['ha_close'].lt(dataframe['ema_slow'])) & | |
| 151 | + (dataframe['volume'].lt(dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 152 | + ) | |
| 153 | + | |
| 154 | + conditions.append(dataframe['volume'].gt(0)) | |
| 155 | + | |
| 156 | + if conditions: | |
| 157 | + dataframe.loc[ | |
| 158 | + reduce(lambda x, y: x & y, conditions), | |
| 159 | + 'buy'] = 1 | |
| 160 | + | |
| 161 | + return dataframe | |
| 162 | + | |
| 163 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 164 | + params = self.sell_params | |
| 165 | + | |
| 166 | + dataframe.loc[ | |
| 167 | + ( | |
| 168 | + (dataframe['adx'] < params['sell-adx']) & | |
| 169 | + (dataframe['tema'].lt(dataframe['tema'].shift(1))) & | |
| 170 | + (dataframe['rmi'].lt(dataframe['rmi'].shift(1))) & | |
| 171 | + (dataframe['rmi'].shift(1).gt(dataframe['rmi'].shift(2))) & | |
| 172 | + (dataframe['ha_close'].lt(dataframe['sar'])) | |
| 173 | + ), | |
| 174 | + 'sell' | |
| 175 | + ] = 1 | |
| 176 | + | |
| 177 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/HacklemostOpt.py +177 −0
| @@ -0,0 +1,177 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class HacklemostOpt(IHyperOpt): | |
| 20 | + | |
| 21 | + """ | |
| 22 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 23 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 24 | + """ | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.02514, | |
| 28 | + 'bbdelta-tail': 1.19782, | |
| 29 | + 'buy-rmi': 1, | |
| 30 | + 'closedelta-close': 0.01671, | |
| 31 | + 'volume': 9 | |
| 32 | + } | |
| 33 | + | |
| 34 | + # Sell hyperspace params: | |
| 35 | + sell_params = { | |
| 36 | + 'sell-adx': 5 | |
| 37 | + } | |
| 38 | + | |
| 39 | + @staticmethod | |
| 40 | + def indicator_space() -> List[Dimension]: | |
| 41 | + return [ | |
| 42 | + Integer(0, 50, name='buy-rmi'), | |
| 43 | + Real(0.0005, 0.03, name='bbdelta-close'), | |
| 44 | + Real(0.0005, 0.03, name='closedelta-close'), | |
| 45 | + Real(0.7, 1.2, name='bbdelta-tail'), | |
| 46 | + Integer(5, 40, name='volume') | |
| 47 | + ] | |
| 48 | + | |
| 49 | + @staticmethod | |
| 50 | + def sell_indicator_space() -> List[Dimension]: | |
| 51 | + return [ | |
| 52 | + Integer(0, 50, name='sell-adx'), | |
| 53 | + ] | |
| 54 | + | |
| 55 | + @staticmethod | |
| 56 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 57 | + | |
| 58 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 59 | + | |
| 60 | + conditions = [] | |
| 61 | + | |
| 62 | + conditions.append( | |
| 63 | + (dataframe['rmi'] >= params['buy-rmi']) & | |
| 64 | + (dataframe['rmi'].gt(dataframe['rmi'].shift(1))) & | |
| 65 | + (dataframe['ha_close'].gt(dataframe['sar'])) & | |
| 66 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 67 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 68 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 69 | + (dataframe['ha_close'].lt(dataframe['ema_slow'])) & | |
| 70 | + (dataframe['volume'].lt(dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 71 | + ) | |
| 72 | + | |
| 73 | + conditions.append(dataframe['volume'].gt(0)) | |
| 74 | + | |
| 75 | + if conditions: | |
| 76 | + dataframe.loc[ | |
| 77 | + reduce(lambda x, y: x & y, conditions), | |
| 78 | + 'buy'] = 1 | |
| 79 | + | |
| 80 | + return dataframe | |
| 81 | + | |
| 82 | + return populate_buy_trend | |
| 83 | + | |
| 84 | + @staticmethod | |
| 85 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 86 | + | |
| 87 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 88 | + | |
| 89 | + dataframe.loc[ | |
| 90 | + ( | |
| 91 | + (dataframe['adx'] < params['sell-adx']) & | |
| 92 | + (dataframe['tema'].lt(dataframe['tema'].shift(1))) & | |
| 93 | + (dataframe['rmi'].lt(dataframe['rmi'].shift(1))) & | |
| 94 | + (dataframe['rmi'].shift(1).gt(dataframe['rmi'].shift(2))) & | |
| 95 | + (dataframe['ha_close'].lt(dataframe['sar'])) | |
| 96 | + ), | |
| 97 | + 'sell' | |
| 98 | + ] = 1 | |
| 99 | + | |
| 100 | + return dataframe | |
| 101 | + | |
| 102 | + return populate_sell_trend | |
| 103 | + | |
| 104 | + | |
| 105 | + @staticmethod | |
| 106 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 107 | + | |
| 108 | + roi_table = {} | |
| 109 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 110 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 111 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 112 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 113 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 114 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 115 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0.0025 | |
| 116 | + | |
| 117 | + return roi_table | |
| 118 | + | |
| 119 | + @staticmethod | |
| 120 | + def roi_space() -> List[Dimension]: | |
| 121 | + # min / max min / max | |
| 122 | + return [ # 0 : 0.100 / 0.200 | |
| 123 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.100 | |
| 124 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.050 | |
| 125 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.030 | |
| 126 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.015 | |
| 127 | + Integer(45, 90, name='roi_t2'), # 81 -> 180 : 0.003 / 0.005 | |
| 128 | + Integer(90, 180, name='roi_t1'), # 171 -> 360 : 0.0025 (should be 0 but I changed it above.) | |
| 129 | + | |
| 130 | + Real(0.05, 0.10, name='roi_p6'), | |
| 131 | + Real(0.02, 0.05, name='roi_p5'), | |
| 132 | + Real(0.015, 0.020, name='roi_p4'), | |
| 133 | + Real(0.005, 0.015, name='roi_p3'), | |
| 134 | + Real(0.007, 0.01, name='roi_p2'), | |
| 135 | + Real(0.003, 0.005, name='roi_p1'), | |
| 136 | + ] | |
| 137 | + | |
| 138 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 139 | + params = self.buy_params | |
| 140 | + | |
| 141 | + conditions = [] | |
| 142 | + | |
| 143 | + conditions.append( | |
| 144 | + (dataframe['rmi'] >= params['buy-rmi']) & | |
| 145 | + (dataframe['rmi'].gt(dataframe['rmi'].shift(1))) & | |
| 146 | + (dataframe['ha_close'].gt(dataframe['sar'])) & | |
| 147 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 148 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 149 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 150 | + (dataframe['ha_close'].lt(dataframe['ema_slow'])) & | |
| 151 | + (dataframe['volume'].lt(dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 152 | + ) | |
| 153 | + | |
| 154 | + conditions.append(dataframe['volume'].gt(0)) | |
| 155 | + | |
| 156 | + if conditions: | |
| 157 | + dataframe.loc[ | |
| 158 | + reduce(lambda x, y: x & y, conditions), | |
| 159 | + 'buy'] = 1 | |
| 160 | + | |
| 161 | + return dataframe | |
| 162 | + | |
| 163 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 164 | + params = self.sell_params | |
| 165 | + | |
| 166 | + dataframe.loc[ | |
| 167 | + ( | |
| 168 | + (dataframe['adx'] < params['sell-adx']) & | |
| 169 | + (dataframe['tema'].lt(dataframe['tema'].shift(1))) & | |
| 170 | + (dataframe['rmi'].lt(dataframe['rmi'].shift(1))) & | |
| 171 | + (dataframe['rmi'].shift(1).gt(dataframe['rmi'].shift(2))) & | |
| 172 | + (dataframe['ha_close'].lt(dataframe['sar'])) | |
| 173 | + ), | |
| 174 | + 'sell' | |
| 175 | + ] = 1 | |
| 176 | + | |
| 177 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/KAMACCIRSI_Hyperopt.py +191 −0
| @@ -0,0 +1,191 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +""" | |
| 20 | +author@: werkkrew | |
| 21 | +github@: https://github.com/werkkrew/freqtrade-strategies | |
| 22 | + | |
| 23 | +Hyperopt for my KAMACCIRSI strategy. | |
| 24 | + | |
| 25 | +Optimizes: | |
| 26 | +- Period for indicators within specified ranges | |
| 27 | +- Should RSI and/or CCI be enabled | |
| 28 | + - Cross points for RSI / CCI on both buy and sell side separately | |
| 29 | +- Should KAMA use a crossing point or slope | |
| 30 | + | |
| 31 | +Default ranges for cross points: | |
| 32 | +RSI: | |
| 33 | + - Buy: 0-100 | |
| 34 | + - Sell: 0-100 | |
| 35 | +CCI: | |
| 36 | + - Buy: 0-200 | |
| 37 | + - Sell: -200-0 | |
| 38 | +""" | |
| 39 | + | |
| 40 | +class KAMACCIRSI_new_Hyperopt(IHyperOpt): | |
| 41 | + | |
| 42 | + @staticmethod | |
| 43 | + def indicator_space() -> List[Dimension]: | |
| 44 | + | |
| 45 | + return [ | |
| 46 | + Integer(100, 200, name='cci-limit'), | |
| 47 | + Integer(40, 90, name='rsi-limit'), | |
| 48 | + Categorical([True, False], name='cci-enabled'), | |
| 49 | + Categorical([True, False], name='rsi-enabled'), | |
| 50 | + Categorical(['cross', 'slope'], name='kama-trigger') | |
| 51 | + ] | |
| 52 | + | |
| 53 | + @staticmethod | |
| 54 | + def sell_indicator_space() -> List[Dimension]: | |
| 55 | + | |
| 56 | + return [ | |
| 57 | + Integer(-200, -100, name='sell-cci-limit'), | |
| 58 | + Integer(40, 90, name='sell-rsi-limit'), | |
| 59 | + Categorical([True, False], name='sell-cci-enabled'), | |
| 60 | + Categorical([True, False], name='sell-rsi-enabled'), | |
| 61 | + Categorical(['cross', 'slope'], name='sell-kama-trigger') | |
| 62 | + ] | |
| 63 | + | |
| 64 | + @staticmethod | |
| 65 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 66 | + | |
| 67 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 68 | + | |
| 69 | + conditions = [] | |
| 70 | + # Guards | |
| 71 | + if params.get('rsi-enabled'): | |
| 72 | + conditions.append( | |
| 73 | + ( | |
| 74 | + qtpylib.crossed_above(dataframe['rsi'], params['rsi-limit']) | | |
| 75 | + qtpylib.crossed_above(dataframe['rsi'].shift(1), params['rsi-limit']) | | |
| 76 | + qtpylib.crossed_above(dataframe['rsi'].shift(2), params['rsi-limit']) | |
| 77 | + ) & | |
| 78 | + ( | |
| 79 | + dataframe['rsi'].gt(params['rsi-limit']) | |
| 80 | + ) | |
| 81 | + ) | |
| 82 | + if params.get('cci-enabled'): | |
| 83 | + conditions.append( | |
| 84 | + ( | |
| 85 | + qtpylib.crossed_above(dataframe['cci'], params['cci-limit']) | | |
| 86 | + qtpylib.crossed_above(dataframe['cci'].shift(1), params['cci-limit']) | | |
| 87 | + qtpylib.crossed_above(dataframe['cci'].shift(2), params['cci-limit']) | |
| 88 | + ) & | |
| 89 | + ( | |
| 90 | + dataframe['cci'].gt(params['cci-limit']) | |
| 91 | + ) | |
| 92 | + ) | |
| 93 | + | |
| 94 | + # Triggers | |
| 95 | + if params.get('kama-trigger') == 'cross': | |
| 96 | + conditions.append(qtpylib.crossed_above(dataframe['kama-short'], dataframe['kama-long'])) | |
| 97 | + if params.get('kama-trigger') == 'slope': | |
| 98 | + conditions.append(dataframe['kama-long'] > dataframe['kama-long'].shift(1)) | |
| 99 | + | |
| 100 | + # Check that volume is not 0 | |
| 101 | + conditions.append(dataframe['volume'] > 0) | |
| 102 | + | |
| 103 | + if conditions: | |
| 104 | + dataframe.loc[ | |
| 105 | + reduce(lambda x, y: x & y, conditions), | |
| 106 | + 'buy'] = 1 | |
| 107 | + | |
| 108 | + return dataframe | |
| 109 | + | |
| 110 | + return populate_buy_trend | |
| 111 | + | |
| 112 | + @staticmethod | |
| 113 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 114 | + | |
| 115 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + | |
| 117 | + conditions = [] | |
| 118 | + # Guards | |
| 119 | + if params.get('sell-rsi-enabled'): | |
| 120 | + conditions.append( | |
| 121 | + ( | |
| 122 | + qtpylib.crossed_below(dataframe['rsi'], params['sell-rsi-limit']) | | |
| 123 | + qtpylib.crossed_below(dataframe['rsi'].shift(1), params['sell-rsi-limit']) | | |
| 124 | + qtpylib.crossed_below(dataframe['rsi'].shift(2), params['sell-rsi-limit']) | |
| 125 | + ) & | |
| 126 | + ( | |
| 127 | + dataframe['rsi'].lt(params['sell-rsi-limit']) | |
| 128 | + ) | |
| 129 | + ) | |
| 130 | + if params.get('sell-cci-enabled'): | |
| 131 | + conditions.append( | |
| 132 | + ( | |
| 133 | + qtpylib.crossed_below(dataframe['cci'], params['sell-cci-limit']) | | |
| 134 | + qtpylib.crossed_below(dataframe['cci'].shift(1), params['sell-cci-limit']) | | |
| 135 | + qtpylib.crossed_below(dataframe['cci'].shift(2), params['sell-cci-limit']) | |
| 136 | + ) & | |
| 137 | + ( | |
| 138 | + dataframe['cci'].lt(params['sell-cci-limit']) | |
| 139 | + ) | |
| 140 | + ) | |
| 141 | + | |
| 142 | + # Triggers | |
| 143 | + if params.get('sell-kama-trigger') == 'cross': | |
| 144 | + conditions.append(qtpylib.crossed_below(dataframe['kama-short'], dataframe['kama-long'])) | |
| 145 | + if params.get('sell-kama-trigger') == 'slope': | |
| 146 | + conditions.append(dataframe['kama-long'] < dataframe['kama-long'].shift(1)) | |
| 147 | + | |
| 148 | + # Check that the candle had volume | |
| 149 | + conditions.append(dataframe['volume'] > 0) | |
| 150 | + | |
| 151 | + if conditions: | |
| 152 | + dataframe.loc[ | |
| 153 | + reduce(lambda x, y: x & y, conditions), | |
| 154 | + 'sell'] = 1 | |
| 155 | + | |
| 156 | + return dataframe | |
| 157 | + | |
| 158 | + return populate_sell_trend | |
| 159 | + | |
| 160 | + @staticmethod | |
| 161 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 162 | + | |
| 163 | + roi_table = {} | |
| 164 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 165 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 166 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 167 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 168 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 169 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 170 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 171 | + | |
| 172 | + return roi_table | |
| 173 | + | |
| 174 | + @staticmethod | |
| 175 | + def roi_space() -> List[Dimension]: | |
| 176 | + | |
| 177 | + return [ | |
| 178 | + Integer(1, 300, name='roi_t6'), | |
| 179 | + Integer(1, 300, name='roi_t5'), | |
| 180 | + Integer(1, 300, name='roi_t4'), | |
| 181 | + Integer(1, 300, name='roi_t3'), | |
| 182 | + Integer(1, 300, name='roi_t2'), | |
| 183 | + Integer(1, 300, name='roi_t1'), | |
| 184 | + | |
| 185 | + Real(0.001, 0.005, name='roi_p6'), | |
| 186 | + Real(0.001, 0.005, name='roi_p5'), | |
| 187 | + Real(0.001, 0.005, name='roi_p4'), | |
| 188 | + Real(0.001, 0.005, name='roi_p3'), | |
| 189 | + Real(0.0001, 0.005, name='roi_p2'), | |
| 190 | + Real(0.0001, 0.005, name='roi_p1'), | |
| 191 | + ] | |
| No newline at the end of the file |
added hyperopts/old/KamaRsi2Hyp.py +191 −0
| @@ -0,0 +1,191 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class KamaRsi2Hyp(IHyperOpt): | |
| 20 | + """ | |
| 21 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 22 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 23 | + """ | |
| 24 | + # Buy hyperspace params: | |
| 25 | + buy_params = { | |
| 26 | + 'rsi-buy-trigger': 10, | |
| 27 | + 'cci-buy-trigger': -100, | |
| 28 | + 'buy-method': 'both', # trend, rsi2, both | |
| 29 | + 'buy-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 30 | + } | |
| 31 | + | |
| 32 | + # Sell hyperspace params: | |
| 33 | + sell_params = { | |
| 34 | + 'rsi-sell-trigger': 90, | |
| 35 | + 'cci-sell-trigger': 100, | |
| 36 | + 'sell-method': 'both', # trend, rsi2, both | |
| 37 | + 'sell-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 38 | + } | |
| 39 | + | |
| 40 | + @staticmethod | |
| 41 | + def indicator_space() -> List[Dimension]: | |
| 42 | + return [ | |
| 43 | + Integer(0, 20, name='rsi-buy-trigger'), | |
| 44 | + Integer(-200, -100, name='cci-buy-trigger'), | |
| 45 | + Categorical(['rsi2','trend','both'], name='buy-method'), | |
| 46 | + Categorical(['open','close','hl2','hlc3','ohlc4'], name='buy-price') | |
| 47 | + ] | |
| 48 | + | |
| 49 | + @staticmethod | |
| 50 | + def sell_indicator_space() -> List[Dimension]: | |
| 51 | + return [ | |
| 52 | + Integer(80, 100, name='rsi-sell-trigger'), | |
| 53 | + Integer(100, 200, name='cci-sell-trigger'), | |
| 54 | + Categorical(['rsi2','trend','both'], name='sell-method'), | |
| 55 | + Categorical(['open','close','hl2','hlc3','ohlc4'], name='sell-price') | |
| 56 | + ] | |
| 57 | + | |
| 58 | + @staticmethod | |
| 59 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 60 | + | |
| 61 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 62 | + | |
| 63 | + conditions = [] | |
| 64 | + | |
| 65 | + if params['buy-method'] == 'rsi2' or params['buy-method'] == 'both': | |
| 66 | + conditions.append(dataframe[params['buy-price']] > dataframe['kama-long']) | |
| 67 | + conditions.append(dataframe['close'] < dataframe['kama-short']) | |
| 68 | + conditions.append(dataframe['rsi'] < params['rsi-buy-trigger']) | |
| 69 | + conditions.append(dataframe['cci'] < params['cci-buy-trigger']) | |
| 70 | + | |
| 71 | + if params['buy-method'] == 'trend' or params['buy-method'] == 'both': | |
| 72 | + conditions.append(dataframe[params['buy-price']] > dataframe['sar']) | |
| 73 | + # conditions.append(dataframe[params['buy-price']] > dataframe['supertrend']) | |
| 74 | + | |
| 75 | + conditions.append(dataframe['volume'] > 0) | |
| 76 | + | |
| 77 | + if conditions: | |
| 78 | + dataframe.loc[ | |
| 79 | + reduce(lambda x, y: x & y, conditions), | |
| 80 | + 'buy'] = 1 | |
| 81 | + | |
| 82 | + return dataframe | |
| 83 | + | |
| 84 | + return populate_buy_trend | |
| 85 | + | |
| 86 | + @staticmethod | |
| 87 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 88 | + | |
| 89 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 90 | + | |
| 91 | + conditions = [] | |
| 92 | + | |
| 93 | + if params['sell-method'] == 'rsi2' or params['sell-method'] == 'both': | |
| 94 | + # conditions.append(dataframe[params['sell-price']] < dataframe['kama-long']) | |
| 95 | + conditions.append(dataframe['close'] > dataframe['kama-short']) | |
| 96 | + conditions.append(dataframe['rsi'] > params['rsi-sell-trigger']) | |
| 97 | + conditions.append(dataframe['cci'] > params['cci-sell-trigger']) | |
| 98 | + if params['sell-method'] == 'trend' or params['sell-method'] == 'both': | |
| 99 | + conditions.append(dataframe[params['sell-price']] < dataframe['sar']) | |
| 100 | + # conditions.append(dataframe[params['sell-price']] < dataframe['supertrend']) | |
| 101 | + | |
| 102 | + conditions.append(dataframe['volume'] > 0) | |
| 103 | + | |
| 104 | + if conditions: | |
| 105 | + dataframe.loc[ | |
| 106 | + reduce(lambda x, y: x & y, conditions), | |
| 107 | + 'sell'] = 1 | |
| 108 | + | |
| 109 | + return dataframe | |
| 110 | + | |
| 111 | + return populate_sell_trend | |
| 112 | + | |
| 113 | + | |
| 114 | + @staticmethod | |
| 115 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 116 | + | |
| 117 | + roi_table = {} | |
| 118 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 119 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 120 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 121 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 122 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 123 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 124 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 125 | + | |
| 126 | + return roi_table | |
| 127 | + | |
| 128 | + @staticmethod | |
| 129 | + def roi_space() -> List[Dimension]: | |
| 130 | + | |
| 131 | + return [ | |
| 132 | + Integer(1, 5, name='roi_t6'), | |
| 133 | + Integer(1, 10, name='roi_t5'), | |
| 134 | + Integer(1, 15, name='roi_t4'), | |
| 135 | + Integer(15, 20, name='roi_t3'), | |
| 136 | + Integer(20, 25, name='roi_t2'), | |
| 137 | + Integer(25, 60, name='roi_t1'), | |
| 138 | + | |
| 139 | + Real(0.005, 0.10, name='roi_p6'), | |
| 140 | + Real(0.005, 0.07, name='roi_p5'), | |
| 141 | + Real(0.005, 0.05, name='roi_p4'), | |
| 142 | + Real(0.005, 0.025, name='roi_p3'), | |
| 143 | + Real(0.005, 0.01, name='roi_p2'), | |
| 144 | + Real(0.003, 0.007, name='roi_p1'), | |
| 145 | + ] | |
| 146 | + | |
| 147 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 148 | + params = self.buy_params | |
| 149 | + | |
| 150 | + conditions = [] | |
| 151 | + | |
| 152 | + if params['buy-method'] == 'rsi2' or params['buy-method'] == 'both': | |
| 153 | + conditions.append(dataframe[params['buy-price']] > dataframe['kama-long']) | |
| 154 | + conditions.append(dataframe['close'] < dataframe['kama-short']) | |
| 155 | + conditions.append(dataframe['rsi'] < params['rsi-buy-trigger']) | |
| 156 | + conditions.append(dataframe['cci'] < params['cci-buy-trigger']) | |
| 157 | + | |
| 158 | + if params['buy-method'] == 'trend' or params['buy-method'] == 'both': | |
| 159 | + conditions.append(dataframe[params['buy-price']] > dataframe['sar']) | |
| 160 | + # conditions.append(dataframe[params['buy-price']] > dataframe['supertrend']) | |
| 161 | + | |
| 162 | + conditions.append(dataframe['volume'] > 0) | |
| 163 | + | |
| 164 | + if conditions: | |
| 165 | + dataframe.loc[ | |
| 166 | + reduce(lambda x, y: x & y, conditions), | |
| 167 | + 'buy'] = 1 | |
| 168 | + | |
| 169 | + return dataframe | |
| 170 | + | |
| 171 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 172 | + params = self.sell_params | |
| 173 | + | |
| 174 | + conditions = [] | |
| 175 | + | |
| 176 | + if params['sell-method'] == 'rsi2' or params['sell-method'] == 'both': | |
| 177 | + # conditions.append(dataframe[params['sell-price']] < dataframe['kama-long']) | |
| 178 | + conditions.append(dataframe['close'] > dataframe['kama-short']) | |
| 179 | + conditions.append(dataframe['rsi'] > params['rsi-sell-trigger']) | |
| 180 | + conditions.append(dataframe['cci'] > params['cci-sell-trigger']) | |
| 181 | + if params['sell-method'] == 'trend' or params['sell-method'] == 'both': | |
| 182 | + conditions.append(dataframe[params['sell-price']] < dataframe['sar']) | |
| 183 | + # conditions.append(dataframe[params['sell-price']] < dataframe['supertrend']) | |
| 184 | + | |
| 185 | + conditions.append(dataframe['volume'] > 0) | |
| 186 | + | |
| 187 | + if conditions: | |
| 188 | + dataframe.loc[ | |
| 189 | + reduce(lambda x, y: x & y, conditions), | |
| 190 | + 'sell'] = 1 | |
| 191 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/KamaflageHyp.py +104 −0
| @@ -0,0 +1,104 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class KamaflageHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Real(-1.00, 1.00, name='macd'), | |
| 25 | + Integer(-1.00, 1.00, name='macdhist'), | |
| 26 | + Integer(40, 90, name='rmi') | |
| 27 | + ] | |
| 28 | + | |
| 29 | + @staticmethod | |
| 30 | + def sell_indicator_space() -> List[Dimension]: | |
| 31 | + return [] | |
| 32 | + | |
| 33 | + @staticmethod | |
| 34 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 35 | + | |
| 36 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 37 | + | |
| 38 | + conditions = [] | |
| 39 | + | |
| 40 | + conditions.append(dataframe['kama-3'] > dataframe['kama-21']) | |
| 41 | + conditions.append(dataframe['macd'] > dataframe['macdsignal']) | |
| 42 | + conditions.append(dataframe['macd'] > params['macd']) | |
| 43 | + conditions.append(dataframe['macdhist'] > params['macdhist']) | |
| 44 | + conditions.append(dataframe['rmi'] > dataframe['rmi'].shift()) | |
| 45 | + conditions.append(dataframe['rmi'] > params['rmi']) | |
| 46 | + conditions.append(dataframe['volume'] < (dataframe['volume_ma'] * 20)) | |
| 47 | + | |
| 48 | + conditions.append(dataframe['volume'] > 0) | |
| 49 | + | |
| 50 | + if conditions: | |
| 51 | + dataframe.loc[ | |
| 52 | + reduce(lambda x, y: x & y, conditions), | |
| 53 | + 'buy'] = 1 | |
| 54 | + | |
| 55 | + return dataframe | |
| 56 | + | |
| 57 | + return populate_buy_trend | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 61 | + | |
| 62 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + """ | |
| 64 | + no sell signal | |
| 65 | + """ | |
| 66 | + dataframe['sell'] = 0 | |
| 67 | + return dataframe | |
| 68 | + | |
| 69 | + return populate_sell_trend | |
| 70 | + | |
| 71 | + | |
| 72 | + @staticmethod | |
| 73 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 74 | + | |
| 75 | + roi_table = {} | |
| 76 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 77 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 78 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 79 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 80 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 81 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 82 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0.0025 | |
| 83 | + | |
| 84 | + return roi_table | |
| 85 | + | |
| 86 | + @staticmethod | |
| 87 | + def roi_space() -> List[Dimension]: | |
| 88 | + # min / max min / max | |
| 89 | + return [ # 0 : 0.100 / 0.200 | |
| 90 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.100 | |
| 91 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.050 | |
| 92 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.030 | |
| 93 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.015 | |
| 94 | + Integer(45, 90, name='roi_t2'), # 81 -> 180 : 0.003 / 0.005 | |
| 95 | + Integer(90, 180, name='roi_t1'), # 171 -> 360 : 0.0025 (should be 0 but I changed it above.) | |
| 96 | + | |
| 97 | + Real(0.05, 0.10, name='roi_p6'), | |
| 98 | + Real(0.02, 0.05, name='roi_p5'), | |
| 99 | + Real(0.015, 0.020, name='roi_p4'), | |
| 100 | + Real(0.005, 0.015, name='roi_p3'), | |
| 101 | + Real(0.007, 0.01, name='roi_p2'), | |
| 102 | + Real(0.003, 0.005, name='roi_p1'), | |
| 103 | + ] | |
| 104 | + |
added hyperopts/old/LateralusHyp.py +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class LateralusHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Real(0.0005, 0.03, name='bbdelta-close'), | |
| 25 | + Real(0.0005, 0.02, name='closedelta-close'), | |
| 26 | + Real(0.0005, 0.02, name='close-bblower'), | |
| 27 | + Real(0.5, 1.0, name='bbdelta-tail'), | |
| 28 | + Integer(1, 30, name='volume') | |
| 29 | + ] | |
| 30 | + | |
| 31 | + @staticmethod | |
| 32 | + def sell_indicator_space() -> List[Dimension]: | |
| 33 | + return [] | |
| 34 | + | |
| 35 | + @staticmethod | |
| 36 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 37 | + | |
| 38 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 39 | + | |
| 40 | + inf_timeframe = '1h' | |
| 41 | + conditions = [] | |
| 42 | + | |
| 43 | + conditions.append( | |
| 44 | + ( | |
| 45 | + (dataframe[f"ema-fast_{inf_timeframe}"] > dataframe[f"ema-slow_{inf_timeframe}"]) & | |
| 46 | + (dataframe[f"macd_{inf_timeframe}"] > dataframe[f"macdsignal_{inf_timeframe}"]) | |
| 47 | + ) & | |
| 48 | + (( | |
| 49 | + (dataframe['bb1-delta'] > (dataframe['close'] * params['bbdelta-close'])) & | |
| 50 | + (dataframe['closedelta'] > (dataframe['close'] * params['closedelta-close'])) & | |
| 51 | + (dataframe['tail'] < (dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 52 | + (dataframe['close'] < dataframe['lower-bb1'].shift()) & | |
| 53 | + (dataframe['close'] <= dataframe['close'].shift()) | |
| 54 | + ) | | |
| 55 | + ( | |
| 56 | + (dataframe['close'] < dataframe['ema-slow']) & | |
| 57 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 58 | + (dataframe['volume'] < (dataframe['volume-mean-slow'].shift(1) * params['volume'])) | |
| 59 | + )) | |
| 60 | + ) | |
| 61 | + | |
| 62 | + conditions.append(dataframe['volume'].gt(0)) | |
| 63 | + | |
| 64 | + if conditions: | |
| 65 | + dataframe.loc[ | |
| 66 | + reduce(lambda x, y: x & y, conditions), | |
| 67 | + 'buy'] = 1 | |
| 68 | + return dataframe | |
| 69 | + | |
| 70 | + return populate_buy_trend | |
| 71 | + | |
| 72 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 73 | + """ | |
| 74 | + no sell signal | |
| 75 | + """ | |
| 76 | + dataframe['sell'] = 0 | |
| 77 | + return dataframe | |
| 78 | + | |
| 79 | + | |
| 80 | + |
added hyperopts/old/PmaxHyper.py +144 −0
| @@ -0,0 +1,144 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | +# isort: skip_file | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | +from technical.indicators import PMAX, zema | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | +import multiprocessing | |
| 12 | +import time | |
| 13 | +import sys | |
| 14 | +import threading | |
| 15 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 16 | + | |
| 17 | +# -------------------------------- | |
| 18 | +# Add your lib to import here | |
| 19 | +import talib.abstract as ta # noqa | |
| 20 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 21 | + | |
| 22 | + | |
| 23 | +class PmaxHyper(IHyperOpt): | |
| 24 | + | |
| 25 | + @staticmethod | |
| 26 | + def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 27 | + """ | |
| 28 | + This method can also be loaded from the strategy, if it doesn't exist in the hyperopt class. | |
| 29 | + """ | |
| 30 | + n=0 | |
| 31 | + length = 10 | |
| 32 | + dframe = dataframe.copy() | |
| 33 | + default = dataframe.copy() | |
| 34 | + jobs = [] | |
| 35 | + tuples = [] | |
| 36 | + | |
| 37 | + def thr(default, length, MAtype, multiplier, src_val, ns): | |
| 38 | + DAT = PMAX(default, period=length, multiplier=multiplier, length=length, MAtype=MAtype, | |
| 39 | + src=src_val) | |
| 40 | + xdata = ns.df | |
| 41 | + xdata[list(DAT.keys())[-1]] = DAT[list(DAT.keys())[-1]] | |
| 42 | + ns.df = xdata | |
| 43 | + | |
| 44 | + mgr = multiprocessing.Manager() | |
| 45 | + ns = mgr.Namespace() | |
| 46 | + ns.df = dataframe | |
| 47 | + print(dataframe.head()) | |
| 48 | + def wrapper(mpobject): | |
| 49 | + mpobject.start() | |
| 50 | + mpobject.join() | |
| 51 | + for length in range(2, 200): | |
| 52 | + for MAtype in range(1, 8): | |
| 53 | + for multiplier in range(1, 30): | |
| 54 | + for src_val in range(1, 3): | |
| 55 | + p = multiprocessing.Process(target=thr, args=(default, length, MAtype, multiplier, src_val, ns)) | |
| 56 | + # p.start() | |
| 57 | + # print(p.exitcode) | |
| 58 | + # thr(default, length, MAtype, multiplier, src_val, ns) | |
| 59 | + # jobs.append(p) | |
| 60 | + # print(ns.df) | |
| 61 | + # print(dataframe) | |
| 62 | + jobs.append(p) | |
| 63 | + # tuples.append(tuple([length, MAtype, multiplier, src_val, default])) | |
| 64 | + # pool = multiprocessing.Pool(processes=16) | |
| 65 | + # pool.map_async(wrapper, jobs) | |
| 66 | + # pool.close() | |
| 67 | + # pool.join() | |
| 68 | + for process in jobs: | |
| 69 | + th = threading.Thread(target=wrapper, args=(process,)) | |
| 70 | + th.start() | |
| 71 | + n=n+1 | |
| 72 | + if n==512: | |
| 73 | + th.join() | |
| 74 | + n=0 | |
| 75 | + print(sys.getsizeof(ns.df)) | |
| 76 | + dataframe = ns.df | |
| 77 | + for i in range(2, 200): | |
| 78 | + EMA = '' | |
| 79 | + EMA = 'EMA' + str(i) | |
| 80 | + dataframe[EMA] = zema(dataframe, period=length) | |
| 81 | + return dataframe | |
| 82 | + | |
| 83 | + @staticmethod | |
| 84 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 85 | + """ | |
| 86 | + Define the buy strategy parameters to be used by hyperopt | |
| 87 | + """ | |
| 88 | + | |
| 89 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 90 | + EMA = "EMA" + str(params['length']) | |
| 91 | + pmax = "pm_" + str(params['length']) + "_" + str(params['multiplier']) + "_" + str( | |
| 92 | + params['length']) + "_" + str(params['MAtype']) | |
| 93 | + dataframe.loc[ | |
| 94 | + ( | |
| 95 | + (qtpylib.crossed_above(dataframe[EMA], dataframe[pmax])) | |
| 96 | + ), | |
| 97 | + 'buy'] = 1 | |
| 98 | + | |
| 99 | + return dataframe | |
| 100 | + | |
| 101 | + return populate_buy_trend | |
| 102 | + | |
| 103 | + @staticmethod | |
| 104 | + def indicator_space() -> List[Dimension]: | |
| 105 | + """ | |
| 106 | + Define your Hyperopt space for searching strategy parameters | |
| 107 | + """ | |
| 108 | + return [ | |
| 109 | + Integer(1, 30, name='multiplier'), | |
| 110 | + Integer(1, 200, name='length'), | |
| 111 | + Integer(1, 3, name='src_val'), | |
| 112 | + Integer(1, 8, name='MAtype') | |
| 113 | + ] | |
| 114 | + | |
| 115 | + @staticmethod | |
| 116 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 117 | + """ | |
| 118 | + Define the sell strategy parameters to be used by hyperopt | |
| 119 | + """ | |
| 120 | + | |
| 121 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 122 | + EMA = "EMA" + str(params['length']) | |
| 123 | + pmax = "pm_" + str(params['length']) + "_" + str(params['multiplier']) + "_" + str( | |
| 124 | + params['length']) + "_" + str(params['MAtype']) | |
| 125 | + dataframe.loc[ | |
| 126 | + ( | |
| 127 | + (qtpylib.crossed_below(dataframe[EMA], dataframe[pmax])) | |
| 128 | + ), | |
| 129 | + 'sell'] = 1 | |
| 130 | + return dataframe | |
| 131 | + | |
| 132 | + return populate_sell_trend | |
| 133 | + | |
| 134 | + @staticmethod | |
| 135 | + def sell_indicator_space() -> List[Dimension]: | |
| 136 | + """ | |
| 137 | + Define your Hyperopt space for searching sell strategy parameters | |
| 138 | + """ | |
| 139 | + return [ | |
| 140 | + Integer(1, 30, name='multiplier'), | |
| 141 | + Integer(1, 200, name='length'), | |
| 142 | + Integer(1, 3, name='src_val'), | |
| 143 | + Integer(1, 8, name='MAtype') | |
| 144 | + ] |
added hyperopts/old/RenkoHyp.py +92 −0
| @@ -0,0 +1,92 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class RenkoHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [] | |
| 24 | + | |
| 25 | + @staticmethod | |
| 26 | + def sell_indicator_space() -> List[Dimension]: | |
| 27 | + return [] | |
| 28 | + | |
| 29 | + @staticmethod | |
| 30 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 31 | + | |
| 32 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 33 | + | |
| 34 | + buy_mode = True | |
| 35 | + for index, row in dataframe.iterrows(): | |
| 36 | + if row['previous-trend'] == False and row['trend'] == True and buy_mode == True: | |
| 37 | + last_row = dataframe.loc[dataframe['date'] == row['date']][-1:] | |
| 38 | + dataframe.loc[dataframe.index== last_row.index.values[0], 'buy'] = 1 | |
| 39 | + buy_mode = False | |
| 40 | + | |
| 41 | + if row['previous-trend'] == True and row['trend'] == False and buy_mode == False: | |
| 42 | + last_row = dataframe.loc[dataframe['date'] == row['date']][-1:] | |
| 43 | + dataframe.loc[dataframe.index== last_row.index.values[0], 'sell'] = 1 | |
| 44 | + buy_mode = True | |
| 45 | + | |
| 46 | + return dataframe | |
| 47 | + | |
| 48 | + return populate_buy_trend | |
| 49 | + | |
| 50 | + @staticmethod | |
| 51 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 52 | + | |
| 53 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 54 | + | |
| 55 | + dataframe['sell'] = 0 | |
| 56 | + return dataframe | |
| 57 | + | |
| 58 | + return populate_sell_trend | |
| 59 | + | |
| 60 | + @staticmethod | |
| 61 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 62 | + | |
| 63 | + roi_table = {} | |
| 64 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 65 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 66 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 67 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 68 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 69 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 70 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 71 | + | |
| 72 | + return roi_table | |
| 73 | + | |
| 74 | + @staticmethod | |
| 75 | + def roi_space() -> List[Dimension]: | |
| 76 | + | |
| 77 | + return [ | |
| 78 | + Integer(1, 15, name='roi_t6'), | |
| 79 | + Integer(1, 45, name='roi_t5'), | |
| 80 | + Integer(1, 90, name='roi_t4'), | |
| 81 | + Integer(45, 120, name='roi_t3'), | |
| 82 | + Integer(45, 180, name='roi_t2'), | |
| 83 | + Integer(90, 200, name='roi_t1'), | |
| 84 | + | |
| 85 | + Real(0.005, 0.10, name='roi_p6'), | |
| 86 | + Real(0.005, 0.07, name='roi_p5'), | |
| 87 | + Real(0.005, 0.05, name='roi_p4'), | |
| 88 | + Real(0.005, 0.025, name='roi_p3'), | |
| 89 | + Real(0.005, 0.01, name='roi_p2'), | |
| 90 | + Real(0.003, 0.007, name='roi_p1'), | |
| 91 | + ] | |
| 92 | + |
added hyperopts/old/Schism2HypMM.py +108 −0
| @@ -0,0 +1,108 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class Schism2HypMM(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Integer(15, 70, name='rmi-slow'), | |
| 25 | + Integer(5, 50, name='rmi-fast'), | |
| 26 | + Integer(5, 70, name='mp'), | |
| 27 | + Integer(10, 100, name='inf-rsi'), | |
| 28 | + Real(0.70, 0.99, name='inf-pct-adr') | |
| 29 | + ] | |
| 30 | + | |
| 31 | + @staticmethod | |
| 32 | + def sell_indicator_space() -> List[Dimension]: | |
| 33 | + return [] | |
| 34 | + | |
| 35 | + @staticmethod | |
| 36 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 37 | + | |
| 38 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 39 | + | |
| 40 | + inf_timeframe = '1h' | |
| 41 | + conditions = [] | |
| 42 | + | |
| 43 | + conditions.append( | |
| 44 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['inf-rsi']) & | |
| 45 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{inf_timeframe}"])) & | |
| 46 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 47 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 48 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 49 | + (dataframe['mp'] <= params['mp']) | |
| 50 | + ) | |
| 51 | + | |
| 52 | + conditions.append(dataframe['volume'].gt(0)) | |
| 53 | + conditions.append(dataframe['buy_signal']) | |
| 54 | + | |
| 55 | + if conditions: | |
| 56 | + dataframe.loc[ | |
| 57 | + reduce(lambda x, y: x & y, conditions), | |
| 58 | + 'buy'] = 1 | |
| 59 | + return dataframe | |
| 60 | + | |
| 61 | + return populate_buy_trend | |
| 62 | + | |
| 63 | + @staticmethod | |
| 64 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 65 | + | |
| 66 | + roi_table = {} | |
| 67 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 68 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 69 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 70 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 71 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 72 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 73 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0.0025 | |
| 74 | + | |
| 75 | + return roi_table | |
| 76 | + | |
| 77 | + @staticmethod | |
| 78 | + def roi_space() -> List[Dimension]: | |
| 79 | + # min / max min / max | |
| 80 | + return [ # 0 : 0.100 / 0.205 | |
| 81 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 82 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 83 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 84 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 85 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 86 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 87 | + | |
| 88 | + Real(0.05, 0.10, name='roi_p6'), | |
| 89 | + Real(0.02, 0.05, name='roi_p5'), | |
| 90 | + Real(0.015, 0.020, name='roi_p4'), | |
| 91 | + Real(0.005, 0.015, name='roi_p3'), | |
| 92 | + Real(0.005, 0.01, name='roi_p2'), | |
| 93 | + Real(0.005, 0.01, name='roi_p1'), | |
| 94 | + ] | |
| 95 | + | |
| 96 | + @staticmethod | |
| 97 | + def stoploss_space() -> List[Dimension]: | |
| 98 | + | |
| 99 | + return [ | |
| 100 | + Real(-0.99, -0.01, name='stoploss'), | |
| 101 | + ] | |
| 102 | + | |
| 103 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 104 | + """ | |
| 105 | + no sell signal | |
| 106 | + """ | |
| 107 | + dataframe['sell'] = 0 | |
| 108 | + return dataframe |
added hyperopts/old/SchismHyp-Badstreak.py +113 −0
| @@ -0,0 +1,113 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class SchismHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Integer(10, 50, name='mp') | |
| 25 | + ] | |
| 26 | + | |
| 27 | + @staticmethod | |
| 28 | + def sell_indicator_space() -> List[Dimension]: | |
| 29 | + return [] | |
| 30 | + | |
| 31 | + @staticmethod | |
| 32 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 33 | + | |
| 34 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 35 | + | |
| 36 | + conditions = [] | |
| 37 | + | |
| 38 | + conditions.append( | |
| 39 | + (dataframe['mp'] < params['mp']) & | |
| 40 | + (dataframe['streak-roc'] > dataframe['pcc-lowerband']) & | |
| 41 | + (dataframe['mac'] == 1) | |
| 42 | + ) | |
| 43 | + | |
| 44 | + conditions.append(dataframe['volume'].gt(0)) | |
| 45 | + | |
| 46 | + if conditions: | |
| 47 | + dataframe.loc[ | |
| 48 | + reduce(lambda x, y: x & y, conditions), | |
| 49 | + 'buy'] = 1 | |
| 50 | + return dataframe | |
| 51 | + | |
| 52 | + return populate_buy_trend | |
| 53 | + | |
| 54 | + @staticmethod | |
| 55 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 56 | + """ | |
| 57 | + Define the sell strategy parameters to be used by Hyperopt. | |
| 58 | + """ | |
| 59 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 60 | + """ | |
| 61 | + no sell signal | |
| 62 | + """ | |
| 63 | + dataframe['sell'] = 0 | |
| 64 | + return dataframe | |
| 65 | + | |
| 66 | + return populate_sell_trend | |
| 67 | + | |
| 68 | + @staticmethod | |
| 69 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 70 | + | |
| 71 | + roi_table = {} | |
| 72 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 73 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 74 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 75 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 76 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 77 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 78 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 79 | + | |
| 80 | + return roi_table | |
| 81 | + | |
| 82 | + @staticmethod | |
| 83 | + def roi_space() -> List[Dimension]: | |
| 84 | + # min / max min / max | |
| 85 | + return [ # 0 : 0.100 / 0.205 | |
| 86 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 87 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 88 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 89 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 90 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 91 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 92 | + | |
| 93 | + Real(0.05, 0.10, name='roi_p6'), | |
| 94 | + Real(0.02, 0.05, name='roi_p5'), | |
| 95 | + Real(0.015, 0.020, name='roi_p4'), | |
| 96 | + Real(0.005, 0.015, name='roi_p3'), | |
| 97 | + Real(0.005, 0.01, name='roi_p2'), | |
| 98 | + Real(0.005, 0.01, name='roi_p1'), | |
| 99 | + ] | |
| 100 | + | |
| 101 | + @staticmethod | |
| 102 | + def stoploss_space() -> List[Dimension]: | |
| 103 | + | |
| 104 | + return [ | |
| 105 | + Real(-0.99, -0.01, name='stoploss'), | |
| 106 | + ] | |
| 107 | + | |
| 108 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 109 | + """ | |
| 110 | + no sell signal | |
| 111 | + """ | |
| 112 | + dataframe['sell'] = 0 | |
| 113 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp-Badstreak2.py +88 −0
| @@ -0,0 +1,88 @@ | ||
| 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 SchismHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(10, 50, name='mp'), | |
| 20 | + Integer(10, 70, name='inf-rsi-1'), | |
| 21 | + Integer(10, 70, name='inf-rsi-2'), | |
| 22 | + Integer(10, 40, name='rmi-above'), | |
| 23 | + Integer(50, 80, name='rmi-below'), | |
| 24 | + Integer(10, 70, name='xinf-stake-rmi'), | |
| 25 | + Integer(50, 90, name='xtf-stake-rsi'), | |
| 26 | + Integer(10, 70, name='xtf-fiat-rsi') | |
| 27 | + ] | |
| 28 | + | |
| 29 | + @staticmethod | |
| 30 | + def sell_indicator_space() -> List[Dimension]: | |
| 31 | + return [] | |
| 32 | + | |
| 33 | + @staticmethod | |
| 34 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 35 | + | |
| 36 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 37 | + | |
| 38 | + inf_timeframe = '4h' | |
| 39 | + stake_currency = 'USD' | |
| 40 | + fiat = 'USD' | |
| 41 | + conditions = [] | |
| 42 | + | |
| 43 | + conditions.append( | |
| 44 | + ( | |
| 45 | + (dataframe[f"rsi_{inf_timeframe}"] < params['inf-rsi-1']) & | |
| 46 | + (dataframe['mp'] < params['mp']) & | |
| 47 | + (dataframe['streak-roc'] > dataframe['pcc-lowerband']) & | |
| 48 | + (dataframe['mac'] == 1) | |
| 49 | + ) | | |
| 50 | + ( | |
| 51 | + (dataframe[f"rsi_{inf_timeframe}"] < params['inf-rsi-2']) & | |
| 52 | + (dataframe['rmi-up-trend'] == 1) & | |
| 53 | + (dataframe['rmi'] < params['rmi-below']) & | |
| 54 | + (dataframe['rmi'] > params['rmi-above']) | |
| 55 | + ) | |
| 56 | + ) | |
| 57 | + | |
| 58 | + if stake_currency in ('BTC', 'ETH'): | |
| 59 | + conditions.append( | |
| 60 | + (dataframe[f"{stake_currency}_rsi"] > params['xtf-stake-rsi']) | | |
| 61 | + (dataframe[f"{fiat}_rsi"] < params['xtf-fiat-rsi']) | |
| 62 | + ) | |
| 63 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 64 | + | |
| 65 | + conditions.append(dataframe['volume'].gt(0)) | |
| 66 | + | |
| 67 | + if conditions: | |
| 68 | + dataframe.loc[ | |
| 69 | + reduce(lambda x, y: x & y, conditions), | |
| 70 | + 'buy'] = 1 | |
| 71 | + return dataframe | |
| 72 | + | |
| 73 | + return populate_buy_trend | |
| 74 | + | |
| 75 | + @staticmethod | |
| 76 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 77 | + | |
| 78 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 79 | + | |
| 80 | + dataframe['sell'] = 0 | |
| 81 | + return dataframe | |
| 82 | + | |
| 83 | + return populate_sell_trend | |
| 84 | + | |
| 85 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 86 | + | |
| 87 | + dataframe['sell'] = 0 | |
| 88 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp-v1.3.py +99 −0
| @@ -0,0 +1,99 @@ | ||
| 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 Schism3Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Categorical(['min', 'max', 'mean', 'median'], name='bounce-price'), | |
| 20 | + Integer(1, 10, name='bounce-lookback'), # 1, 10 | |
| 21 | + Integer(20, 50, name='down-inf-rsi'), # 20, 50 | |
| 22 | + Integer(20, 50, name='down-rmi-slow'), # 20, 50 | |
| 23 | + Integer(10, 50, name='down-rmi-fast'), # 10, 50 | |
| 24 | + Integer(10, 70, name='down-mp'), # 10, 70 | |
| 25 | + Integer(30, 70, name='up-inf-rsi'), # 30, 70 | |
| 26 | + Integer(10, 70, name='xinf-stake-rmi'), # 10, 70 | |
| 27 | + Integer(50, 90, name='xtf-stake-rsi'), # 50, 90 | |
| 28 | + Integer(10, 70, name='xtf-fiat-rsi') # 10, 70 | |
| 29 | + ] | |
| 30 | + | |
| 31 | + @staticmethod | |
| 32 | + def sell_indicator_space() -> List[Dimension]: | |
| 33 | + return [] | |
| 34 | + | |
| 35 | + @staticmethod | |
| 36 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 37 | + | |
| 38 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 39 | + | |
| 40 | + inf_timeframe = '1h' | |
| 41 | + stake_currency = 'USD' | |
| 42 | + fiat = 'USD' | |
| 43 | + conditions = [] | |
| 44 | + | |
| 45 | + dataframe['bounce-pending'] = np.where( | |
| 46 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['down-inf-rsi']) & | |
| 47 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 48 | + (dataframe['rmi-slow'] >= params['down-rmi-slow']) & | |
| 49 | + (dataframe['rmi-fast'] <= params['down-rmi-fast']) & | |
| 50 | + (dataframe['mp'] <= params['down-mp']), | |
| 51 | + 1,0 | |
| 52 | + ) | |
| 53 | + | |
| 54 | + dataframe['bounce-price'] = np.where( | |
| 55 | + dataframe['bounce-pending'] == 1, | |
| 56 | + dataframe['close'], | |
| 57 | + getattr(dataframe['close'].rolling(params['bounce-lookback'], min_periods=1), params['bounce-price'])() | |
| 58 | + ) | |
| 59 | + | |
| 60 | + dataframe['bounce-range'] = np.where(dataframe['bounce-pending'].rolling(params['bounce-lookback'], min_periods=1).sum() >= 1,1,0) | |
| 61 | + | |
| 62 | + conditions.append( | |
| 63 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['up-inf-rsi']) & | |
| 64 | + (dataframe['bounce-range'] == 1) & | |
| 65 | + (dataframe['rmi-up-trend'] == 1) & | |
| 66 | + (dataframe['close'] >= dataframe['bounce-price']) | |
| 67 | + ) | |
| 68 | + | |
| 69 | + if stake_currency in ('BTC', 'ETH'): | |
| 70 | + conditions.append( | |
| 71 | + (dataframe[f"{stake_currency}_rsi"] < params['xtf-stake-rsi']) | | |
| 72 | + (dataframe[f"{fiat}_rsi"] > params['xtf-fiat-rsi']) | |
| 73 | + ) | |
| 74 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 75 | + | |
| 76 | + conditions.append(dataframe['volume'].gt(0)) | |
| 77 | + | |
| 78 | + if conditions: | |
| 79 | + dataframe.loc[ | |
| 80 | + reduce(lambda x, y: x & y, conditions), | |
| 81 | + 'buy'] = 1 | |
| 82 | + return dataframe | |
| 83 | + | |
| 84 | + return populate_buy_trend | |
| 85 | + | |
| 86 | + @staticmethod | |
| 87 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 88 | + | |
| 89 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 90 | + | |
| 91 | + dataframe['sell'] = 0 | |
| 92 | + return dataframe | |
| 93 | + | |
| 94 | + return populate_sell_trend | |
| 95 | + | |
| 96 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 97 | + | |
| 98 | + dataframe['sell'] = 0 | |
| 99 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp-v1.4.py +80 −0
| @@ -0,0 +1,80 @@ | ||
| 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 Schism4Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(15, 70, name='rmi-slow'), | |
| 20 | + Integer(10, 50, name='rmi-fast'), | |
| 21 | + Integer(10, 70, name='mp'), | |
| 22 | + Integer(10, 70, name='inf-rsi'), | |
| 23 | + Integer(10, 70, name='xinf-stake-rmi'), | |
| 24 | + Integer(50, 90, name='xtf-stake-rsi'), | |
| 25 | + Integer(10, 70, name='xtf-fiat-rsi') | |
| 26 | + ] | |
| 27 | + | |
| 28 | + @staticmethod | |
| 29 | + def sell_indicator_space() -> List[Dimension]: | |
| 30 | + return [] | |
| 31 | + | |
| 32 | + @staticmethod | |
| 33 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 34 | + | |
| 35 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 36 | + | |
| 37 | + inf_timeframe = '1h' | |
| 38 | + stake_currency = 'USD' | |
| 39 | + fiat = 'USD' | |
| 40 | + conditions = [] | |
| 41 | + | |
| 42 | + conditions.append( | |
| 43 | + (dataframe[f"rsi_{inf_timeframe}"] <= params['inf-rsi']) & | |
| 44 | + (dataframe['rmi-up-trend'] == 1) & | |
| 45 | + (dataframe['rmi-slow'] <= params['rmi-slow']) & | |
| 46 | + (dataframe['rmi-fast'] >= params['rmi-fast']) & | |
| 47 | + (dataframe['mp'] >= params['mp']) | |
| 48 | + ) | |
| 49 | + | |
| 50 | + if stake_currency in ('BTC', 'ETH'): | |
| 51 | + conditions.append( | |
| 52 | + (dataframe[f"{stake_currency}_rsi"] < params['xtf-stake-rsi']) | | |
| 53 | + (dataframe[f"{fiat}_rsi"] > params['xtf-fiat-rsi']) | |
| 54 | + ) | |
| 55 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 56 | + | |
| 57 | + conditions.append(dataframe['volume'].gt(0)) | |
| 58 | + | |
| 59 | + if conditions: | |
| 60 | + dataframe.loc[ | |
| 61 | + reduce(lambda x, y: x & y, conditions), | |
| 62 | + 'buy'] = 1 | |
| 63 | + return dataframe | |
| 64 | + | |
| 65 | + return populate_buy_trend | |
| 66 | + | |
| 67 | + @staticmethod | |
| 68 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 69 | + | |
| 70 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 71 | + | |
| 72 | + dataframe['sell'] = 0 | |
| 73 | + return dataframe | |
| 74 | + | |
| 75 | + return populate_sell_trend | |
| 76 | + | |
| 77 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 78 | + | |
| 79 | + dataframe['sell'] = 0 | |
| 80 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp-v1.5.py +70 −0
| @@ -0,0 +1,70 @@ | ||
| 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 Schism5Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(10, 50, name='bull-buy-rsi'), | |
| 20 | + Integer(10, 50, name='bear-buy-rsi') | |
| 21 | + ] | |
| 22 | + | |
| 23 | + @staticmethod | |
| 24 | + def sell_indicator_space() -> List[Dimension]: | |
| 25 | + return [ | |
| 26 | + Integer(50, 90, name='bull-sell-rsi'), | |
| 27 | + Integer(50, 90, name='bear-sell-rsi') | |
| 28 | + ] | |
| 29 | + | |
| 30 | + @staticmethod | |
| 31 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 32 | + | |
| 33 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 34 | + conditions = [] | |
| 35 | + | |
| 36 | + conditions.append( | |
| 37 | + ((dataframe['bull'] > 0) & qtpylib.crossed_below(dataframe['rsi'], params['bull-buy-rsi'])) | | |
| 38 | + (~(dataframe['bull'] > 0) & qtpylib.crossed_below(dataframe['rsi'], params['bear-buy-rsi'])) | |
| 39 | + ) | |
| 40 | + | |
| 41 | + conditions.append(dataframe['volume'].gt(0)) | |
| 42 | + | |
| 43 | + if conditions: | |
| 44 | + dataframe.loc[ | |
| 45 | + reduce(lambda x, y: x & y, conditions), | |
| 46 | + 'buy'] = 1 | |
| 47 | + return dataframe | |
| 48 | + | |
| 49 | + return populate_buy_trend | |
| 50 | + | |
| 51 | + @staticmethod | |
| 52 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 53 | + | |
| 54 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 55 | + conditions = [] | |
| 56 | + | |
| 57 | + conditions.append( | |
| 58 | + ((dataframe['bull'] > 0) & (dataframe['rsi'] > params['bull-sell-rsi'])) | | |
| 59 | + (~(dataframe['bull'] > 0) & (dataframe['rsi'] > params['bear-sell-rsi'])) | |
| 60 | + ) | |
| 61 | + | |
| 62 | + conditions.append(dataframe['volume'].gt(0)) | |
| 63 | + | |
| 64 | + if conditions: | |
| 65 | + dataframe.loc[ | |
| 66 | + reduce(lambda x, y: x & y, conditions), | |
| 67 | + 'sell'] = 1 | |
| 68 | + return dataframe | |
| 69 | + | |
| 70 | + return populate_sell_trend | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp-v1.6.py +98 −0
| @@ -0,0 +1,98 @@ | ||
| 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 Schism6Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + # Base Timeframe | |
| 20 | + Integer(15, 70, name='base-rmi-slow'), | |
| 21 | + Integer(10, 50, name='base-rmi-fast'), | |
| 22 | + Integer(10, 70, name='base-mp'), | |
| 23 | + # Informative Timeframe | |
| 24 | + Integer(10, 70, name='inf-rsi'), | |
| 25 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 26 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 27 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 28 | + # Exra BTC/ETH Stakes | |
| 29 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 30 | + Integer(50, 90, name='xtra-base-stake-rsi'), | |
| 31 | + Integer(10, 70, name='xtra-base-fiat-rsi') | |
| 32 | + ] | |
| 33 | + | |
| 34 | + @staticmethod | |
| 35 | + def sell_indicator_space() -> List[Dimension]: | |
| 36 | + return [] | |
| 37 | + | |
| 38 | + @staticmethod | |
| 39 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 40 | + | |
| 41 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 42 | + | |
| 43 | + inf_timeframe = '1h' | |
| 44 | + stake_currency = 'USD' | |
| 45 | + fiat = 'USD' | |
| 46 | + conditions = [] | |
| 47 | + | |
| 48 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 49 | + conditions.append( | |
| 50 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 51 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 52 | + ) | |
| 53 | + | |
| 54 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 55 | + conditions.append( | |
| 56 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 57 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 58 | + ) | |
| 59 | + | |
| 60 | + conditions.append( | |
| 61 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['inf-rsi']) & | |
| 62 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 63 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 64 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 65 | + (dataframe['mp'] <= params['base-mp']) | |
| 66 | + ) | |
| 67 | + | |
| 68 | + if stake_currency in ('BTC', 'ETH'): | |
| 69 | + conditions.append( | |
| 70 | + (dataframe[f"{stake_currency}_rsi"] < params['xtra-base-stake-rsi']) | | |
| 71 | + (dataframe[f"{fiat}_rsi"] > params['xtra-base-fiat-rsi']) | |
| 72 | + ) | |
| 73 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 74 | + | |
| 75 | + conditions.append(dataframe['volume'].gt(0)) | |
| 76 | + | |
| 77 | + if conditions: | |
| 78 | + dataframe.loc[ | |
| 79 | + reduce(lambda x, y: x & y, conditions), | |
| 80 | + 'buy'] = 1 | |
| 81 | + return dataframe | |
| 82 | + | |
| 83 | + return populate_buy_trend | |
| 84 | + | |
| 85 | + @staticmethod | |
| 86 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 87 | + | |
| 88 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 89 | + | |
| 90 | + dataframe['sell'] = 0 | |
| 91 | + return dataframe | |
| 92 | + | |
| 93 | + return populate_sell_trend | |
| 94 | + | |
| 95 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 96 | + | |
| 97 | + dataframe['sell'] = 0 | |
| 98 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp-v2.py +82 −0
| @@ -0,0 +1,82 @@ | ||
| 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 Schism2Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(15, 70, name='rmi-slow'), | |
| 20 | + Integer(10, 50, name='rmi-fast'), | |
| 21 | + Integer(10, 70, name='mp'), | |
| 22 | + Integer(10, 70, name='inf-rsi'), | |
| 23 | + Real(0.70, 0.99, name='inf-pct-adr'), | |
| 24 | + Integer(10, 70, name='xinf-stake-rmi'), | |
| 25 | + Integer(50, 90, name='xtf-stake-rsi'), | |
| 26 | + Integer(10, 70, name='xtf-fiat-rsi') | |
| 27 | + ] | |
| 28 | + | |
| 29 | + @staticmethod | |
| 30 | + def sell_indicator_space() -> List[Dimension]: | |
| 31 | + return [] | |
| 32 | + | |
| 33 | + @staticmethod | |
| 34 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 35 | + | |
| 36 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 37 | + | |
| 38 | + inf_timeframe = '1h' | |
| 39 | + stake_currency = 'USD' | |
| 40 | + fiat = 'USD' | |
| 41 | + conditions = [] | |
| 42 | + | |
| 43 | + conditions.append( | |
| 44 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['inf-rsi']) & | |
| 45 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{inf_timeframe}"])) & | |
| 46 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 47 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 48 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 49 | + (dataframe['mp'] <= params['mp']) | |
| 50 | + ) | |
| 51 | + | |
| 52 | + if stake_currency in ('BTC', 'ETH'): | |
| 53 | + conditions.append( | |
| 54 | + (dataframe[f"{stake_currency}_rsi"] < params['xtf-stake-rsi']) | | |
| 55 | + (dataframe[f"{fiat}_rsi"] > params['xtf-fiat-rsi']) | |
| 56 | + ) | |
| 57 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 58 | + | |
| 59 | + conditions.append(dataframe['volume'].gt(0)) | |
| 60 | + | |
| 61 | + if conditions: | |
| 62 | + dataframe.loc[ | |
| 63 | + reduce(lambda x, y: x & y, conditions), | |
| 64 | + 'buy'] = 1 | |
| 65 | + return dataframe | |
| 66 | + | |
| 67 | + return populate_buy_trend | |
| 68 | + | |
| 69 | + @staticmethod | |
| 70 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 71 | + | |
| 72 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 73 | + | |
| 74 | + dataframe['sell'] = 0 | |
| 75 | + return dataframe | |
| 76 | + | |
| 77 | + return populate_sell_trend | |
| 78 | + | |
| 79 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 80 | + | |
| 81 | + dataframe['sell'] = 0 | |
| 82 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SchismHyp.py +114 −0
| @@ -0,0 +1,114 @@ | ||
| 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 SchismHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(1, 10, name='bounce-lookback'), | |
| 20 | + Integer(20, 50, name='down-inf-rsi'), | |
| 21 | + Integer(20, 50, name='down-rmi-slow'), | |
| 22 | + Integer(10, 50, name='down-rmi-fast'), | |
| 23 | + Integer(10, 70, name='down-mp'), | |
| 24 | + Integer(30, 70, name='up-inf-rsi'), | |
| 25 | + Integer(30, 70, name='up-rmi-slow'), | |
| 26 | + Integer(10, 50, name='up-rmi-fast'), | |
| 27 | + Integer(10, 70, name='xinf-stake-rmi'), | |
| 28 | + Integer(50, 90, name='xtf-stake-rsi'), | |
| 29 | + Integer(10, 70, name='xtf-fiat-rsi') | |
| 30 | + ] | |
| 31 | + | |
| 32 | + @staticmethod | |
| 33 | + def sell_indicator_space() -> List[Dimension]: | |
| 34 | + return [ | |
| 35 | + Integer(30, 70, name='rmi-high'), | |
| 36 | + Integer(10, 30, name='rmi-low') | |
| 37 | + ] | |
| 38 | + | |
| 39 | + @staticmethod | |
| 40 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 41 | + | |
| 42 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 43 | + | |
| 44 | + inf_timeframe = '1h' | |
| 45 | + stake_currency = 'USD' | |
| 46 | + fiat = 'USD' | |
| 47 | + conditions = [] | |
| 48 | + | |
| 49 | + dataframe['bounce-pending'] = np.where( | |
| 50 | + (dataframe[f"rsi_{inf_timeframe}"] < params['down-inf-rsi']) & | |
| 51 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 52 | + (dataframe['rmi-slow'] > params['down-rmi-slow']) & | |
| 53 | + (dataframe['rmi-fast'] < params['down-rmi-fast']) & | |
| 54 | + (dataframe['mp'] <= params['down-mp']), | |
| 55 | + 1,0 | |
| 56 | + ) | |
| 57 | + | |
| 58 | + dataframe['bounce-price'] = np.where( | |
| 59 | + dataframe['bounce-pending'] == 1, | |
| 60 | + dataframe['close'], | |
| 61 | + dataframe['close'].rolling(params['bounce-lookback'], min_periods=1).min() #min/max/mean? | |
| 62 | + ) | |
| 63 | + | |
| 64 | + dataframe['bounce-range'] = np.where(dataframe['bounce-pending'].rolling(params['bounce-lookback'], min_periods=1).sum() >= 1,1,0) | |
| 65 | + | |
| 66 | + conditions.append( | |
| 67 | + (dataframe[f"rsi_{inf_timeframe}"] > params['up-inf-rsi']) & | |
| 68 | + (dataframe['bounce-range'] == 1) & | |
| 69 | + (dataframe['rmi-up-trend'] == 1) & | |
| 70 | + # 3 (dataframe['rmi-slow'] < params['up-rmi-slow']) & | |
| 71 | + # 3 (dataframe['rmi-fast'] > params['up-rmi-fast']) & | |
| 72 | + (dataframe['close'] > dataframe['bounce-price']) | |
| 73 | + ) | |
| 74 | + | |
| 75 | + """ | |
| 76 | + if stake_currency in ('BTC', 'ETH'): | |
| 77 | + conditions.append( | |
| 78 | + (dataframe[f"{stake_currency}_rsi"] > params['xtf-stake-rsi']) | | |
| 79 | + (dataframe[f"{fiat}_rsi"] < params['xtf-fiat-rsi']) | |
| 80 | + ) | |
| 81 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 82 | + """ | |
| 83 | + | |
| 84 | + conditions.append(dataframe['volume'].gt(0)) | |
| 85 | + | |
| 86 | + if conditions: | |
| 87 | + dataframe.loc[ | |
| 88 | + reduce(lambda x, y: x & y, conditions), | |
| 89 | + 'buy'] = 1 | |
| 90 | + return dataframe | |
| 91 | + | |
| 92 | + return populate_buy_trend | |
| 93 | + | |
| 94 | + @staticmethod | |
| 95 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 96 | + | |
| 97 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 98 | + | |
| 99 | + conditions.append((dataframe['rmi-dn-trend'] == 1)) | |
| 100 | + conditions.append( | |
| 101 | + qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-high']) | | |
| 102 | + qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-low']) | |
| 103 | + ) | |
| 104 | + | |
| 105 | + conditions.append(dataframe['volume'].gt(0)) | |
| 106 | + | |
| 107 | + if conditions: | |
| 108 | + dataframe.loc[ | |
| 109 | + reduce(lambda x, y: x & y, conditions), | |
| 110 | + 'sell'] = 1 | |
| 111 | + | |
| 112 | + return dataframe | |
| 113 | + | |
| 114 | + return populate_sell_trend | |
| No newline at the end of the file |
added hyperopts/old/SchismLessHyp.py +79 −0
| @@ -0,0 +1,79 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class SchismHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Integer(15, 70, name='rmi-slow'), | |
| 25 | + Integer(10, 50, name='rmi-fast'), | |
| 26 | + Integer(10, 70, name='mp'), | |
| 27 | + Integer(10, 70, name='inf-rsi') | |
| 28 | + ] | |
| 29 | + | |
| 30 | + @staticmethod | |
| 31 | + def sell_indicator_space() -> List[Dimension]: | |
| 32 | + return [] | |
| 33 | + | |
| 34 | + @staticmethod | |
| 35 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 36 | + | |
| 37 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 38 | + | |
| 39 | + inf_timeframe = '4h' | |
| 40 | + conditions = [] | |
| 41 | + | |
| 42 | + conditions.append( | |
| 43 | + (dataframe[f"rsi_{inf_timeframe}"] < params['inf-rsi']) & | |
| 44 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 45 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 46 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 47 | + (dataframe['mp'] <= params['mp']) | |
| 48 | + ) | |
| 49 | + | |
| 50 | + conditions.append(dataframe['volume'].gt(0)) | |
| 51 | + | |
| 52 | + if conditions: | |
| 53 | + dataframe.loc[ | |
| 54 | + reduce(lambda x, y: x & y, conditions), | |
| 55 | + 'buy'] = 1 | |
| 56 | + return dataframe | |
| 57 | + | |
| 58 | + return populate_buy_trend | |
| 59 | + | |
| 60 | + @staticmethod | |
| 61 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 62 | + """ | |
| 63 | + Define the sell strategy parameters to be used by Hyperopt. | |
| 64 | + """ | |
| 65 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 66 | + """ | |
| 67 | + no sell signal | |
| 68 | + """ | |
| 69 | + dataframe['sell'] = 0 | |
| 70 | + return dataframe | |
| 71 | + | |
| 72 | + return populate_sell_trend | |
| 73 | + | |
| 74 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 75 | + """ | |
| 76 | + no sell signal | |
| 77 | + """ | |
| 78 | + dataframe['sell'] = 0 | |
| 79 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-Con-v1.py +105 −0
| @@ -0,0 +1,105 @@ | ||
| 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 SolipsisConHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(0, 100, name='consensus-buy'), | |
| 20 | + # Informative Timeframe | |
| 21 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 22 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 23 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 24 | + # Extra BTC/ETH Stakes | |
| 25 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 26 | + Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 27 | + Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 28 | + # Extra BTC/STAKE if not in whitelist | |
| 29 | + Integer(0, 100, name='xbtc-consensus-buy') | |
| 30 | + ] | |
| 31 | + | |
| 32 | + @staticmethod | |
| 33 | + def sell_indicator_space() -> List[Dimension]: | |
| 34 | + return [ | |
| 35 | + Integer(0, 100, name='consensus-sell') | |
| 36 | + ] | |
| 37 | + | |
| 38 | + @staticmethod | |
| 39 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 40 | + | |
| 41 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 42 | + conditions = [] | |
| 43 | + | |
| 44 | + inf_timeframe = '1h' | |
| 45 | + stake_currency = 'USD' | |
| 46 | + custom_fiat = 'USD' | |
| 47 | + btc_in_whitelist = False | |
| 48 | + | |
| 49 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 50 | + conditions.append( | |
| 51 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 52 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 53 | + ) | |
| 54 | + | |
| 55 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 56 | + conditions.append( | |
| 57 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 58 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 59 | + ) | |
| 60 | + | |
| 61 | + conditions.append(dataframe['consensus_buy'] > params['consensus-buy']) | |
| 62 | + | |
| 63 | + if stake_currency in ('BTC', 'ETH'): | |
| 64 | + conditions.append( | |
| 65 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 66 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 67 | + ) | |
| 68 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 69 | + else: | |
| 70 | + if btc_in_whitelist == False: | |
| 71 | + conditions.append(dataframe['BTC_consensus_buy'] > params['xbtc-consensus-buy']) | |
| 72 | + | |
| 73 | + conditions.append(dataframe['volume'].gt(0)) | |
| 74 | + | |
| 75 | + if conditions: | |
| 76 | + dataframe.loc[ | |
| 77 | + reduce(lambda x, y: x & y, conditions), | |
| 78 | + 'buy'] = 1 | |
| 79 | + return dataframe | |
| 80 | + | |
| 81 | + return populate_buy_trend | |
| 82 | + | |
| 83 | + @staticmethod | |
| 84 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 85 | + | |
| 86 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 87 | + conditions = [] | |
| 88 | + | |
| 89 | + conditions.append(dataframe['consensus_sell'] > params['consensus-sell']) | |
| 90 | + | |
| 91 | + if conditions: | |
| 92 | + dataframe.loc[ | |
| 93 | + reduce(lambda x, y: x & y, conditions), | |
| 94 | + 'sell'] = 1 | |
| 95 | + | |
| 96 | + # dataframe['sell'] = 0 | |
| 97 | + return dataframe | |
| 98 | + | |
| 99 | + return populate_sell_trend | |
| 100 | + | |
| 101 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 102 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 103 | + | |
| 104 | + dataframe['sell'] = 0 | |
| 105 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-Con.py +105 −0
| @@ -0,0 +1,105 @@ | ||
| 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 SolipsisConHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(0, 100, name='consensus-buy'), | |
| 20 | + # Informative Timeframe | |
| 21 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 22 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 23 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 24 | + # Extra BTC/ETH Stakes | |
| 25 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 26 | + Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 27 | + Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 28 | + # Extra BTC/STAKE if not in whitelist | |
| 29 | + Integer(0, 100, name='xbtc-consensus-buy') | |
| 30 | + ] | |
| 31 | + | |
| 32 | + @staticmethod | |
| 33 | + def sell_indicator_space() -> List[Dimension]: | |
| 34 | + return [ | |
| 35 | + Integer(0, 100, name='consensus-sell') | |
| 36 | + ] | |
| 37 | + | |
| 38 | + @staticmethod | |
| 39 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 40 | + | |
| 41 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 42 | + conditions = [] | |
| 43 | + | |
| 44 | + inf_timeframe = '1h' | |
| 45 | + stake_currency = 'USD' | |
| 46 | + custom_fiat = 'USD' | |
| 47 | + btc_in_whitelist = False | |
| 48 | + | |
| 49 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 50 | + conditions.append( | |
| 51 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 52 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 53 | + ) | |
| 54 | + | |
| 55 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 56 | + conditions.append( | |
| 57 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 58 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 59 | + ) | |
| 60 | + | |
| 61 | + conditions.append(dataframe['consensus_buy'] > params['consensus-buy']) | |
| 62 | + | |
| 63 | + if stake_currency in ('BTC', 'ETH'): | |
| 64 | + conditions.append( | |
| 65 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 66 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 67 | + ) | |
| 68 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 69 | + else: | |
| 70 | + if btc_in_whitelist == False: | |
| 71 | + conditions.append(dataframe['BTC_consensus_buy'] > params['xbtc-consensus-buy']) | |
| 72 | + | |
| 73 | + conditions.append(dataframe['volume'].gt(0)) | |
| 74 | + | |
| 75 | + if conditions: | |
| 76 | + dataframe.loc[ | |
| 77 | + reduce(lambda x, y: x & y, conditions), | |
| 78 | + 'buy'] = 1 | |
| 79 | + return dataframe | |
| 80 | + | |
| 81 | + return populate_buy_trend | |
| 82 | + | |
| 83 | + @staticmethod | |
| 84 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 85 | + | |
| 86 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 87 | + conditions = [] | |
| 88 | + | |
| 89 | + conditions.append(dataframe['consensus_sell'] > params['consensus-sell']) | |
| 90 | + | |
| 91 | + if conditions: | |
| 92 | + dataframe.loc[ | |
| 93 | + reduce(lambda x, y: x & y, conditions), | |
| 94 | + 'sell'] = 1 | |
| 95 | + | |
| 96 | + # dataframe['sell'] = 0 | |
| 97 | + return dataframe | |
| 98 | + | |
| 99 | + return populate_sell_trend | |
| 100 | + | |
| 101 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 102 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 103 | + | |
| 104 | + dataframe['sell'] = 0 | |
| 105 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-v1.py +141 −0
| @@ -0,0 +1,141 @@ | ||
| 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 SolipsisHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + # Base Timeframe | |
| 20 | + Categorical(['up', 'down'], name='base-trend'), | |
| 21 | + Categorical([True, False], name='base-pmax-enable'), | |
| 22 | + Categorical(['up', 'down'], name='base-pmax'), | |
| 23 | + Integer(10, 90, name='base-rmi-slow'), | |
| 24 | + Integer(10, 90, name='base-rmi-fast'), | |
| 25 | + Integer(10, 90, name='base-mp'), | |
| 26 | + Categorical([1.0, 0.786, 0.618, 0.5, 0.382, 0.236, 0.0], name='base-fib-level'), | |
| 27 | + # Informative Timeframe | |
| 28 | + Integer(10, 70, name='inf-rsi'), | |
| 29 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 30 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 31 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 32 | + Categorical([1.0, 0.786, 0.618, 0.5, 0.382, 0.236, 0.0], name='inf-fib-level'), | |
| 33 | + # Exra BTC/ETH Stakes | |
| 34 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 35 | + Integer(10, 70, name='xtra-base-stake-rsi'), | |
| 36 | + Integer(10, 70, name='xtra-base-fiat-rsi') | |
| 37 | + ] | |
| 38 | + | |
| 39 | + @staticmethod | |
| 40 | + def sell_indicator_space() -> List[Dimension]: | |
| 41 | + return [ | |
| 42 | + Real(0.10, 0.90, name='sell-rmi-drop'), | |
| 43 | + Categorical([True, False], name='sell-pmax-enable'), | |
| 44 | + ] | |
| 45 | + | |
| 46 | + @staticmethod | |
| 47 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 48 | + | |
| 49 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 50 | + conditions = [] | |
| 51 | + | |
| 52 | + inf_timeframe = '1h' | |
| 53 | + stake_currency = 'USD' | |
| 54 | + custom_fiat = 'USD' | |
| 55 | + | |
| 56 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 57 | + conditions.append( | |
| 58 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 59 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 60 | + ) | |
| 61 | + | |
| 62 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 63 | + conditions.append( | |
| 64 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 65 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 66 | + ) | |
| 67 | + | |
| 68 | + conditions.append( | |
| 69 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['inf-rsi']) & | |
| 70 | + (dataframe[f"fib-ret_{inf_timeframe}"] >= params['inf-fib-level']) | |
| 71 | + ) | |
| 72 | + | |
| 73 | + if params['base-pmax-enable'] == True: | |
| 74 | + conditions.append((dataframe['pmax-trend'] == params['base-pmax'])) | |
| 75 | + | |
| 76 | + if params['base-trend'] == 'down': | |
| 77 | + conditions.append( | |
| 78 | + (dataframe['fib-ret'] <= params['base-fib-level']) & | |
| 79 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 80 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 81 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 82 | + (dataframe['mp'] <= params['base-mp']) | |
| 83 | + ) | |
| 84 | + | |
| 85 | + elif params['base-trend'] == 'up': | |
| 86 | + conditions.append( | |
| 87 | + (dataframe['fib-ret'] >= params['base-fib-level']) & | |
| 88 | + (dataframe['rmi-up-trend'] == 1) & | |
| 89 | + (dataframe['rmi-slow'] <= params['base-rmi-slow']) & | |
| 90 | + (dataframe['rmi-fast'] >= params['base-rmi-fast']) & | |
| 91 | + (dataframe['mp'] >= params['base-mp']) | |
| 92 | + ) | |
| 93 | + | |
| 94 | + if stake_currency in ('BTC', 'ETH'): | |
| 95 | + conditions.append( | |
| 96 | + (dataframe[f"{stake_currency}_rsi"] < params['xtra-base-stake-rsi']) | | |
| 97 | + (dataframe[f"{custom_fiat}_rsi"] > params['xtra-base-fiat-rsi']) | |
| 98 | + ) | |
| 99 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 100 | + | |
| 101 | + conditions.append(dataframe['volume'].gt(0)) | |
| 102 | + | |
| 103 | + if conditions: | |
| 104 | + dataframe.loc[ | |
| 105 | + reduce(lambda x, y: x & y, conditions), | |
| 106 | + 'buy'] = 1 | |
| 107 | + return dataframe | |
| 108 | + | |
| 109 | + return populate_buy_trend | |
| 110 | + | |
| 111 | + @staticmethod | |
| 112 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 113 | + | |
| 114 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 115 | + conditions = [] | |
| 116 | + | |
| 117 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 118 | + conditions.append( | |
| 119 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 120 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 121 | + (dataframe['volume'].gt(0)) | |
| 122 | + ) | |
| 123 | + | |
| 124 | + if params['sell-pmax-enable'] == True: | |
| 125 | + conditions.append((dataframe['pmax-trend'] == 'down')) | |
| 126 | + | |
| 127 | + if conditions: | |
| 128 | + dataframe.loc[ | |
| 129 | + reduce(lambda x, y: x & y, conditions), | |
| 130 | + 'sell'] = 1 | |
| 131 | + | |
| 132 | + # dataframe['sell'] = 0 | |
| 133 | + return dataframe | |
| 134 | + | |
| 135 | + return populate_sell_trend | |
| 136 | + | |
| 137 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 138 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 139 | + | |
| 140 | + dataframe['sell'] = 0 | |
| 141 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-v2.4.py +135 −0
| @@ -0,0 +1,135 @@ | ||
| 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 SolipsisHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + Integer(0, 100, name='consensus-buy'), | |
| 20 | + # Informative Timeframe | |
| 21 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 22 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 23 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 24 | + # Extra BTC/ETH Stakes | |
| 25 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 26 | + Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 27 | + Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 28 | + # Extra BTC/STAKE if not in whitelist | |
| 29 | + Integer(0, 100, name='xbtc-consensus-buy') | |
| 30 | + ] | |
| 31 | + | |
| 32 | + @staticmethod | |
| 33 | + def sell_indicator_space() -> List[Dimension]: | |
| 34 | + return [] | |
| 35 | + | |
| 36 | + @staticmethod | |
| 37 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 38 | + | |
| 39 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 40 | + conditions = [] | |
| 41 | + | |
| 42 | + inf_timeframe = '1h' | |
| 43 | + stake_currency = 'USD' | |
| 44 | + custom_fiat = 'USD' | |
| 45 | + btc_in_whitelist = False | |
| 46 | + | |
| 47 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 48 | + conditions.append( | |
| 49 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 50 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 51 | + ) | |
| 52 | + | |
| 53 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 54 | + conditions.append( | |
| 55 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 56 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 57 | + ) | |
| 58 | + | |
| 59 | + conditions.append(dataframe['consensus-buy'] > params['consensus-buy']) | |
| 60 | + | |
| 61 | + if stake_currency in ('BTC', 'ETH'): | |
| 62 | + conditions.append( | |
| 63 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 64 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 65 | + ) | |
| 66 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 67 | + else: | |
| 68 | + if btc_in_whitelist == False: | |
| 69 | + conditions.append(dataframe['BTC_consensus-buy'] > params['xbtc-consensus-buy']) | |
| 70 | + | |
| 71 | + conditions.append(dataframe['volume'].gt(0)) | |
| 72 | + | |
| 73 | + if conditions: | |
| 74 | + dataframe.loc[ | |
| 75 | + reduce(lambda x, y: x & y, conditions), | |
| 76 | + 'buy'] = 1 | |
| 77 | + return dataframe | |
| 78 | + | |
| 79 | + return populate_buy_trend | |
| 80 | + | |
| 81 | + @staticmethod | |
| 82 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 83 | + | |
| 84 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 85 | + | |
| 86 | + dataframe['sell'] = 0 | |
| 87 | + return dataframe | |
| 88 | + | |
| 89 | + return populate_sell_trend | |
| 90 | + | |
| 91 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 92 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 93 | + | |
| 94 | + dataframe['sell'] = 0 | |
| 95 | + return dataframe | |
| 96 | + | |
| 97 | + @staticmethod | |
| 98 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 99 | + | |
| 100 | + roi_table = {} | |
| 101 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 102 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 103 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 104 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 105 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 106 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 107 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 108 | + | |
| 109 | + return roi_table | |
| 110 | + | |
| 111 | + @staticmethod | |
| 112 | + def roi_space() -> List[Dimension]: | |
| 113 | + # min / max min / max | |
| 114 | + return [ # 0 : 0.100 / 0.205 | |
| 115 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 116 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 117 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 118 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 119 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 120 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 121 | + | |
| 122 | + Real(0.05, 0.10, name='roi_p6'), | |
| 123 | + Real(0.02, 0.05, name='roi_p5'), | |
| 124 | + Real(0.015, 0.020, name='roi_p4'), | |
| 125 | + Real(0.005, 0.015, name='roi_p3'), | |
| 126 | + Real(0.005, 0.01, name='roi_p2'), | |
| 127 | + Real(0.005, 0.01, name='roi_p1'), | |
| 128 | + ] | |
| 129 | + | |
| 130 | + @staticmethod | |
| 131 | + def stoploss_space() -> List[Dimension]: | |
| 132 | + | |
| 133 | + return [ | |
| 134 | + Real(-0.99, -0.01, name='stoploss'), | |
| 135 | + ] | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-v2.5.py +141 −0
| @@ -0,0 +1,141 @@ | ||
| 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 Solipsis5Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + # Base Timeframe | |
| 20 | + Integer(5, 15, name='base-yolo'), | |
| 21 | + # Informative Timeframe | |
| 22 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 23 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 24 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 25 | + # Extra BTC/ETH Stakes | |
| 26 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 27 | + Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 28 | + Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 29 | + # Extra BTC/STAKE if not in whitelist | |
| 30 | + Integer(10, 70, name='xbtc-base-rmi'), | |
| 31 | + Integer(10, 70, name='xbtc-inf-rmi') | |
| 32 | + ] | |
| 33 | + | |
| 34 | + @staticmethod | |
| 35 | + def sell_indicator_space() -> List[Dimension]: | |
| 36 | + return [] | |
| 37 | + | |
| 38 | + @staticmethod | |
| 39 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 40 | + | |
| 41 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 42 | + conditions = [] | |
| 43 | + | |
| 44 | + inf_timeframe = '1h' | |
| 45 | + stake_currency = 'USD' | |
| 46 | + custom_fiat = 'USD' | |
| 47 | + btc_in_whitelist = False | |
| 48 | + | |
| 49 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 50 | + conditions.append( | |
| 51 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 52 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 53 | + ) | |
| 54 | + | |
| 55 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 56 | + conditions.append( | |
| 57 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 58 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 59 | + ) | |
| 60 | + | |
| 61 | + # YOLO ON THE BASE | |
| 62 | + conditions.append(dataframe['yolo'] > params['base-yolo']) | |
| 63 | + | |
| 64 | + if stake_currency in ('BTC', 'ETH'): | |
| 65 | + conditions.append( | |
| 66 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 67 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 68 | + ) | |
| 69 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 70 | + else: | |
| 71 | + if btc_in_whitelist == False: | |
| 72 | + conditions.append( | |
| 73 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 74 | + (dataframe[f"BTC_rmi_{inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 75 | + ) | |
| 76 | + | |
| 77 | + conditions.append(dataframe['volume'].gt(0)) | |
| 78 | + | |
| 79 | + if conditions: | |
| 80 | + dataframe.loc[ | |
| 81 | + reduce(lambda x, y: x & y, conditions), | |
| 82 | + 'buy'] = 1 | |
| 83 | + return dataframe | |
| 84 | + | |
| 85 | + return populate_buy_trend | |
| 86 | + | |
| 87 | + @staticmethod | |
| 88 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 89 | + | |
| 90 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 91 | + | |
| 92 | + dataframe['sell'] = 0 | |
| 93 | + return dataframe | |
| 94 | + | |
| 95 | + return populate_sell_trend | |
| 96 | + | |
| 97 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 98 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 99 | + | |
| 100 | + dataframe['sell'] = 0 | |
| 101 | + return dataframe | |
| 102 | + | |
| 103 | + @staticmethod | |
| 104 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 105 | + | |
| 106 | + roi_table = {} | |
| 107 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 108 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 109 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 110 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 111 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 112 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 113 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 114 | + | |
| 115 | + return roi_table | |
| 116 | + | |
| 117 | + @staticmethod | |
| 118 | + def roi_space() -> List[Dimension]: | |
| 119 | + # min / max min / max | |
| 120 | + return [ # 0 : 0.100 / 0.205 | |
| 121 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 122 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 123 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 124 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 125 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 126 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 127 | + | |
| 128 | + Real(0.05, 0.10, name='roi_p6'), | |
| 129 | + Real(0.02, 0.05, name='roi_p5'), | |
| 130 | + Real(0.015, 0.020, name='roi_p4'), | |
| 131 | + Real(0.005, 0.015, name='roi_p3'), | |
| 132 | + Real(0.005, 0.01, name='roi_p2'), | |
| 133 | + Real(0.005, 0.01, name='roi_p1'), | |
| 134 | + ] | |
| 135 | + | |
| 136 | + @staticmethod | |
| 137 | + def stoploss_space() -> List[Dimension]: | |
| 138 | + | |
| 139 | + return [ | |
| 140 | + Real(-0.99, -0.01, name='stoploss'), | |
| 141 | + ] | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-v2.6.py +222 −0
| @@ -0,0 +1,222 @@ | ||
| 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 Solipsis6Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + # Base Timeframe | |
| 20 | + Real(0.005, 0.015, name='base-bbdelta'), | |
| 21 | + Real(0.01, 0.03, name='base-closedelta'), | |
| 22 | + Real(0.10, 0.75, name='base-tail'), | |
| 23 | + Real(0.75, 1.1, name='base-bblower'), | |
| 24 | + Integer(5,50, name='base-vms'), | |
| 25 | + # Informative Timeframe | |
| 26 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 27 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 28 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 29 | + # Extra BTC/ETH Stakes | |
| 30 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 31 | + Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 32 | + Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 33 | + # Extra BTC/STAKE if not in whitelist | |
| 34 | + Integer(10, 70, name='xbtc-base-rmi'), | |
| 35 | + Integer(10, 70, name='xbtc-inf-rmi') | |
| 36 | + ] | |
| 37 | + | |
| 38 | + @staticmethod | |
| 39 | + def sell_indicator_space() -> List[Dimension]: | |
| 40 | + return [] | |
| 41 | + | |
| 42 | + @staticmethod | |
| 43 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 44 | + | |
| 45 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 46 | + conditions = [] | |
| 47 | + | |
| 48 | + inf_timeframe = '1h' | |
| 49 | + stake_currency = 'USD' | |
| 50 | + custom_fiat = 'USD' | |
| 51 | + btc_in_whitelist = False | |
| 52 | + | |
| 53 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 54 | + conditions.append( | |
| 55 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 56 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 57 | + ) | |
| 58 | + | |
| 59 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 60 | + conditions.append( | |
| 61 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 62 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 63 | + ) | |
| 64 | + | |
| 65 | + conditions.append( | |
| 66 | + ( | |
| 67 | + dataframe['lower'].shift().gt(0) & | |
| 68 | + dataframe['bbdelta'].gt(dataframe['close'] * params['base-bbdelta']) & | |
| 69 | + dataframe['closedelta'].gt(dataframe['close'] * params['base-closedelta']) & | |
| 70 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['base-tail']) & | |
| 71 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 72 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 73 | + ) | | |
| 74 | + ( | |
| 75 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 76 | + (dataframe['close'] < (params['base-bblower'] * dataframe['bb_lowerband'])) & | |
| 77 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['base-vms'])) | |
| 78 | + ) | |
| 79 | + ) | |
| 80 | + | |
| 81 | + if stake_currency in ('BTC', 'ETH'): | |
| 82 | + conditions.append( | |
| 83 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 84 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 85 | + ) | |
| 86 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 87 | + else: | |
| 88 | + if btc_in_whitelist == False: | |
| 89 | + conditions.append( | |
| 90 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 91 | + (dataframe[f"BTC_rmi_{inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 92 | + ) | |
| 93 | + | |
| 94 | + conditions.append(dataframe['volume'].gt(0)) | |
| 95 | + | |
| 96 | + if conditions: | |
| 97 | + dataframe.loc[ | |
| 98 | + reduce(lambda x, y: x & y, conditions), | |
| 99 | + 'buy'] = 1 | |
| 100 | + return dataframe | |
| 101 | + | |
| 102 | + return populate_buy_trend | |
| 103 | + | |
| 104 | + @staticmethod | |
| 105 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 106 | + | |
| 107 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 108 | + | |
| 109 | + dataframe['sell'] = 0 | |
| 110 | + return dataframe | |
| 111 | + | |
| 112 | + return populate_sell_trend | |
| 113 | + | |
| 114 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 115 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + | |
| 117 | + dataframe['sell'] = 0 | |
| 118 | + return dataframe | |
| 119 | + | |
| 120 | + @staticmethod | |
| 121 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 122 | + | |
| 123 | + roi_table = {} | |
| 124 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 125 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 126 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 127 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 128 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 129 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 130 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 131 | + | |
| 132 | + return roi_table | |
| 133 | + | |
| 134 | + @staticmethod | |
| 135 | + def roi_space() -> List[Dimension]: | |
| 136 | + # min / max min / max | |
| 137 | + return [ # 0 : 0.100 / 0.205 | |
| 138 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 139 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 140 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 141 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 142 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 143 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 144 | + | |
| 145 | + Real(0.05, 0.10, name='roi_p6'), | |
| 146 | + Real(0.02, 0.05, name='roi_p5'), | |
| 147 | + Real(0.015, 0.020, name='roi_p4'), | |
| 148 | + Real(0.005, 0.015, name='roi_p3'), | |
| 149 | + Real(0.005, 0.01, name='roi_p2'), | |
| 150 | + Real(0.005, 0.01, name='roi_p1'), | |
| 151 | + ] | |
| 152 | + | |
| 153 | + # None of this will work unless you pull the fork werkkrew/freqtrade and switch to branch hyperopt | |
| 154 | + # Which you almost certainly do *not* want to do. | |
| 155 | + @staticmethod | |
| 156 | + def generate_dynamic_roi(params: Dict) -> Dict[int, float]: | |
| 157 | + | |
| 158 | + dynamic_roi = { | |
| 159 | + 'enabled': params['droi_enabled'], | |
| 160 | + 'profit-factor': params['droi_profit_factor'], | |
| 161 | + 'rmi-start': params['droi_rmi_start'], | |
| 162 | + 'rmi-end': params['droi_rmi_end'], | |
| 163 | + 'grow-delay': params['droi_grow_delay'], | |
| 164 | + 'grow-time': params['droi_grow_time'], | |
| 165 | + 'fallback': params['droi_fallback'], | |
| 166 | + 'min-roc-atr': params['droi_min_roc_atr'] | |
| 167 | + } | |
| 168 | + | |
| 169 | + return dynamic_roi | |
| 170 | + | |
| 171 | + @staticmethod | |
| 172 | + def dynamic_roi_space() -> List[Dimension]: | |
| 173 | + | |
| 174 | + return [ | |
| 175 | + Categorical([True], 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', 'atr', 'roc', 'roc-table', 'atr-table'], name='droi_fallback'), | |
| 182 | + Real(0.0, 1.0, name='droi_min_roc_atr') | |
| 183 | + ] | |
| 184 | + | |
| 185 | + | |
| 186 | + @staticmethod | |
| 187 | + def generate_custom_stop(params: Dict) -> Dict[int, float]: | |
| 188 | + | |
| 189 | + custom_stop = { | |
| 190 | + 'decay-time': params['cstp_decay_time'], | |
| 191 | + 'decay-delay': params['cstp_decay_delay'], | |
| 192 | + 'decay-start': params['cstp_decay_start'], | |
| 193 | + 'decay-end': params['cstp_decay_end'], | |
| 194 | + 'cur-min-diff': params['cstp_cur_min_diff'], | |
| 195 | + 'cur-threshold': params['cstp_cur_threshold'], | |
| 196 | + 'roc-bail': params['cstp_roc_bail'], | |
| 197 | + 'rmi-trend': params['cstp_rmi_trend'], | |
| 198 | + 'bail-how': params['cstp_bail_how'], | |
| 199 | + 'pos-trail': params['cstp_pos_trail'], | |
| 200 | + 'pos-threshold': params['cstp_pos_threshold'], | |
| 201 | + 'pos-trail-dist': params['cstp_trail_dist'] | |
| 202 | + } | |
| 203 | + | |
| 204 | + return custom_stop | |
| 205 | + | |
| 206 | + @staticmethod | |
| 207 | + def custom_stoploss_space() -> List[Dimension]: | |
| 208 | + | |
| 209 | + return [ | |
| 210 | + Integer(500, 1440, name='cstp_decay_time'), | |
| 211 | + Integer(0, 360, name='cstp_decay_delay'), | |
| 212 | + Real(-0.30, -0.20, name='cstp_decay_start'), | |
| 213 | + Real(-0.05, 0, name='cstp_decay_end'), | |
| 214 | + Real(0.01, 0.04, name='cstp_cur_min_diff'), | |
| 215 | + Real(-0.05, 0, name='cstp_cur_threshold'), | |
| 216 | + Real(-0.05, 0, name='cstp_roc_bail'), | |
| 217 | + Integer(30, 70, name='cstp_rmi_trend'), | |
| 218 | + Categorical(['atr', 'immediate'], name='cstp_bail_how'), | |
| 219 | + Categorical([True, False], name='cstp_pos_trail'), | |
| 220 | + Real(0.0, 0.03, name='cstp_pos_threshold'), | |
| 221 | + Real(0.005, 0.03, name='cstp_trail_dist') | |
| 222 | + ] | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-v2.py +122 −0
| @@ -0,0 +1,122 @@ | ||
| 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 SolipsisHyp(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(10, 50, name='base-rmi-fast'), | |
| 22 | + Integer(10, 50, 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 | + Real(0.10, 0.90, name='sell-rmi-drop') | |
| 40 | + ] | |
| 41 | + | |
| 42 | + @staticmethod | |
| 43 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 44 | + | |
| 45 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 46 | + conditions = [] | |
| 47 | + | |
| 48 | + inf_timeframe = '1h' | |
| 49 | + stake_currency = 'USD' | |
| 50 | + custom_fiat = 'USD' | |
| 51 | + btc_in_whitelist = False | |
| 52 | + | |
| 53 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 54 | + conditions.append( | |
| 55 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 56 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 57 | + ) | |
| 58 | + | |
| 59 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 60 | + conditions.append( | |
| 61 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 62 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 63 | + ) | |
| 64 | + | |
| 65 | + conditions.append( | |
| 66 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 67 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 68 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 69 | + (dataframe['mp'] <= params['base-mp']) | |
| 70 | + ) | |
| 71 | + | |
| 72 | + if stake_currency in ('BTC', 'ETH'): | |
| 73 | + conditions.append( | |
| 74 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 75 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 76 | + ) | |
| 77 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 78 | + else: | |
| 79 | + if btc_in_whitelist == False: | |
| 80 | + conditions.append( | |
| 81 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 82 | + (dataframe[f"BTC_rmi_{inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 83 | + ) | |
| 84 | + | |
| 85 | + conditions.append(dataframe['volume'].gt(0)) | |
| 86 | + | |
| 87 | + if conditions: | |
| 88 | + dataframe.loc[ | |
| 89 | + reduce(lambda x, y: x & y, conditions), | |
| 90 | + 'buy'] = 1 | |
| 91 | + return dataframe | |
| 92 | + | |
| 93 | + return populate_buy_trend | |
| 94 | + | |
| 95 | + @staticmethod | |
| 96 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 97 | + | |
| 98 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 99 | + conditions = [] | |
| 100 | + | |
| 101 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 102 | + conditions.append( | |
| 103 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 104 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 105 | + (dataframe['volume'].gt(0)) | |
| 106 | + ) | |
| 107 | + | |
| 108 | + if conditions: | |
| 109 | + dataframe.loc[ | |
| 110 | + reduce(lambda x, y: x & y, conditions), | |
| 111 | + 'sell'] = 1 | |
| 112 | + | |
| 113 | + # dataframe['sell'] = 0 | |
| 114 | + return dataframe | |
| 115 | + | |
| 116 | + return populate_sell_trend | |
| 117 | + | |
| 118 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 119 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 120 | + | |
| 121 | + dataframe['sell'] = 0 | |
| 122 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp-v3.py +221 −0
| @@ -0,0 +1,221 @@ | ||
| 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 | + inf_timeframe = '1h' | |
| 47 | + stake_currency = 'USD' | |
| 48 | + custom_fiat = 'USD' | |
| 49 | + btc_in_whitelist = False | |
| 50 | + | |
| 51 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 52 | + conditions.append( | |
| 53 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 54 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 55 | + ) | |
| 56 | + | |
| 57 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 58 | + conditions.append( | |
| 59 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 60 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 61 | + ) | |
| 62 | + | |
| 63 | + # Base Timeframe | |
| 64 | + conditions.append( | |
| 65 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 66 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 67 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 68 | + (dataframe['mp'] <= params['base-mp']) | |
| 69 | + ) | |
| 70 | + | |
| 71 | + if stake_currency in ('BTC', 'ETH'): | |
| 72 | + conditions.append( | |
| 73 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 74 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 75 | + ) | |
| 76 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 77 | + else: | |
| 78 | + if btc_in_whitelist == False: | |
| 79 | + conditions.append( | |
| 80 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 81 | + (dataframe[f"BTC_rmi_{inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 82 | + ) | |
| 83 | + | |
| 84 | + conditions.append(dataframe['volume'].gt(0)) | |
| 85 | + | |
| 86 | + if conditions: | |
| 87 | + dataframe.loc[ | |
| 88 | + reduce(lambda x, y: x & y, conditions), | |
| 89 | + 'buy'] = 1 | |
| 90 | + return dataframe | |
| 91 | + | |
| 92 | + return populate_buy_trend | |
| 93 | + | |
| 94 | + @staticmethod | |
| 95 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 96 | + | |
| 97 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 98 | + | |
| 99 | + dataframe['sell'] = 0 | |
| 100 | + return dataframe | |
| 101 | + | |
| 102 | + return populate_sell_trend | |
| 103 | + | |
| 104 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 105 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 106 | + | |
| 107 | + dataframe['sell'] = 0 | |
| 108 | + return dataframe | |
| 109 | + | |
| 110 | + @staticmethod | |
| 111 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 112 | + | |
| 113 | + roi_table = {} | |
| 114 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 115 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 116 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 117 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 118 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 119 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 120 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 121 | + | |
| 122 | + return roi_table | |
| 123 | + | |
| 124 | + @staticmethod | |
| 125 | + def roi_space() -> List[Dimension]: | |
| 126 | + # min / max min / max | |
| 127 | + return [ # 0 : 0.100 / 0.205 | |
| 128 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 129 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 130 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 131 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 132 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 133 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 134 | + | |
| 135 | + Real(0.05, 0.10, name='roi_p6'), | |
| 136 | + Real(0.02, 0.05, name='roi_p5'), | |
| 137 | + Real(0.015, 0.020, name='roi_p4'), | |
| 138 | + Real(0.005, 0.015, name='roi_p3'), | |
| 139 | + Real(0.005, 0.01, name='roi_p2'), | |
| 140 | + Real(0.005, 0.01, name='roi_p1'), | |
| 141 | + ] | |
| 142 | + | |
| 143 | + @staticmethod | |
| 144 | + def stoploss_space() -> List[Dimension]: | |
| 145 | + | |
| 146 | + return [ | |
| 147 | + Real(-0.99, -0.01, name='stoploss'), | |
| 148 | + ] | |
| 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 | + @staticmethod | |
| 154 | + def generate_dynamic_roi(params: Dict) -> Dict[int, float]: | |
| 155 | + | |
| 156 | + dynamic_roi = { | |
| 157 | + 'enabled': params['droi_enabled'], | |
| 158 | + 'profit-factor': params['droi_profit_factor'], | |
| 159 | + 'rmi-start': params['droi_rmi_start'], | |
| 160 | + 'rmi-end': params['droi_rmi_end'], | |
| 161 | + 'grow-delay': params['droi_grow_delay'], | |
| 162 | + 'grow-time': params['droi_grow_time'], | |
| 163 | + 'fallback': params['droi_fallback'], | |
| 164 | + 'min-roc-atr': params['droi_min_roc_atr'] | |
| 165 | + } | |
| 166 | + | |
| 167 | + return dynamic_roi | |
| 168 | + | |
| 169 | + @staticmethod | |
| 170 | + def dynamic_roi_space() -> List[Dimension]: | |
| 171 | + | |
| 172 | + return [ | |
| 173 | + Categorical([True, False], name='droi_enabled'), | |
| 174 | + Integer(200, 500, name='droi_profit_factor'), | |
| 175 | + Integer(0, 50, name='droi_rmi_start'), | |
| 176 | + Integer(50, 90, name='droi_rmi_end'), | |
| 177 | + Integer(0, 180, name='droi_grow_delay'), | |
| 178 | + Integer(360, 1440, name='droi_grow_time'), | |
| 179 | + Categorical(['table', 'atr', 'roc', 'roc-table', 'atr-table'], name='droi_fallback'), | |
| 180 | + Real(0.0, 1.0, name='droi_min_roc_atr') | |
| 181 | + ] | |
| 182 | + | |
| 183 | + | |
| 184 | + @staticmethod | |
| 185 | + def generate_custom_stop(params: Dict) -> Dict[int, float]: | |
| 186 | + | |
| 187 | + custom_stop = { | |
| 188 | + 'decay-time': params['cstp_decay_time'], | |
| 189 | + 'decay-delay': params['cstp_decay_delay'], | |
| 190 | + 'decay-start': params['cstp_decay_start'], | |
| 191 | + 'decay-end': params['cstp_decay_end'], | |
| 192 | + 'cur-min-diff': params['cstp_cur_min_diff'], | |
| 193 | + 'cur-threshold': params['cstp_cur_threshold'], | |
| 194 | + 'roc-bail': params['cstp_roc_bail'], | |
| 195 | + 'rmi-trend': params['cstp_rmi_trend'], | |
| 196 | + 'bail-how': params['cstp_bail_how'], | |
| 197 | + 'pos-trail': params['cstp_pos_trail'], | |
| 198 | + 'pos-threshold': params['cstp_pos_threshold'], | |
| 199 | + 'pos-trail-dist': params['cstp_trail_dist'] | |
| 200 | + } | |
| 201 | + | |
| 202 | + return custom_stop | |
| 203 | + | |
| 204 | + @staticmethod | |
| 205 | + def custom_stoploss_space() -> List[Dimension]: | |
| 206 | + | |
| 207 | + return [ | |
| 208 | + Integer(500, 1440, name='cstp_decay_time'), | |
| 209 | + Integer(0, 360, name='cstp_decay_delay'), | |
| 210 | + Real(-0.30, -0.20, name='cstp_decay_start'), | |
| 211 | + Real(-0.05, 0, name='cstp_decay_end'), | |
| 212 | + Real(0.01, 0.04, name='cstp_cur_min_diff'), | |
| 213 | + Real(-0.05, 0, name='cstp_cur_threshold'), | |
| 214 | + Real(-0.05, 0, name='cstp_roc_bail'), | |
| 215 | + Integer(30, 70, name='cstp_rmi_trend'), | |
| 216 | + Categorical(['atr', 'immediate'], name='cstp_bail_how'), | |
| 217 | + Categorical([True, False], name='cstp_pos_trail'), | |
| 218 | + Real(0.0, 0.03, name='cstp_pos_threshold'), | |
| 219 | + Real(0.005, 0.03, name='cstp_trail_dist') | |
| 220 | + ] | |
| 221 | + """ |
added hyperopts/old/SolipsisMMHyp.py +142 −0
| @@ -0,0 +1,142 @@ | ||
| 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 SolipsisMMHyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + # Base Timeframe | |
| 20 | + Categorical(['up', 'down'], name='base-trend'), | |
| 21 | + Categorical([True, False], name='base-pmax-enable'), | |
| 22 | + Categorical(['up', 'down'], name='base-pmax'), | |
| 23 | + Integer(10, 90, name='base-rmi-slow'), | |
| 24 | + Integer(10, 90, name='base-rmi-fast'), | |
| 25 | + Integer(10, 90, name='base-mp'), | |
| 26 | + Categorical([1.0, 0.786, 0.618, 0.5, 0.382, 0.236, 0.0], name='base-fib-level'), | |
| 27 | + # Informative Timeframe | |
| 28 | + Integer(10, 70, name='inf-rsi'), | |
| 29 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 30 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 31 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 32 | + Categorical([1.0, 0.786, 0.618, 0.5, 0.382, 0.236, 0.0], name='inf-fib-level'), | |
| 33 | + # Exra BTC/ETH Stakes | |
| 34 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 35 | + Integer(10, 70, name='xtra-base-stake-rsi'), | |
| 36 | + Integer(10, 70, name='xtra-base-fiat-rsi') | |
| 37 | + ] | |
| 38 | + | |
| 39 | + @staticmethod | |
| 40 | + def sell_indicator_space() -> List[Dimension]: | |
| 41 | + return [ | |
| 42 | + Real(0.10, 0.90, name='sell-rmi-drop'), | |
| 43 | + Categorical([True, False], name='sell-pmax-enable'), | |
| 44 | + ] | |
| 45 | + | |
| 46 | + @staticmethod | |
| 47 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 48 | + | |
| 49 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 50 | + conditions = [] | |
| 51 | + | |
| 52 | + inf_timeframe = '1h' | |
| 53 | + stake_currency = 'USD' | |
| 54 | + custom_fiat = 'USD' | |
| 55 | + | |
| 56 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 57 | + conditions.append( | |
| 58 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 59 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 60 | + ) | |
| 61 | + | |
| 62 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 63 | + conditions.append( | |
| 64 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 65 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 66 | + ) | |
| 67 | + | |
| 68 | + conditions.append( | |
| 69 | + (dataframe[f"rsi_{inf_timeframe}"] >= params['inf-rsi']) & | |
| 70 | + (dataframe[f"fib-ret_{inf_timeframe}"] >= params['inf-fib-level']) | |
| 71 | + ) | |
| 72 | + | |
| 73 | + if params['base-pmax-enable'] == True: | |
| 74 | + conditions.append((dataframe['pmax-trend'] == params['base-pmax'])) | |
| 75 | + | |
| 76 | + if params['base-trend'] == 'down': | |
| 77 | + conditions.append( | |
| 78 | + (dataframe['fib-ret'] <= params['base-fib-level']) & | |
| 79 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 80 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 81 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 82 | + (dataframe['mp'] <= params['base-mp']) | |
| 83 | + ) | |
| 84 | + | |
| 85 | + elif params['base-trend'] == 'up': | |
| 86 | + conditions.append( | |
| 87 | + (dataframe['fib-ret'] >= params['base-fib-level']) & | |
| 88 | + (dataframe['rmi-up-trend'] == 1) & | |
| 89 | + (dataframe['rmi-slow'] <= params['base-rmi-slow']) & | |
| 90 | + (dataframe['rmi-fast'] >= params['base-rmi-fast']) & | |
| 91 | + (dataframe['mp'] >= params['base-mp']) | |
| 92 | + ) | |
| 93 | + | |
| 94 | + if stake_currency in ('BTC', 'ETH'): | |
| 95 | + conditions.append( | |
| 96 | + (dataframe[f"{stake_currency}_rsi"] < params['xtra-base-stake-rsi']) | | |
| 97 | + (dataframe[f"{custom_fiat}_rsi"] > params['xtra-base-fiat-rsi']) | |
| 98 | + ) | |
| 99 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 100 | + | |
| 101 | + conditions.append(dataframe['buy_signal']) | |
| 102 | + conditions.append(dataframe['volume'].gt(0)) | |
| 103 | + | |
| 104 | + if conditions: | |
| 105 | + dataframe.loc[ | |
| 106 | + reduce(lambda x, y: x & y, conditions), | |
| 107 | + 'buy'] = 1 | |
| 108 | + return dataframe | |
| 109 | + | |
| 110 | + return populate_buy_trend | |
| 111 | + | |
| 112 | + @staticmethod | |
| 113 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 114 | + | |
| 115 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + conditions = [] | |
| 117 | + | |
| 118 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 119 | + conditions.append( | |
| 120 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 121 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 122 | + (dataframe['volume'].gt(0)) | |
| 123 | + ) | |
| 124 | + | |
| 125 | + if params['sell-pmax-enable'] == True: | |
| 126 | + conditions.append((dataframe['pmax-trend'] == 'down')) | |
| 127 | + | |
| 128 | + if conditions: | |
| 129 | + dataframe.loc[ | |
| 130 | + reduce(lambda x, y: x & y, conditions), | |
| 131 | + 'sell'] = 1 | |
| 132 | + | |
| 133 | + # dataframe['sell'] = 0 | |
| 134 | + return dataframe | |
| 135 | + | |
| 136 | + return populate_sell_trend | |
| 137 | + | |
| 138 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 139 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 140 | + | |
| 141 | + dataframe['sell'] = 0 | |
| 142 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/StinkfistHyp.py +106 −0
| @@ -0,0 +1,106 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class StinkfistHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Integer(5, 70, name='mp'), | |
| 25 | + Real(0.70, 0.99, name='inf-pct-adr') | |
| 26 | + ] | |
| 27 | + | |
| 28 | + @staticmethod | |
| 29 | + def sell_indicator_space() -> List[Dimension]: | |
| 30 | + return [] | |
| 31 | + | |
| 32 | + @staticmethod | |
| 33 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 34 | + | |
| 35 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 36 | + | |
| 37 | + inf_timeframe = '1h' | |
| 38 | + conditions = [] | |
| 39 | + | |
| 40 | + # Primary buy triggers | |
| 41 | + conditions.append( | |
| 42 | + # informative timeframe conditions | |
| 43 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{inf_timeframe}"])) & | |
| 44 | + # default timeframe conditions | |
| 45 | + (dataframe['mp'] < params['mp']) & | |
| 46 | + (dataframe['streak-roc'] > dataframe['pcc-lowerband']) & | |
| 47 | + (dataframe['mac'] == 1) | |
| 48 | + ) | |
| 49 | + | |
| 50 | + # Anything below here applies to persisting and new buy signal | |
| 51 | + conditions.append(dataframe['volume'].gt(0)) | |
| 52 | + | |
| 53 | + if conditions: | |
| 54 | + dataframe.loc[ | |
| 55 | + reduce(lambda x, y: x & y, conditions), | |
| 56 | + 'buy'] = 1 | |
| 57 | + return dataframe | |
| 58 | + | |
| 59 | + return populate_buy_trend | |
| 60 | + | |
| 61 | + @staticmethod | |
| 62 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 63 | + | |
| 64 | + roi_table = {} | |
| 65 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 66 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 67 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 68 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 69 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 70 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 71 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 72 | + | |
| 73 | + return roi_table | |
| 74 | + | |
| 75 | + @staticmethod | |
| 76 | + def roi_space() -> List[Dimension]: | |
| 77 | + # min / max min / max | |
| 78 | + return [ # 0 : 0.100 / 0.205 | |
| 79 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 80 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 81 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 82 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 83 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 84 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 85 | + | |
| 86 | + Real(0.05, 0.10, name='roi_p6'), | |
| 87 | + Real(0.02, 0.05, name='roi_p5'), | |
| 88 | + Real(0.015, 0.020, name='roi_p4'), | |
| 89 | + Real(0.005, 0.015, name='roi_p3'), | |
| 90 | + Real(0.005, 0.01, name='roi_p2'), | |
| 91 | + Real(0.005, 0.01, name='roi_p1'), | |
| 92 | + ] | |
| 93 | + | |
| 94 | + @staticmethod | |
| 95 | + def stoploss_space() -> List[Dimension]: | |
| 96 | + | |
| 97 | + return [ | |
| 98 | + Real(-0.99, -0.01, name='stoploss'), | |
| 99 | + ] | |
| 100 | + | |
| 101 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 102 | + """ | |
| 103 | + no sell signal | |
| 104 | + """ | |
| 105 | + dataframe['sell'] = 0 | |
| 106 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/StochRSITEMAHyperopt.py +146 −0
| @@ -0,0 +1,146 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +""" | |
| 20 | +author@: werkkrew | |
| 21 | +github@: https://github.com/werkkrew/freqtrade-strategies | |
| 22 | + | |
| 23 | +Hyperopt for my KAMACCIRSI strategy. | |
| 24 | + | |
| 25 | +Optimizes: | |
| 26 | +- Period for indicators within specified ranges | |
| 27 | +- RSI and Stoch lower band location | |
| 28 | +- TEMA trigger method | |
| 29 | + | |
| 30 | +Default Ranges for dynamic indicator periods: | |
| 31 | + | |
| 32 | +rsiStart = 5 | |
| 33 | +rsiEnd = 30 | |
| 34 | +temaStart = 5 | |
| 35 | +temaEnd = 50 | |
| 36 | + | |
| 37 | +Default ranges for lower bands: | |
| 38 | +RSI: 10-50 | |
| 39 | +Stoch: 10-50 | |
| 40 | + | |
| 41 | +Default Stochasitc Periods: | |
| 42 | +fastkPeriod = 14 | |
| 43 | +slowkPeriod = 3 | |
| 44 | +slowdPeriod = 3 | |
| 45 | +""" | |
| 46 | + | |
| 47 | +# Ranges for dynamic indicator periods | |
| 48 | +rsiStart = 5 | |
| 49 | +rsiEnd = 30 | |
| 50 | +temaStart = 5 | |
| 51 | +temaEnd = 50 | |
| 52 | + | |
| 53 | +# Settings for Stochastic | |
| 54 | +# These do not get optimized | |
| 55 | +fastkPeriod = 14 | |
| 56 | +slowkPeriod = 3 | |
| 57 | +slowdPeriod = 3 | |
| 58 | + | |
| 59 | +class StochRSITEMAHyperopt(IHyperOpt): | |
| 60 | + | |
| 61 | + @staticmethod | |
| 62 | + def indicator_space() -> List[Dimension]: | |
| 63 | + """ | |
| 64 | + Ranges and Options for BUY strategy | |
| 65 | + """ | |
| 66 | + return [ | |
| 67 | + Integer(10, 50, name='stoch-lower-band'), | |
| 68 | + Integer(rsiStart, rsiEnd, name='rsi-period'), | |
| 69 | + Integer(10, 50, name='rsi-lower-band') | |
| 70 | + ] | |
| 71 | + | |
| 72 | + @staticmethod | |
| 73 | + def sell_indicator_space() -> List[Dimension]: | |
| 74 | + """ | |
| 75 | + Ranges and Options for SELL strategy | |
| 76 | + """ | |
| 77 | + return [ | |
| 78 | + Integer(temaStart, temaEnd, name='tema-period'), | |
| 79 | + Categorical(['close', 'both', 'average'], name='tema-trigger') | |
| 80 | + ] | |
| 81 | + | |
| 82 | + @staticmethod | |
| 83 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 84 | + """ | |
| 85 | + Define the buy strategy parameters to be used by Hyperopt. | |
| 86 | + """ | |
| 87 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 88 | + """ | |
| 89 | + Buy strategy Hyperopt will build and use. | |
| 90 | + """ | |
| 91 | + conditions = [] | |
| 92 | + | |
| 93 | + conditions.append( | |
| 94 | + dataframe[f"rsi({params['rsi-period']})"] > params['rsi-lower-band']) | |
| 95 | + conditions.append(qtpylib.crossed_above( | |
| 96 | + dataframe['stoch-slowd'], params['stoch-lower-band'])) | |
| 97 | + conditions.append(qtpylib.crossed_above( | |
| 98 | + dataframe['stoch-slowk'], params['stoch-lower-band'])) | |
| 99 | + conditions.append(qtpylib.crossed_above( | |
| 100 | + dataframe['stoch-slowk'], dataframe['stoch-slowd'])) | |
| 101 | + | |
| 102 | + # Check that the candle had volume | |
| 103 | + conditions.append(dataframe['volume'] > 0) | |
| 104 | + | |
| 105 | + if conditions: | |
| 106 | + dataframe.loc[ | |
| 107 | + reduce(lambda x, y: x & y, conditions), | |
| 108 | + 'buy'] = 1 | |
| 109 | + | |
| 110 | + return dataframe | |
| 111 | + | |
| 112 | + return populate_buy_trend | |
| 113 | + | |
| 114 | + @staticmethod | |
| 115 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 116 | + """ | |
| 117 | + Define the sell strategy parameters to be used by Hyperopt. | |
| 118 | + """ | |
| 119 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 120 | + """ | |
| 121 | + Sell strategy Hyperopt will build and use. | |
| 122 | + """ | |
| 123 | + | |
| 124 | + conditions = [] | |
| 125 | + if params.get('tema-trigger') == 'close': | |
| 126 | + conditions.append( | |
| 127 | + dataframe['close'] < dataframe[f"tema({params['tema-period']})"]) | |
| 128 | + if params.get('tema-trigger') == 'both': | |
| 129 | + conditions.append((dataframe['close'] < dataframe[f"tema({params['tema-period']})"]) & ( | |
| 130 | + dataframe['open'] < dataframe[f"tema({params['tema-period']})"])) | |
| 131 | + if params.get('tema-trigger') == 'average': | |
| 132 | + conditions.append( | |
| 133 | + ((dataframe['close'] + dataframe['open']) / 2) < dataframe[f"tema({params['tema-period']})"]) | |
| 134 | + | |
| 135 | + # Check that the candle had volume | |
| 136 | + conditions.append(dataframe['volume'] > 0) | |
| 137 | + | |
| 138 | + if conditions: | |
| 139 | + dataframe.loc[ | |
| 140 | + reduce(lambda x, y: x & y, conditions), | |
| 141 | + 'sell'] = 1 | |
| 142 | + | |
| 143 | + return dataframe | |
| 144 | + | |
| 145 | + return populate_sell_trend | |
| 146 | + |
added hyperopts/old/SuperHV27Hyp.py +176 −0
| @@ -0,0 +1,176 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class SuperHV27Hyp(IHyperOpt): | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def indicator_space() -> List[Dimension]: | |
| 23 | + return [ | |
| 24 | + Integer(10,50, name='adx1'), | |
| 25 | + Integer(10,50, name='adx2'), | |
| 26 | + Integer(10,50, name='adx3'), | |
| 27 | + Integer(10,50, name='adx4'), | |
| 28 | + Integer(10,50, name='emarsi1'), | |
| 29 | + Integer(10,50, name='emarsi2'), | |
| 30 | + Integer(10,50, name='emarsi3'), | |
| 31 | + Integer(10,50, name='emarsi4'), | |
| 32 | + ] | |
| 33 | + | |
| 34 | + @staticmethod | |
| 35 | + def sell_indicator_space() -> List[Dimension]: | |
| 36 | + return [ | |
| 37 | + Integer(10,50, name='adx2'), | |
| 38 | + Integer(10,50, name='emarsi1'), | |
| 39 | + Integer(10,50, name='emarsi2'), | |
| 40 | + Integer(10,50, name='emarsi3'), | |
| 41 | + ] | |
| 42 | + | |
| 43 | + @staticmethod | |
| 44 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 45 | + | |
| 46 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 47 | + | |
| 48 | + dataframe.loc[ | |
| 49 | + dataframe['slowsma'].gt(0) & | |
| 50 | + dataframe['close'].lt(dataframe['highsma']) & | |
| 51 | + dataframe['close'].lt(dataframe['lowsma']) & | |
| 52 | + dataframe['minusdi'].gt(dataframe['minusdiema']) & | |
| 53 | + dataframe['rsi'].ge(dataframe['rsi'].shift()) & | |
| 54 | + ( | |
| 55 | + ( | |
| 56 | + ~dataframe['preparechangetrend'] & | |
| 57 | + ~dataframe['continueup'] & | |
| 58 | + dataframe['adx'].gt(params['adx1']) & | |
| 59 | + dataframe['bigdown'] & | |
| 60 | + dataframe['emarsi'].le(params['emarsi1']) | |
| 61 | + ) | | |
| 62 | + ( | |
| 63 | + ~dataframe['preparechangetrend'] & | |
| 64 | + dataframe['continueup'] & | |
| 65 | + dataframe['adx'].gt(params['adx2']) & | |
| 66 | + dataframe['bigdown'] & | |
| 67 | + dataframe['emarsi'].le(params['emarsi2']) | |
| 68 | + ) | | |
| 69 | + ( | |
| 70 | + ~dataframe['continueup'] & | |
| 71 | + dataframe['adx'].gt(params['adx3']) & | |
| 72 | + dataframe['bigup'] & | |
| 73 | + dataframe['emarsi'].le(params['emarsi3']) | |
| 74 | + ) | | |
| 75 | + ( | |
| 76 | + dataframe['continueup'] & | |
| 77 | + dataframe['adx'].gt(params['adx4']) & | |
| 78 | + dataframe['bigup'] & | |
| 79 | + dataframe['emarsi'].le(params['emarsi4']) | |
| 80 | + ) | |
| 81 | + ), | |
| 82 | + 'buy'] = 1 | |
| 83 | + | |
| 84 | + return dataframe | |
| 85 | + | |
| 86 | + return populate_buy_trend | |
| 87 | + | |
| 88 | + @staticmethod | |
| 89 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 90 | + | |
| 91 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 92 | + | |
| 93 | + dataframe.loc[ | |
| 94 | + ( | |
| 95 | + ( | |
| 96 | + ~dataframe['preparechangetrendconfirm'] & | |
| 97 | + ~dataframe['continueup'] & | |
| 98 | + (dataframe['close'].gt(dataframe['lowsma']) | dataframe['close'].gt(dataframe['highsma'])) & | |
| 99 | + dataframe['highsma'].gt(0) & | |
| 100 | + dataframe['bigdown'] | |
| 101 | + ) | | |
| 102 | + ( | |
| 103 | + ~dataframe['preparechangetrendconfirm'] & | |
| 104 | + ~dataframe['continueup'] & | |
| 105 | + dataframe['close'].gt(dataframe['highsma']) & | |
| 106 | + dataframe['highsma'].gt(0) & | |
| 107 | + (dataframe['emarsi'].ge(params['emarsi1']) | dataframe['close'].gt(dataframe['slowsma'])) & | |
| 108 | + dataframe['bigdown'] | |
| 109 | + ) | | |
| 110 | + ( | |
| 111 | + ~dataframe['preparechangetrendconfirm'] & | |
| 112 | + dataframe['close'].gt(dataframe['highsma']) & | |
| 113 | + dataframe['highsma'].gt(0) & | |
| 114 | + dataframe['adx'].gt(params['adx2']) & | |
| 115 | + dataframe['emarsi'].ge(params['emarsi2']) & | |
| 116 | + dataframe['bigup'] | |
| 117 | + ) | | |
| 118 | + ( | |
| 119 | + dataframe['preparechangetrendconfirm'] & | |
| 120 | + ~dataframe['continueup'] & | |
| 121 | + dataframe['slowingdown'] & | |
| 122 | + dataframe['emarsi'].ge(params['emarsi3']) & | |
| 123 | + dataframe['slowsma'].gt(0) | |
| 124 | + ) | | |
| 125 | + ( | |
| 126 | + dataframe['preparechangetrendconfirm'] & | |
| 127 | + dataframe['minusdi'].lt(dataframe['plusdi']) & | |
| 128 | + dataframe['close'].gt(dataframe['lowsma']) & | |
| 129 | + dataframe['slowsma'].gt(0) | |
| 130 | + ) | |
| 131 | + ), | |
| 132 | + 'sell'] = 1 | |
| 133 | + | |
| 134 | + return dataframe | |
| 135 | + | |
| 136 | + return populate_sell_trend | |
| 137 | + | |
| 138 | + @staticmethod | |
| 139 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 140 | + | |
| 141 | + roi_table = {} | |
| 142 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 143 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 144 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 145 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 146 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 147 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 148 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 149 | + | |
| 150 | + return roi_table | |
| 151 | + | |
| 152 | + @staticmethod | |
| 153 | + def roi_space() -> List[Dimension]: | |
| 154 | + # min / max min / max | |
| 155 | + return [ # 0 : 0.100 / 0.205 | |
| 156 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 157 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 158 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 159 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 160 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 161 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 162 | + | |
| 163 | + Real(0.05, 0.10, name='roi_p6'), | |
| 164 | + Real(0.02, 0.05, name='roi_p5'), | |
| 165 | + Real(0.015, 0.020, name='roi_p4'), | |
| 166 | + Real(0.005, 0.015, name='roi_p3'), | |
| 167 | + Real(0.005, 0.01, name='roi_p2'), | |
| 168 | + Real(0.005, 0.01, name='roi_p1'), | |
| 169 | + ] | |
| 170 | + | |
| 171 | + @staticmethod | |
| 172 | + def stoploss_space() -> List[Dimension]: | |
| 173 | + | |
| 174 | + return [ | |
| 175 | + Real(-0.99, -0.01, name='stoploss'), | |
| 176 | + ] |
added hyperopts/old/SupertrendHyp.py +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class SupertrendHyp(IHyperOpt): | |
| 20 | + """ | |
| 21 | + Only used in the buy/sell methods when --spaces does not include buy or sell | |
| 22 | + Should put previously best optimized values here so they are used during ROI/stoploss/etc. | |
| 23 | + """ | |
| 24 | + # Buy hyperspace params: | |
| 25 | + buy_params = { | |
| 26 | + 'buy-method': 'both', # sar, supertrend, both | |
| 27 | + 'buy-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 28 | + } | |
| 29 | + | |
| 30 | + # Sell hyperspace params: | |
| 31 | + sell_params = { | |
| 32 | + 'sell-method': 'both', # sar, supertrend, both | |
| 33 | + 'sell-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 34 | + } | |
| 35 | + | |
| 36 | + @staticmethod | |
| 37 | + def indicator_space() -> List[Dimension]: | |
| 38 | + return [ | |
| 39 | + Categorical(['sar','supertrend','both'], name='buy-method'), | |
| 40 | + Categorical(['open','close','hl2','hlc3','ohlc4'], name='buy-price') | |
| 41 | + ] | |
| 42 | + | |
| 43 | + @staticmethod | |
| 44 | + def sell_indicator_space() -> List[Dimension]: | |
| 45 | + return [ | |
| 46 | + Categorical(['sar','supertrend','both'], name='sell-method'), | |
| 47 | + Categorical(['open','close','hl2','hlc3','ohlc4'], name='sell-price') | |
| 48 | + ] | |
| 49 | + | |
| 50 | + @staticmethod | |
| 51 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 52 | + | |
| 53 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 54 | + | |
| 55 | + conditions = [] | |
| 56 | + | |
| 57 | + if params['buy-method'] == 'supertrend' or params['buy-method'] == 'both': | |
| 58 | + conditions.append(dataframe[params['buy-price']] > dataframe['supertrend']) | |
| 59 | + | |
| 60 | + if params['buy-method'] == 'sar' or params['buy-method'] == 'both': | |
| 61 | + conditions.append(dataframe[params['buy-price']] > dataframe['sar']) | |
| 62 | + | |
| 63 | + conditions.append(dataframe['volume'] > 0) | |
| 64 | + | |
| 65 | + if conditions: | |
| 66 | + dataframe.loc[ | |
| 67 | + reduce(lambda x, y: x & y, conditions), | |
| 68 | + 'buy'] = 1 | |
| 69 | + | |
| 70 | + return dataframe | |
| 71 | + | |
| 72 | + return populate_buy_trend | |
| 73 | + | |
| 74 | + @staticmethod | |
| 75 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 76 | + | |
| 77 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 78 | + | |
| 79 | + conditions = [] | |
| 80 | + | |
| 81 | + if params['sell-method'] == 'supertrend' or params['sell-method'] == 'both': | |
| 82 | + conditions.append(dataframe[params['sell-price']] < dataframe['supertrend']) | |
| 83 | + | |
| 84 | + if params['sell-method'] == 'sar' or params['sell-method'] == 'both': | |
| 85 | + conditions.append(dataframe[params['sell-price']] < dataframe['sar']) | |
| 86 | + | |
| 87 | + conditions.append(dataframe['volume'] > 0) | |
| 88 | + | |
| 89 | + if conditions: | |
| 90 | + dataframe.loc[ | |
| 91 | + reduce(lambda x, y: x & y, conditions), | |
| 92 | + 'sell'] = 1 | |
| 93 | + | |
| 94 | + return dataframe | |
| 95 | + | |
| 96 | + return populate_sell_trend | |
| 97 | + | |
| 98 | + | |
| 99 | + @staticmethod | |
| 100 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 101 | + | |
| 102 | + roi_table = {} | |
| 103 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 104 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 105 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 106 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 107 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 108 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 109 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 110 | + | |
| 111 | + return roi_table | |
| 112 | + | |
| 113 | + @staticmethod | |
| 114 | + def roi_space() -> List[Dimension]: | |
| 115 | + | |
| 116 | + return [ | |
| 117 | + Integer(1, 5, name='roi_t6'), | |
| 118 | + Integer(1, 10, name='roi_t5'), | |
| 119 | + Integer(1, 15, name='roi_t4'), | |
| 120 | + Integer(15, 20, name='roi_t3'), | |
| 121 | + Integer(20, 25, name='roi_t2'), | |
| 122 | + Integer(25, 60, name='roi_t1'), | |
| 123 | + | |
| 124 | + Real(0.005, 0.10, name='roi_p6'), | |
| 125 | + Real(0.005, 0.07, name='roi_p5'), | |
| 126 | + Real(0.005, 0.05, name='roi_p4'), | |
| 127 | + Real(0.005, 0.025, name='roi_p3'), | |
| 128 | + Real(0.005, 0.01, name='roi_p2'), | |
| 129 | + Real(0.003, 0.007, name='roi_p1'), | |
| 130 | + ] | |
| 131 | + | |
| 132 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 133 | + params = self.buy_params | |
| 134 | + | |
| 135 | + conditions = [] | |
| 136 | + | |
| 137 | + if params['buy-method'] == 'supertrend' or params['buy-method'] == 'both': | |
| 138 | + conditions.append(dataframe[params['buy-price']] > dataframe['supertrend']) | |
| 139 | + | |
| 140 | + if params['buy-method'] == 'sar' or params['buy-method'] == 'both': | |
| 141 | + conditions.append(dataframe[params['buy-price']] > dataframe['sar']) | |
| 142 | + | |
| 143 | + conditions.append(dataframe['volume'] > 0) | |
| 144 | + | |
| 145 | + if conditions: | |
| 146 | + dataframe.loc[ | |
| 147 | + reduce(lambda x, y: x & y, conditions), | |
| 148 | + 'buy'] = 1 | |
| 149 | + | |
| 150 | + return dataframe | |
| 151 | + | |
| 152 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 153 | + params = self.sell_params | |
| 154 | + | |
| 155 | + conditions = [] | |
| 156 | + | |
| 157 | + if params['sell-method'] == 'supertrend' or params['sell-method'] == 'both': | |
| 158 | + conditions.append(dataframe[params['sell-price']] < dataframe['supertrend']) | |
| 159 | + | |
| 160 | + if params['sell-method'] == 'sar' or params['sell-method'] == 'both': | |
| 161 | + conditions.append(dataframe[params['sell-price']] < dataframe['sar']) | |
| 162 | + | |
| 163 | + conditions.append(dataframe['volume'] > 0) | |
| 164 | + | |
| 165 | + if conditions: | |
| 166 | + dataframe.loc[ | |
| 167 | + reduce(lambda x, y: x & y, conditions), | |
| 168 | + 'sell'] = 1 | |
| 169 | + return dataframe | |
| No newline at the end of the file |
added hyperopts/old/YOLOHyp.py +114 −0
| @@ -0,0 +1,114 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +from typing import Any, Callable, Dict, List | |
| 6 | + | |
| 7 | +import numpy as np # noqa | |
| 8 | +import pandas as pd # noqa | |
| 9 | +from pandas import DataFrame | |
| 10 | +from skopt.space import Categorical, Dimension, Integer, Real # noqa | |
| 11 | + | |
| 12 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 13 | + | |
| 14 | +# -------------------------------- | |
| 15 | +# Add your lib to import here | |
| 16 | +import talib.abstract as ta # noqa | |
| 17 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 18 | + | |
| 19 | +class YOLOHyp(IHyperOpt): | |
| 20 | + | |
| 21 | + buy_params = { | |
| 22 | + 'adx': 34, | |
| 23 | + 'aroon-down': 33, | |
| 24 | + 'aroon-up': 98 | |
| 25 | + } | |
| 26 | + | |
| 27 | + @staticmethod | |
| 28 | + def indicator_space() -> List[Dimension]: | |
| 29 | + return [ | |
| 30 | + Integer(0, 100.0, name='adx'), | |
| 31 | + Integer(0, 100.0, name='aroon-up'), | |
| 32 | + Integer(0, 100.0, name='aroon-down') | |
| 33 | + ] | |
| 34 | + | |
| 35 | + @staticmethod | |
| 36 | + def sell_indicator_space() -> List[Dimension]: | |
| 37 | + return [] | |
| 38 | + | |
| 39 | + @staticmethod | |
| 40 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 41 | + | |
| 42 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 43 | + | |
| 44 | + dataframe.loc[ | |
| 45 | + ( | |
| 46 | + (dataframe['adx'] > params['adx']) & | |
| 47 | + (dataframe['aroon-up'] > params['aroon-up']) & | |
| 48 | + (dataframe['aroon-down'] < params['aroon-down']) & | |
| 49 | + (dataframe['volume'] > 0) | |
| 50 | + ), | |
| 51 | + 'buy' | |
| 52 | + ] = 1 | |
| 53 | + | |
| 54 | + return dataframe | |
| 55 | + | |
| 56 | + return populate_buy_trend | |
| 57 | + | |
| 58 | + @staticmethod | |
| 59 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 60 | + | |
| 61 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 62 | + | |
| 63 | + dataframe['sell'] = 0 | |
| 64 | + return dataframe | |
| 65 | + | |
| 66 | + return populate_sell_trend | |
| 67 | + | |
| 68 | + @staticmethod | |
| 69 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 70 | + | |
| 71 | + roi_table = {} | |
| 72 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 73 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 74 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 75 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 76 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 77 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 78 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 79 | + | |
| 80 | + return roi_table | |
| 81 | + | |
| 82 | + @staticmethod | |
| 83 | + def roi_space() -> List[Dimension]: | |
| 84 | + | |
| 85 | + return [ | |
| 86 | + Integer(1, 15, name='roi_t6'), | |
| 87 | + Integer(1, 45, name='roi_t5'), | |
| 88 | + Integer(1, 90, name='roi_t4'), | |
| 89 | + Integer(45, 120, name='roi_t3'), | |
| 90 | + Integer(45, 180, name='roi_t2'), | |
| 91 | + Integer(90, 200, name='roi_t1'), | |
| 92 | + | |
| 93 | + Real(0.005, 0.10, name='roi_p6'), | |
| 94 | + Real(0.005, 0.07, name='roi_p5'), | |
| 95 | + Real(0.005, 0.05, name='roi_p4'), | |
| 96 | + Real(0.005, 0.025, name='roi_p3'), | |
| 97 | + Real(0.005, 0.01, name='roi_p2'), | |
| 98 | + Real(0.003, 0.007, name='roi_p1'), | |
| 99 | + ] | |
| 100 | + | |
| 101 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 102 | + params = self.buy_params | |
| 103 | + | |
| 104 | + dataframe.loc[ | |
| 105 | + ( | |
| 106 | + (dataframe['adx'] > params['adx']) & | |
| 107 | + (dataframe['aroon-up'] > params['aroon-up']) & | |
| 108 | + (dataframe['aroon-down'] < params['aroon-down']) & | |
| 109 | + (dataframe['volume'] > 0) | |
| 110 | + ), | |
| 111 | + 'buy' | |
| 112 | + ] = 1 | |
| 113 | + | |
| 114 | + return dataframe |
added hyperopts/old/avgprofit_hyperopt_loss.py +32 −0
| @@ -0,0 +1,32 @@ | ||
| 1 | +""" | |
| 2 | +OnlyProfitHyperOptLoss | |
| 3 | + | |
| 4 | +This module defines the alternative HyperOptLoss class which can be used for | |
| 5 | +Hyperoptimization. | |
| 6 | +""" | |
| 7 | +from pandas import DataFrame | |
| 8 | + | |
| 9 | +from freqtrade.optimize.hyperopt import IHyperOptLoss | |
| 10 | + | |
| 11 | +# Optimize around the "average profit" result | |
| 12 | +EXPECTED_AVG_PROFIT = 2.0 | |
| 13 | + | |
| 14 | + | |
| 15 | +class AvgProfitHyperOptLoss(IHyperOptLoss): | |
| 16 | + """ | |
| 17 | + Defines the loss function for hyperopt. | |
| 18 | + | |
| 19 | + This implementation takes only avg profit into account. | |
| 20 | + """ | |
| 21 | + | |
| 22 | + @staticmethod | |
| 23 | + def hyperopt_loss_function(results: DataFrame, trade_count: int, | |
| 24 | + *args, **kwargs) -> float: | |
| 25 | + """ | |
| 26 | + Objective function, returns smaller number for better results. | |
| 27 | + """ | |
| 28 | + | |
| 29 | + profit_mean = results['profit_ratio'].mean() if len(results) > 0 else 0.0, | |
| 30 | + profit_mean_pct = results['profit_ratio'].mean() * 100.0 if len(results) > 0 else 0.0, | |
| 31 | + | |
| 32 | + return 1 - profit_mean_pct / EXPECTED_AVG_PROFIT |
added hyperopts/old/winrate_hyperopt_loss.py +31 −0
| @@ -0,0 +1,31 @@ | ||
| 1 | +from datetime import datetime | |
| 2 | +from math import exp | |
| 3 | + | |
| 4 | +from pandas import DataFrame | |
| 5 | + | |
| 6 | +from freqtrade.optimize.hyperopt import IHyperOptLoss | |
| 7 | + | |
| 8 | + | |
| 9 | +# Define some constants: | |
| 10 | + | |
| 11 | +# set TARGET_RATIO to your desired ratio of winning:losing trades | |
| 12 | +# a value of 10 would look for a win rate of 10:1, e.g. in 100 trades only 10 are losing. | |
| 13 | +TARGET_RATIO = 10 | |
| 14 | + | |
| 15 | +class WinRateHyperOptLoss(IHyperOptLoss): | |
| 16 | + | |
| 17 | + @staticmethod | |
| 18 | + def hyperopt_loss_function(results: DataFrame, trade_count: int, | |
| 19 | + min_date: datetime, max_date: datetime, | |
| 20 | + *args, **kwargs) -> float: | |
| 21 | + """ | |
| 22 | + Objective function, returns smaller number for better results | |
| 23 | + """ | |
| 24 | + | |
| 25 | + wins = len(results[results['profit_abs'] > 0]) | |
| 26 | + drawss = len(results[results['profit_abs'] == 0]) | |
| 27 | + losses = len(results[results['profit_abs'] < 0]) | |
| 28 | + | |
| 29 | + winrate = wins / losses | |
| 30 | + | |
| 31 | + return 1 - winrate / TARGET_RATIO |
added strategies/Solipsis.py +312 −0
| @@ -0,0 +1,312 @@ | ||
| 1 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 2 | +import sys | |
| 3 | +from pathlib import Path | |
| 4 | +sys.path.append(str(Path(__file__).parent)) | |
| 5 | + | |
| 6 | +from Solipsis_v3 import Solipsis3 as Solipsis | |
| 7 | + | |
| 8 | +""" | |
| 9 | +*** THIS IS YOUR LIVE TRADING COPY *** | |
| 10 | +*** THIS IS A CHILD STRATEGY, REQUIRES IMPORT OF PARENT STRATEGY ** | |
| 11 | +*** CURRENTLY MAPS TO PARENT STRATEGY: Solipsis_v3 *** | |
| 12 | + | |
| 13 | +LAST OPTIMIZED: | |
| 14 | + | |
| 15 | +EXCHANGE: Kraken, full pairlists with some personally selected blacklisted coins | |
| 16 | + | |
| 17 | +USD - 03/25/2021 | |
| 18 | +BTC - 03/27/2021 | |
| 19 | +ETH - 03/27/2021 | |
| 20 | + | |
| 21 | +USD - | |
| 22 | + Global: | |
| 23 | + 5m / 1h | |
| 24 | + 20210301- / Sharpe / DROI / CSTP | |
| 25 | + 1038 trades. 929/0/109 Wins/Draws/Losses. Avg profit 0.86%. Total profit 557.30976144 USD ( 889.87Σ%). Avg duration 436.9 min. Objective: -303.93860 | |
| 26 | + | |
| 27 | + Pairlists (Sorted/grouped by avg. profit in global backtests): | |
| 28 | + | |
| 29 | + ('KNC/USD', 'OXT/USD', 'QTUM/USD', 'YFI/USD', 'BAL/USD', 'WAVES/USD', 'FIL/USD', 'ANT/USD', 'REPV1/USD', 'ETC/USD', 'MANA/USD', 'LSK/USD', 'CRV/USD', 'MLN/USD') | |
| 30 | + 143/1000: 1292 trades. 1168/13/111 Wins/Draws/Losses. Avg profit 0.74%. Total profit 586.33656072 USD ( 957.50Σ%). Avg duration 197.1 min. Objective: -402.24916 | |
| 31 | + | |
| 32 | + ('ZEC/USD', 'REP/USD', 'GRT/USD', 'UNI/USD', 'FLOW/USD', 'DASH/USD', 'KEEP/USD', 'AAVE/USD', 'BCH/USD', 'ALGO/USD', 'KAVA/USD', 'BAT/USD', 'KSM/USD', 'ETH/USD', 'SC/USD', 'EOS/USD', 'XMR/USD', 'LTC/USD', 'NANO/USD', 'GNO/USD') | |
| 33 | + 81/704: 1744 trades. 1590/24/130 Wins/Draws/Losses. Avg profit 0.65%. Total profit 735.77585861 USD ( 1136.05Σ%). Avg duration 231.8 min. Objective: -535.37970 | |
| 34 | + | |
| 35 | + ('EWT/USD', 'ADA/USD', 'ATOM/USD', 'XTZ/USD', 'LINK/USD', 'XLM/USD', 'TRX/USD', 'DOT/USD', 'OMG/USD', 'ICX/USD', 'OCEAN/USD', 'COMP/USD', 'STORJ/USD', 'SNX/USD') | |
| 36 | + 213/392: 1292 trades. 1130/4/158 Wins/Draws/Losses. Avg profit 0.46%. Total profit 332.13998403 USD ( 599.07Σ%). Avg duration 135.4 min. Objective: -322.25214 | |
| 37 | + | |
| 38 | + | |
| 39 | +""" | |
| 40 | +# Sub-strategy with parameters specific to USD stake | |
| 41 | +class Solipsis_USD(Solipsis): | |
| 42 | + | |
| 43 | + timeframe = '5m' | |
| 44 | + inf_timeframe = '1h' | |
| 45 | + | |
| 46 | + minimal_roi = { | |
| 47 | + "0": 0.01, | |
| 48 | + "360": 0.005, | |
| 49 | + "720": 0 | |
| 50 | + } | |
| 51 | + | |
| 52 | + # Global for not in custom_pair_params | |
| 53 | + buy_params = { | |
| 54 | + 'base-mp': 61, | |
| 55 | + 'base-rmi-fast': 65, | |
| 56 | + 'base-rmi-slow': 27, | |
| 57 | + 'inf-guard': 'lower', | |
| 58 | + 'inf-pct-adr-bot': 0.14002, | |
| 59 | + 'inf-pct-adr-top': 0.98205, | |
| 60 | + 'xbtc-base-rmi': 56, | |
| 61 | + 'xbtc-inf-rmi': 17, | |
| 62 | + 'xtra-base-fiat-rmi': 45, | |
| 63 | + 'xtra-base-stake-rmi': 69, | |
| 64 | + 'xtra-inf-stake-rmi': 27 | |
| 65 | + } | |
| 66 | + | |
| 67 | + # Global for not in custom_pair_params | |
| 68 | + dynamic_roi = { | |
| 69 | + 'enabled': True, | |
| 70 | + 'profit-factor': 308, | |
| 71 | + 'rmi-start': 48, | |
| 72 | + 'rmi-end': 53, | |
| 73 | + 'grow-delay': 17, | |
| 74 | + 'grow-time': 770, | |
| 75 | + 'fallback': 'table', | |
| 76 | + 'min-roc-atr': 0.0075 | |
| 77 | + } | |
| 78 | + | |
| 79 | + # Global for not in custom_pair_params | |
| 80 | + custom_stop = { | |
| 81 | + 'decay-time': 1058, | |
| 82 | + 'decay-delay': 131, | |
| 83 | + 'decay-start': -0.23, | |
| 84 | + 'decay-end': -0.043, | |
| 85 | + 'cur-min-diff': 0.03, | |
| 86 | + 'cur-threshold': -0.0056, | |
| 87 | + 'roc-bail': -0.01, | |
| 88 | + 'rmi-trend': 50, | |
| 89 | + 'bail-how': 'immediate', | |
| 90 | + 'pos-trail': False, | |
| 91 | + 'pos-threshold': 0.005, | |
| 92 | + 'pos-trail-dist': 0.015 | |
| 93 | + } | |
| 94 | + | |
| 95 | + stoploss = custom_stop['decay-start'] | |
| 96 | + use_custom_stoploss = True | |
| 97 | + | |
| 98 | + custom_pair_params = [ | |
| 99 | + { | |
| 100 | + 'pairs': ('KNC/USD', 'OXT/USD', 'QTUM/USD', 'YFI/USD', 'BAL/USD', 'WAVES/USD', 'FIL/USD', 'ANT/USD', 'REPV1/USD', 'ETC/USD', 'MANA/USD', 'LSK/USD', 'CRV/USD', 'MLN/USD'), | |
| 101 | + 'buy_params': { | |
| 102 | + 'base-mp': 73, | |
| 103 | + 'base-rmi-fast': 53, | |
| 104 | + 'base-rmi-slow': 24, | |
| 105 | + 'inf-guard': 'none', | |
| 106 | + 'inf-pct-adr-bot': 0.02261, | |
| 107 | + 'inf-pct-adr-top': 0.89013, | |
| 108 | + 'xbtc-base-rmi': 63, | |
| 109 | + 'xbtc-inf-rmi': 10, | |
| 110 | + 'xtra-base-fiat-rmi': 42, | |
| 111 | + 'xtra-base-stake-rmi': 36, | |
| 112 | + 'xtra-inf-stake-rmi': 15 | |
| 113 | + }, | |
| 114 | + 'dynamic_roi': { | |
| 115 | + 'enabled': True, | |
| 116 | + 'profit-factor': 372, | |
| 117 | + 'rmi-start': 40, | |
| 118 | + 'rmi-end': 52, | |
| 119 | + 'grow-delay': 23, | |
| 120 | + 'grow-time': 652, | |
| 121 | + 'fallback': 'roc', | |
| 122 | + 'min-roc-atr': 0.005 | |
| 123 | + }, | |
| 124 | + 'custom_stop': { | |
| 125 | + 'decay-time': 1316, | |
| 126 | + 'decay-delay': 103, | |
| 127 | + 'decay-start': -0.28, | |
| 128 | + 'decay-end': -0.004, | |
| 129 | + 'cur-min-diff': 0.022, | |
| 130 | + 'cur-threshold': -0.035, | |
| 131 | + 'roc-bail': -0.045, | |
| 132 | + 'rmi-trend': 35, | |
| 133 | + 'bail-how': 'immediate', | |
| 134 | + 'pos-trail': False, | |
| 135 | + 'pos-threshold': 0.005, | |
| 136 | + 'pos-trail-dist': 0.015 | |
| 137 | + } | |
| 138 | + }, | |
| 139 | + { | |
| 140 | + 'pairs': ('ZEC/USD', 'REP/USD', 'GRT/USD', 'UNI/USD', 'FLOW/USD', 'DASH/USD', 'KEEP/USD', 'AAVE/USD', 'BCH/USD', 'ALGO/USD', 'KAVA/USD', 'BAT/USD', 'KSM/USD', 'ETH/USD', 'SC/USD', 'EOS/USD', 'XMR/USD', 'LTC/USD', 'NANO/USD', 'GNO/USD'), | |
| 141 | + 'buy_params': { | |
| 142 | + 'base-mp': 63, | |
| 143 | + 'base-rmi-fast': 52, | |
| 144 | + 'base-rmi-slow': 22, | |
| 145 | + 'inf-guard': 'lower', | |
| 146 | + 'inf-pct-adr-bot': 0.05986, | |
| 147 | + 'inf-pct-adr-top': 0.76319, | |
| 148 | + 'xbtc-base-rmi': 68, | |
| 149 | + 'xbtc-inf-rmi': 17, | |
| 150 | + 'xtra-base-fiat-rmi': 51, | |
| 151 | + 'xtra-base-stake-rmi': 32, | |
| 152 | + 'xtra-inf-stake-rmi': 16 | |
| 153 | + }, | |
| 154 | + 'dynamic_roi': { | |
| 155 | + 'enabled': True, | |
| 156 | + 'profit-factor': 204, | |
| 157 | + 'rmi-start': 14, | |
| 158 | + 'rmi-end': 75, | |
| 159 | + 'grow-delay': 85, | |
| 160 | + 'grow-time': 630, | |
| 161 | + 'fallback': 'roc', | |
| 162 | + 'min-roc-atr': 0.005 | |
| 163 | + }, | |
| 164 | + 'custom_stop': { | |
| 165 | + 'decay-time': 934, | |
| 166 | + 'decay-delay': 47, | |
| 167 | + 'decay-start': -0.22, | |
| 168 | + 'decay-end': -0.039, | |
| 169 | + 'cur-min-diff': 0.0336, | |
| 170 | + 'cur-threshold': -0.003, | |
| 171 | + 'roc-bail': -0.01, | |
| 172 | + 'rmi-trend': 57, | |
| 173 | + 'bail-how': 'immediate', | |
| 174 | + 'pos-trail': False, | |
| 175 | + 'pos-threshold': 0.005, | |
| 176 | + 'pos-trail-dist': 0.015 | |
| 177 | + } | |
| 178 | + }, | |
| 179 | + { | |
| 180 | + 'pairs': ('EWT/USD', 'ADA/USD', 'ATOM/USD', 'XTZ/USD', 'LINK/USD', 'XLM/USD', 'TRX/USD', 'DOT/USD', 'OMG/USD', 'ICX/USD', 'OCEAN/USD', 'COMP/USD', 'STORJ/USD', 'SNX/USD'), | |
| 181 | + 'buy_params': { | |
| 182 | + 'base-mp': 64, | |
| 183 | + 'base-rmi-fast': 48, | |
| 184 | + 'base-rmi-slow': 20, | |
| 185 | + 'inf-guard': 'upper', | |
| 186 | + 'inf-pct-adr-bot': 0.10287, | |
| 187 | + 'inf-pct-adr-top': 0.83482, | |
| 188 | + 'xbtc-base-rmi': 70, | |
| 189 | + 'xbtc-inf-rmi': 17, | |
| 190 | + 'xtra-base-fiat-rmi': 47, | |
| 191 | + 'xtra-base-stake-rmi': 18, | |
| 192 | + 'xtra-inf-stake-rmi': 17 | |
| 193 | + }, | |
| 194 | + 'dynamic_roi': { | |
| 195 | + 'enabled': True, | |
| 196 | + 'profit-factor': 272, | |
| 197 | + 'rmi-start': 44, | |
| 198 | + 'rmi-end': 84, | |
| 199 | + 'grow-delay': 116, | |
| 200 | + 'grow-time': 877, | |
| 201 | + 'fallback': 'roc', | |
| 202 | + 'min-roc-atr': 0.005 | |
| 203 | + }, | |
| 204 | + 'custom_stop': { | |
| 205 | + 'decay-time': 1081, | |
| 206 | + 'decay-delay': 27, | |
| 207 | + 'decay-start': -0.26, | |
| 208 | + 'decay-end': -0.035, | |
| 209 | + 'cur-min-diff': 0.016, | |
| 210 | + 'cur-threshold': -0.0358, | |
| 211 | + 'roc-bail': -0.032, | |
| 212 | + 'rmi-trend': 52, | |
| 213 | + 'bail-how': 'atr', | |
| 214 | + 'pos-trail': False, | |
| 215 | + 'pos-threshold': 0.005, | |
| 216 | + 'pos-trail-dist': 0.015 | |
| 217 | + } | |
| 218 | + } | |
| 219 | + ] | |
| 220 | + | |
| 221 | +""" | |
| 222 | +BTC - | |
| 223 | + Global: | |
| 224 | + 15m / 4h | |
| 225 | + 20210301- / Sharpe / DROI / CSTP | |
| 226 | + 594/1000: 1254 trades. 1023/1/230 Wins/Draws/Losses. Avg profit 0.43%. Median profit 1.00%. Total profit 0.00605866 BTC ( 537.60Σ%). Avg duration 168.1 min. Objective: -338.21036 | |
| 227 | + | |
| 228 | + Pairlists (Sorted/grouped by avg. profit in global backtests): | |
| 229 | + | |
| 230 | +""" | |
| 231 | +# Sub-strategy with parameters specific to BTC stake | |
| 232 | +class Solipsis_BTC(Solipsis): | |
| 233 | + | |
| 234 | + timeframe = '15m' | |
| 235 | + inf_timeframe = '4h' | |
| 236 | + | |
| 237 | + minimal_roi = { | |
| 238 | + "0": 0.01, | |
| 239 | + "720": 0.005, | |
| 240 | + "1440": 0 | |
| 241 | + } | |
| 242 | + | |
| 243 | + # Global for not in custom_pair_params | |
| 244 | + buy_params = { | |
| 245 | + 'base-mp': 36, | |
| 246 | + 'base-rmi-fast': 45, | |
| 247 | + 'base-rmi-slow': 36, | |
| 248 | + 'inf-guard': 'none', | |
| 249 | + 'inf-pct-adr-bot': 0.08671, | |
| 250 | + 'inf-pct-adr-top': 0.95097, | |
| 251 | + 'xbtc-base-rmi': 55, | |
| 252 | + 'xbtc-inf-rmi': 20, | |
| 253 | + 'xtra-base-fiat-rmi': 22, | |
| 254 | + 'xtra-base-stake-rmi': 62, | |
| 255 | + 'xtra-inf-stake-rmi': 68 | |
| 256 | + } | |
| 257 | + | |
| 258 | + # Global for not in custom_pair_params | |
| 259 | + dynamic_roi = { | |
| 260 | + 'enabled': True, | |
| 261 | + 'profit-factor': 400, | |
| 262 | + 'rmi-start': 11, | |
| 263 | + 'rmi-end': 72, | |
| 264 | + 'grow-delay': 137, | |
| 265 | + 'grow-time': 371, | |
| 266 | + 'fallback': 'roc', | |
| 267 | + 'min-roc-atr': 0.0025 | |
| 268 | + } | |
| 269 | + | |
| 270 | + # Global for not in custom_pair_params | |
| 271 | + custom_stop = { | |
| 272 | + 'decay-time': 761, | |
| 273 | + 'decay-delay': 122, | |
| 274 | + 'decay-start': -0.23, | |
| 275 | + 'decay-end': -0.001, | |
| 276 | + 'cur-min-diff': 0.013, | |
| 277 | + 'cur-threshold': -0.027, | |
| 278 | + 'roc-bail': -0.01068, | |
| 279 | + 'rmi-trend': 36, | |
| 280 | + 'bail-how': 'immediate', | |
| 281 | + 'pos-trail': True, | |
| 282 | + 'pos-threshold': 0.003, | |
| 283 | + 'pos-trail-dist': 0.016 | |
| 284 | + } | |
| 285 | + | |
| 286 | + stoploss = custom_stop['decay-start'] | |
| 287 | + use_custom_stoploss = True | |
| 288 | + | |
| 289 | + custom_pair_params = [] | |
| 290 | + | |
| 291 | +""" | |
| 292 | +ETH - | |
| 293 | + Global: | |
| 294 | + 15m / 4h | |
| 295 | + 20210301- / Sharpe / DROI / CSTP | |
| 296 | + | |
| 297 | + | |
| 298 | + Pairlists (Sorted/grouped by avg. profit in global backtests): | |
| 299 | + | |
| 300 | +""" | |
| 301 | +# Sub-strategy with parameters specific to ETH stake | |
| 302 | +class Solipsis_ETH(Solipsis): | |
| 303 | + | |
| 304 | + timeframe = '15m' | |
| 305 | + inf_timeframe = '4h' | |
| 306 | + | |
| 307 | + | |
| 308 | + | |
| 309 | + stoploss = custom_stop['decay-start'] | |
| 310 | + use_custom_stoploss = True | |
| 311 | + | |
| 312 | + custom_pair_params = [] | |
| No newline at the end of the file |
added strategies/Solipsis_v3.py +602 −0
| @@ -0,0 +1,602 @@ | ||
| 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 | |
| 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 and @JimmyNixx | |
| 28 | +This strategy is an evolution of our previous framework "Schism" which we are happy to share by request. While Schism has been superceded by this | |
| 29 | +strategy there may still be valuable examples and ideas in it. | |
| 30 | + | |
| 31 | +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 | |
| 32 | +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. | |
| 33 | + | |
| 34 | +We take no responsibility for any success or failure you have using this strategy. | |
| 35 | + | |
| 36 | +Apes together strong. | |
| 37 | + | |
| 38 | + | |
| 39 | +************* | |
| 40 | +This is a very advanced strategy. It requires a lot of configuration, optimization, and understanding of how it works and what it does before use. | |
| 41 | +It **will not** work at all for you "out of the box". If you download it and run an immediate backtest the odds are the results will be awful. | |
| 42 | + | |
| 43 | +Please review the code, understand it, and attempt to do as much due diligence as you can before asking questions about it. | |
| 44 | +************* | |
| 45 | + | |
| 46 | +FEATURES: | |
| 47 | + - Dynamic ROI | |
| 48 | + - Several options, initial idea was to ride trends past ROI in a similar way to trailing stoploss but using indicators. | |
| 49 | + - Fallback choices includes table, roc, atr, and others. Has the ability to set ROI table values dynamically based on indicator math. | |
| 50 | + - Custom Stoploss | |
| 51 | + - Generally a vanilla implementation of Freqtrade custom stoploss but tries to do some clever things. Uses indicator data. (Thanks @JoeSchr!) | |
| 52 | + - Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 53 | + - If BTC/STAKE is not in whitelist, make sure to use that for an informative. | |
| 54 | + - If your stake is BTC or ETH, use COIN/FIAT and BTC/FIAT as informatives. | |
| 55 | + - 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. | |
| 56 | + - Custom indicator file to keep primary strategy clean(ish). | |
| 57 | + - 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 | |
| 58 | + for some customization without having to edit those files directly. | |
| 59 | + - Child strategy for stake specific settings and different settings for different instances, hoping to keep this strategy file relatively | |
| 60 | + clutter-free from the extensive options especially when using per-pair settings. | |
| 61 | + | |
| 62 | +STRATEGY NOTES: | |
| 63 | + - If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) is *highly recommended* that you remove BTC/STAKE | |
| 64 | + from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC | |
| 65 | + itself. | |
| 66 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 67 | + "--enable-protections" as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 68 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 69 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 70 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 71 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only and at least 1000 total epochs several times. There are | |
| 72 | + a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 73 | + - It is possible to hyperopt the custom stoploss and dynamic ROI settings, however a change to the freqtrade code is needed. I have done | |
| 74 | + 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. | |
| 75 | + (github.com/werkkrew/freqtrade branch: hyperopt) | |
| 76 | + - Hyperopt Notes: | |
| 77 | + - Hyperopting buy/custom-stoploss/dynamic-roi together takes a LOT of repeat 1000 epoch runs to get optimal results. There | |
| 78 | + are a ton of variables moving around and often times the reported best epoch is not desirable. | |
| 79 | + - Avoid hyperopt results with small avg. profit and avg. duration of < 60m (in my opinion.) | |
| 80 | + - I find the best results come from SharpeHyperOptLoss | |
| 81 | + - 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. | |
| 82 | + - It is *recommended* to leave this file untouched and do your configuration / optimizations from the child strategy Solipsis.py. | |
| 83 | + | |
| 84 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 85 | + | |
| 86 | + custom_pair_params = [ | |
| 87 | + { | |
| 88 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 89 | + 'buy_params': {}, | |
| 90 | + 'sell_params': {}, | |
| 91 | + 'minimal_roi': {} | |
| 92 | + } | |
| 93 | + ] | |
| 94 | + | |
| 95 | +TODO: | |
| 96 | + - Continue to hunt for a better all around buy signal. | |
| 97 | + - Tweak ROI Trend Ride | |
| 98 | + - Verify ROI trend ride correctly reports profit during backtest. | |
| 99 | + - Further enchance and optimize custom stop loss | |
| 100 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 101 | + - Develop a PR to fully support trades database in backtest so we can go back to previous Schism methodology for buy/sell | |
| 102 | + rather than hacking the crap out of the ROI methods? | |
| 103 | + - Develop a PR to fully support hyperopting the custom_stoploss and dynamic_roi spaces? | |
| 104 | +""" | |
| 105 | + | |
| 106 | +class Solipsis3(IStrategy): | |
| 107 | + | |
| 108 | + # Recommended for USD/USDT/etc. | |
| 109 | + timeframe = '5m' | |
| 110 | + inf_timeframe = '1h' | |
| 111 | + | |
| 112 | + buy_params = { | |
| 113 | + 'base-mp': 30, | |
| 114 | + 'base-rmi-fast': 50, | |
| 115 | + 'base-rmi-slow': 30, | |
| 116 | + 'inf-guard': 'upper', | |
| 117 | + 'inf-pct-adr-bot': 0.10, | |
| 118 | + 'inf-pct-adr-top': 0.85, | |
| 119 | + 'xbtc-base-rmi': 50, | |
| 120 | + 'xbtc-inf-rmi': 20, | |
| 121 | + 'xtra-base-fiat-rmi': 45, | |
| 122 | + 'xtra-base-stake-rmi': 69, | |
| 123 | + 'xtra-inf-stake-rmi': 27 | |
| 124 | + } | |
| 125 | + | |
| 126 | + sell_params = {} | |
| 127 | + | |
| 128 | + # Custom buy/sell parameters per pair | |
| 129 | + custom_pair_params = [] | |
| 130 | + | |
| 131 | + # Recommended on 5m timeframe | |
| 132 | + minimal_roi = { | |
| 133 | + "0": 0.01, | |
| 134 | + "360": 0.005, | |
| 135 | + "720": 0 | |
| 136 | + } | |
| 137 | + | |
| 138 | + dynamic_roi = { | |
| 139 | + 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 140 | + 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 141 | + 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 142 | + 'rmi-end': 70, # ending value | |
| 143 | + 'grow-delay': 0, # delay on growth | |
| 144 | + 'grow-time': 720, # finish time of growth | |
| 145 | + 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 146 | + 'min-roc-atr': 0.0075 # minimum roi value to return in roc or atr mode | |
| 147 | + } | |
| 148 | + | |
| 149 | + use_custom_stoploss = True | |
| 150 | + custom_stop = { | |
| 151 | + # Linear Decay Parameters | |
| 152 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 153 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 154 | + 'decay-start': -0.30, # starting value: should be the same or smaller than initial stoploss | |
| 155 | + 'decay-end': -0.03, # ending value | |
| 156 | + # Profit and TA | |
| 157 | + 'cur-min-diff': 0.03, # diff between current and minimum profit to move stoploss up to min profit point | |
| 158 | + 'cur-threshold': -0.02, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 159 | + 'roc-bail': -0.03, # value for roc to use for dynamic bailout | |
| 160 | + 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 161 | + 'bail-how': 'immediate', # set the stoploss to the atr offset below current price, or immediate | |
| 162 | + # Positive Trailing | |
| 163 | + 'pos-trail': False, # enable trailing once positive | |
| 164 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 165 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 166 | + } | |
| 167 | + | |
| 168 | + stoploss = custom_stop['decay-start'] | |
| 169 | + | |
| 170 | + # Recommended | |
| 171 | + use_sell_signal = False | |
| 172 | + sell_profit_only = False | |
| 173 | + ignore_roi_if_buy_signal = False | |
| 174 | + | |
| 175 | + # Required | |
| 176 | + startup_candle_count: int = 72 | |
| 177 | + process_only_new_candles = False | |
| 178 | + | |
| 179 | + # Strategy Specific Variable Storage | |
| 180 | + custom_trade_info = {} | |
| 181 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 182 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 183 | + | |
| 184 | + """ | |
| 185 | + Informative Pair Definitions | |
| 186 | + """ | |
| 187 | + def informative_pairs(self): | |
| 188 | + # add all whitelisted pairs on informative timeframe | |
| 189 | + pairs = self.dp.current_whitelist() | |
| 190 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 191 | + | |
| 192 | + # add extra informative pairs if the stake is BTC or ETH | |
| 193 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 194 | + for pair in pairs: | |
| 195 | + coin, stake = pair.split('/') | |
| 196 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 197 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 198 | + | |
| 199 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 200 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 201 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 202 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 203 | + else: | |
| 204 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 205 | + if not btc_stake in pairs: | |
| 206 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 207 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 208 | + | |
| 209 | + return informative_pairs | |
| 210 | + | |
| 211 | + """ | |
| 212 | + Indicator Definitions | |
| 213 | + """ | |
| 214 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 215 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 216 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 217 | + | |
| 218 | + # Base timeframe indicators | |
| 219 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 220 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 221 | + | |
| 222 | + # Indicators for ROI and Custom Stoploss | |
| 223 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 224 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 225 | + | |
| 226 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 227 | + dataframe['roc-mp'] = ta.ROC(dataframe, timeperiod=6) | |
| 228 | + dataframe['mp'] = ta.RSI(dataframe['roc-mp'], timeperiod=6) | |
| 229 | + | |
| 230 | + # Trends, Peaks and Crosses | |
| 231 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 232 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 233 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 234 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 235 | + | |
| 236 | + # Base pair informative timeframe indicators | |
| 237 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 238 | + | |
| 239 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 240 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 241 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 242 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 243 | + | |
| 244 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 245 | + | |
| 246 | + # Other stake specific informative indicators | |
| 247 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 248 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 249 | + coin, stake = metadata['pair'].split('/') | |
| 250 | + fiat = self.custom_fiat | |
| 251 | + coin_fiat = f"{coin}/{fiat}" | |
| 252 | + stake_fiat = f"{stake}/{fiat}" | |
| 253 | + | |
| 254 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 255 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 256 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 257 | + | |
| 258 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 259 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 260 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 261 | + | |
| 262 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 263 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 264 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 265 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 266 | + | |
| 267 | + # Informatives for BTC/STAKE if not in whitelist | |
| 268 | + else: | |
| 269 | + pairs = self.dp.current_whitelist() | |
| 270 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 271 | + if not btc_stake in pairs: | |
| 272 | + # BTC/STAKE - Base Timeframe | |
| 273 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 274 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 275 | + | |
| 276 | + # BTC/STAKE - Informative Timeframe | |
| 277 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 278 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 279 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 280 | + | |
| 281 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 282 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 283 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 284 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 285 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 286 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 287 | + | |
| 288 | + return dataframe | |
| 289 | + | |
| 290 | + """ | |
| 291 | + Buy Signal | |
| 292 | + """ | |
| 293 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 294 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 295 | + conditions = [] | |
| 296 | + | |
| 297 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 298 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 299 | + conditions.append( | |
| 300 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 301 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 302 | + ) | |
| 303 | + | |
| 304 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 305 | + conditions.append( | |
| 306 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 307 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 308 | + ) | |
| 309 | + | |
| 310 | + # Base Timeframe | |
| 311 | + conditions.append( | |
| 312 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 313 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 314 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 315 | + (dataframe['mp'] <= params['base-mp']) | |
| 316 | + ) | |
| 317 | + | |
| 318 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 319 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 320 | + conditions.append( | |
| 321 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 322 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 323 | + ) | |
| 324 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 325 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 326 | + else: | |
| 327 | + pairs = self.dp.current_whitelist() | |
| 328 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 329 | + if not btc_stake in pairs: | |
| 330 | + conditions.append( | |
| 331 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 332 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 333 | + ) | |
| 334 | + | |
| 335 | + conditions.append(dataframe['volume'].gt(0)) | |
| 336 | + | |
| 337 | + if conditions: | |
| 338 | + dataframe.loc[ | |
| 339 | + reduce(lambda x, y: x & y, conditions), | |
| 340 | + 'buy'] = 1 | |
| 341 | + | |
| 342 | + return dataframe | |
| 343 | + | |
| 344 | + """ | |
| 345 | + Sell Signal | |
| 346 | + """ | |
| 347 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 348 | + # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 349 | + | |
| 350 | + dataframe['sell'] = 0 | |
| 351 | + | |
| 352 | + return dataframe | |
| 353 | + | |
| 354 | + """ | |
| 355 | + Custom Stoploss | |
| 356 | + """ | |
| 357 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 358 | + params = self.get_pair_params(pair, 'custom_stop') | |
| 359 | + | |
| 360 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 361 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 362 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 363 | + profit_diff = current_profit - min_profit | |
| 364 | + | |
| 365 | + decay_stoploss = cta.linear_growth(params['decay-start'], params['decay-end'], params['decay-delay'], params['decay-time'], trade_dur) | |
| 366 | + | |
| 367 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 368 | + if params['pos-trail'] == True: | |
| 369 | + if current_profit > params['pos-threshold']: | |
| 370 | + return current_profit - params['pos-trail-dist'] | |
| 371 | + | |
| 372 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 373 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 374 | + roc = dataframe['roc'].iat[-1] | |
| 375 | + atr = dataframe['atr'].iat[-1] | |
| 376 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 377 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 378 | + else: | |
| 379 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 380 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 381 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 382 | + | |
| 383 | + if current_profit < params['cur-threshold']: | |
| 384 | + # Dynamic bailout based on rate of change | |
| 385 | + if (roc/100) <= params['roc-bail']: | |
| 386 | + if params['bail-how'] == 'atr': | |
| 387 | + return ((current_rate - atr)/current_rate) - 1 | |
| 388 | + elif params['bail-how'] == 'immediate': | |
| 389 | + return current_rate | |
| 390 | + else: | |
| 391 | + return decay_stoploss | |
| 392 | + | |
| 393 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 394 | + if (current_profit > min_profit) or roc > 0 or rmi_slow >= params['rmi-trend']: | |
| 395 | + if profit_diff > params['cur-min-diff']: | |
| 396 | + return min_profit | |
| 397 | + return -1 | |
| 398 | + | |
| 399 | + return decay_stoploss | |
| 400 | + | |
| 401 | + """ | |
| 402 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 403 | + """ | |
| 404 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 405 | + | |
| 406 | + dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 407 | + minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 408 | + | |
| 409 | + if not dynamic_roi or not minimal_roi: | |
| 410 | + return None, None | |
| 411 | + | |
| 412 | + _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 413 | + | |
| 414 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 415 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 416 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 417 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 418 | + roc = dataframe['roc'].iat[-1] | |
| 419 | + atr = dataframe['atr'].iat[-1] | |
| 420 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 421 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 422 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 423 | + else: | |
| 424 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 425 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 426 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 427 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 428 | + | |
| 429 | + d = dynamic_roi | |
| 430 | + open_rate = trade.open_rate | |
| 431 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 432 | + | |
| 433 | + atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 434 | + roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 435 | + | |
| 436 | + # atr as the fallback (if > min-roc-atr) | |
| 437 | + if d['fallback'] == 'atr': | |
| 438 | + min_roi = atr_roi | |
| 439 | + # roc as the fallback (if > min-roc-atr) | |
| 440 | + elif d['fallback'] == 'roc': | |
| 441 | + min_roi = roc_roi | |
| 442 | + # atr or table as the fallback (whichever is larger) | |
| 443 | + elif d['fallback'] == 'atr-table': | |
| 444 | + min_roi = max(table_roi, atr_roi) | |
| 445 | + # roc or table as the fallback (whichever is larger) | |
| 446 | + elif d['fallback'] == 'roc-table': | |
| 447 | + min_roi = max(table_roi, roc_roi) | |
| 448 | + # default to table | |
| 449 | + else: | |
| 450 | + min_roi = table_roi | |
| 451 | + | |
| 452 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 453 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 454 | + pullback_buffer = (max_profit * profit_factor) | |
| 455 | + | |
| 456 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 457 | + if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 458 | + if (current_profit < pullback_buffer) and max_profit > min_roi: | |
| 459 | + # allow immediate bailout if we were above the ROI point and retreated below it | |
| 460 | + min_roi = current_profit / 2 | |
| 461 | + else: | |
| 462 | + min_roi = 100 | |
| 463 | + | |
| 464 | + else: | |
| 465 | + min_roi = table_roi | |
| 466 | + | |
| 467 | + return trade_dur, min_roi | |
| 468 | + | |
| 469 | + # Minor change to the usual method here to allow feeding the pair for per-pair settings | |
| 470 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 471 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 472 | + | |
| 473 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 474 | + if not roi_list: | |
| 475 | + return None, None | |
| 476 | + roi_entry = max(roi_list) | |
| 477 | + min_roi = minimal_roi[roi_entry] | |
| 478 | + | |
| 479 | + return roi_entry, min_roi | |
| 480 | + | |
| 481 | + # Change here to allow loading of the dynamic_roi settings | |
| 482 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 483 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 484 | + | |
| 485 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 486 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 487 | + else: | |
| 488 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 489 | + if roi is None: | |
| 490 | + return False | |
| 491 | + else: | |
| 492 | + return current_profit > roi | |
| 493 | + | |
| 494 | + """ | |
| 495 | + Trade Timeout Overloads | |
| 496 | + """ | |
| 497 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 498 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 499 | + ob = self.dp.orderbook(pair, 1) | |
| 500 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 501 | + if current_price > order['price'] * 1.01: | |
| 502 | + return True | |
| 503 | + return False | |
| 504 | + | |
| 505 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 506 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 507 | + ob = self.dp.orderbook(pair, 1) | |
| 508 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 509 | + if current_price < order['price'] * 0.99: | |
| 510 | + return True | |
| 511 | + return False | |
| 512 | + | |
| 513 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 514 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 515 | + ob = self.dp.orderbook(pair, 1) | |
| 516 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 517 | + if current_price > rate * 1.01: | |
| 518 | + return False | |
| 519 | + return True | |
| 520 | + | |
| 521 | + """ | |
| 522 | + Custom Methods | |
| 523 | + """ | |
| 524 | + # Get parameters for various settings on a per pair or group of pairs basis | |
| 525 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 526 | + buy_params = self.buy_params | |
| 527 | + sell_params = self.sell_params | |
| 528 | + minimal_roi = self.minimal_roi | |
| 529 | + custom_stop = self.custom_stop | |
| 530 | + dynamic_roi = self.dynamic_roi | |
| 531 | + | |
| 532 | + if self.custom_pair_params: | |
| 533 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 534 | + if custom_params['buy_params']: | |
| 535 | + buy_params = custom_params['buy_params'] | |
| 536 | + if custom_params['sell_params']: | |
| 537 | + sell_params = custom_params['sell_params'] | |
| 538 | + if custom_params['minimal_roi']: | |
| 539 | + custom_stop = custom_params['minimal_roi'] | |
| 540 | + if custom_params['custom_stop']: | |
| 541 | + custom_stop = custom_params['custom_stop'] | |
| 542 | + if custom_params['dynamic_roi']: | |
| 543 | + dynamic_roi = custom_params['dynamic_roi'] | |
| 544 | + | |
| 545 | + if params == 'buy': | |
| 546 | + return buy_params | |
| 547 | + if params == 'sell': | |
| 548 | + return sell_params | |
| 549 | + if params == 'minimal_roi': | |
| 550 | + return minimal_roi | |
| 551 | + if params == 'custom_stop': | |
| 552 | + return custom_stop | |
| 553 | + if params == 'dynamic_roi': | |
| 554 | + return dynamic_roi | |
| 555 | + | |
| 556 | + return False | |
| 557 | + | |
| 558 | + # Get the current price from the exchange (or local cache) | |
| 559 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 560 | + if not refresh: | |
| 561 | + rate = self.custom_current_price_cache.get(pair) | |
| 562 | + # Check if cache has been invalidated | |
| 563 | + if rate: | |
| 564 | + return rate | |
| 565 | + | |
| 566 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 567 | + if ask_strategy.get('use_order_book', False): | |
| 568 | + ob = self.dp.orderbook(pair, 1) | |
| 569 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 570 | + else: | |
| 571 | + ticker = self.dp.ticker(pair) | |
| 572 | + rate = ticker['last'] | |
| 573 | + | |
| 574 | + self.custom_current_price_cache[pair] = rate | |
| 575 | + return rate | |
| 576 | + | |
| 577 | + """ | |
| 578 | + Stripped down version from Schism, meant only to update the price data a bit | |
| 579 | + more frequently than the default instead of getting all sorts of trade information | |
| 580 | + """ | |
| 581 | + def populate_trades(self, pair: str) -> dict: | |
| 582 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 583 | + if not pair in self.custom_trade_info: | |
| 584 | + self.custom_trade_info[pair] = {} | |
| 585 | + | |
| 586 | + # init the temp dicts and set the trade stuff to false | |
| 587 | + trade_data = {} | |
| 588 | + trade_data['active_trade'] = False | |
| 589 | + | |
| 590 | + # active trade stuff only works in live and dry, not backtest | |
| 591 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 592 | + | |
| 593 | + # find out if we have an open trade for this pair | |
| 594 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 595 | + | |
| 596 | + # if so, get some information | |
| 597 | + if active_trade: | |
| 598 | + # get current price and update the min/max rate | |
| 599 | + current_rate = self.get_current_price(pair, True) | |
| 600 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 601 | + | |
| 602 | + return trade_data | |
| No newline at the end of the file |
added strategies/custom_indicators.py +323 −0
| @@ -0,0 +1,323 @@ | ||
| 1 | +""" | |
| 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 | +""" | |
| 7 | +import numpy as np | |
| 8 | +import talib.abstract as ta | |
| 9 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 10 | + | |
| 11 | +from pandas import DataFrame, Series | |
| 12 | + | |
| 13 | + | |
| 14 | +""" | |
| 15 | +Misc. Helper Functions | |
| 16 | +""" | |
| 17 | +def same_length(bigger, shorter): | |
| 18 | + return np.concatenate((np.full((bigger.shape[0] - shorter.shape[0]), np.nan), shorter)) | |
| 19 | + | |
| 20 | + | |
| 21 | +""" | |
| 22 | +Maths | |
| 23 | +""" | |
| 24 | +def linear_growth(start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 25 | + """ | |
| 26 | + Simple linear growth function. Grows from start to end after end_time minutes (starts after start_time minutes) | |
| 27 | + """ | |
| 28 | + time = max(0, trade_time - start_time) | |
| 29 | + rate = (end - start) / (end_time - start_time) | |
| 30 | + | |
| 31 | + return min(end, start + (rate * time)) | |
| 32 | + | |
| 33 | +""" | |
| 34 | +TA Indicators | |
| 35 | +""" | |
| 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 | + | |
| 107 | +def zema(dataframe, period, field='close'): | |
| 108 | + """ | |
| 109 | + Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/overlap_studies.py#L79 | |
| 110 | + Modified slightly to use ta.EMA instead of technical ema | |
| 111 | + """ | |
| 112 | + df = dataframe.copy() | |
| 113 | + | |
| 114 | + df['ema1'] = ta.EMA(df[field], timeperiod=period) | |
| 115 | + df['ema2'] = ta.EMA(df['ema1'], timeperiod=period) | |
| 116 | + df['d'] = df['ema1'] - df['ema2'] | |
| 117 | + df['zema'] = df['ema1'] + df['d'] | |
| 118 | + | |
| 119 | + return df['zema'] | |
| 120 | + | |
| 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: | |
| 215 | + """ | |
| 216 | + Moving Average Cross | |
| 217 | + Port of: https://www.tradingview.com/script/PcWAuplI-Moving-Average-Cross/ | |
| 218 | + """ | |
| 219 | + df = dataframe.copy() | |
| 220 | + | |
| 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) | |
| 232 | + | |
| 233 | + dir_1 = np.where(crosses_lf_us, 1, np.nan) | |
| 234 | + dir_2 = np.where(crosses_uf_ls, -1, np.nan) | |
| 235 | + | |
| 236 | + dir = np.where(dir_1 == 1, dir_1, np.nan) | |
| 237 | + dir = np.where(dir_2 == -1, dir_2, dir_1) | |
| 238 | + | |
| 239 | + res = Series(dir).fillna(method='ffill').to_numpy() | |
| 240 | + | |
| 241 | + return res | |
| 242 | + | |
| 243 | +def mastreak(dataframe: DataFrame, period: int = 4, field='close') -> Series: | |
| 244 | + """ | |
| 245 | + MA Streak | |
| 246 | + Port of: https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/ | |
| 247 | + """ | |
| 248 | + df = dataframe.copy() | |
| 249 | + | |
| 250 | + avgval = zema(df, period, field) | |
| 251 | + | |
| 252 | + arr = np.diff(avgval) | |
| 253 | + pos = np.clip(arr, 0, 1).astype(bool).cumsum() | |
| 254 | + neg = np.clip(arr, -1, 0).astype(bool).cumsum() | |
| 255 | + streak = np.where(arr >= 0, pos - np.maximum.accumulate(np.where(arr <= 0, pos, 0)), | |
| 256 | + -neg + np.maximum.accumulate(np.where(arr >= 0, neg, 0))) | |
| 257 | + | |
| 258 | + res = same_length(df['close'], streak) | |
| 259 | + | |
| 260 | + return res | |
| 261 | + | |
| 262 | +def pcc(dataframe: DataFrame, period: int = 20, mult: int = 2): | |
| 263 | + """ | |
| 264 | + Percent Change Channel | |
| 265 | + PCC is like KC unless it uses percentage changes in price to set channel distance. | |
| 266 | + https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/ | |
| 267 | + """ | |
| 268 | + df = dataframe.copy() | |
| 269 | + | |
| 270 | + df['previous_close'] = df['close'].shift() | |
| 271 | + | |
| 272 | + df['close_change'] = (df['close'] - df['previous_close']) / df['previous_close'] * 100 | |
| 273 | + df['high_change'] = (df['high'] - df['close']) / df['close'] * 100 | |
| 274 | + df['low_change'] = (df['low'] - df['close']) / df['close'] * 100 | |
| 275 | + | |
| 276 | + df['delta'] = df['high_change'] - df['low_change'] | |
| 277 | + | |
| 278 | + mid = zema(df, period, 'close_change') | |
| 279 | + rangema = zema(df, period, 'delta') | |
| 280 | + | |
| 281 | + upper = mid + rangema * mult | |
| 282 | + lower = mid - rangema * mult | |
| 283 | + | |
| 284 | + return upper, rangema, lower | |
| 285 | + | |
| 286 | +def SSLChannels(dataframe, length=10, mode='sma'): | |
| 287 | + """ | |
| 288 | + Source: https://www.tradingview.com/script/xzIoaIJC-SSL-channel/ | |
| 289 | + 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 | + Usage: | |
| 298 | + dataframe['sslDown'], dataframe['sslUp'] = SSLChannels(dataframe, 10) | |
| 299 | + """ | |
| 300 | + if mode not in ('sma'): | |
| 301 | + raise ValueError(f"Mode {mode} not supported yet") | |
| 302 | + | |
| 303 | + df = dataframe.copy() | |
| 304 | + | |
| 305 | + if mode == 'sma': | |
| 306 | + df['smaHigh'] = df['high'].rolling(length).mean() | |
| 307 | + df['smaLow'] = df['low'].rolling(length).mean() | |
| 308 | + | |
| 309 | + df['hlv'] = np.where(df['close'] > df['smaHigh'], 1, | |
| 310 | + np.where(df['close'] < df['smaLow'], -1, np.NAN)) | |
| 311 | + df['hlv'] = df['hlv'].ffill() | |
| 312 | + | |
| 313 | + df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow']) | |
| 314 | + df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh']) | |
| 315 | + | |
| 316 | + return df['sslDown'], df['sslUp'] | |
| 317 | + | |
| 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) |
added strategies/old/BinHV27.py +227 −0
| @@ -0,0 +1,227 @@ | ||
| 1 | +from freqtrade.strategy.interface import IStrategy | |
| 2 | +from typing import Dict, List | |
| 3 | +from functools import reduce | |
| 4 | +from pandas import DataFrame | |
| 5 | +# -------------------------------- | |
| 6 | + | |
| 7 | +import talib.abstract as ta | |
| 8 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 9 | +from typing import Dict, List | |
| 10 | +from functools import reduce | |
| 11 | +from pandas import DataFrame, DatetimeIndex, merge | |
| 12 | +# -------------------------------- | |
| 13 | + | |
| 14 | +import talib.abstract as ta | |
| 15 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 16 | +import numpy # noqa | |
| 17 | + | |
| 18 | + | |
| 19 | +class BinHV27(IStrategy): | |
| 20 | + | |
| 21 | + timeframe = '5m' | |
| 22 | + | |
| 23 | + buy_params = { | |
| 24 | + 'adx1': 25, | |
| 25 | + 'emarsi1': 20, | |
| 26 | + 'adx2': 30, | |
| 27 | + 'emarsi2': 20, | |
| 28 | + 'adx3': 35, | |
| 29 | + 'emarsi3': 20, | |
| 30 | + 'adx4': 30, | |
| 31 | + 'emarsi4': 25 | |
| 32 | + } | |
| 33 | + | |
| 34 | + sell_params = { | |
| 35 | + 'emarsi1': 75, | |
| 36 | + 'adx2': 30, | |
| 37 | + 'emarsi2': 80, | |
| 38 | + 'emarsi3': 75, | |
| 39 | + } | |
| 40 | + | |
| 41 | + minimal_roi = { | |
| 42 | + "0": 0.05, | |
| 43 | + "10": 0.025, | |
| 44 | + "20": 0.015, | |
| 45 | + "30": 0.01, | |
| 46 | + "720": 0.005, | |
| 47 | + "1440": 0 | |
| 48 | + } | |
| 49 | + | |
| 50 | + custom_minimal_roi = { | |
| 51 | + 'enabled': True, | |
| 52 | + 'decay-type': 'exp', # linear (lin) or exponential (exp) | |
| 53 | + 'decay-rate': 0.015, # bigger is faster, recommended to graph f(t) = start-pct * e(-rate*t) | |
| 54 | + 'decay-time': 1440, # amount of time to reach zero, only relevant for linear decay | |
| 55 | + 'start-pct': 0.10, # starting percentage | |
| 56 | + 'end-pct': 0, # ending percentage | |
| 57 | + 'fit-type': 'poly' # best-fit a shape to the standard ROI table points using a polynomial (linear) or exponential shape | |
| 58 | + } | |
| 59 | + | |
| 60 | + stoploss = -0.50 | |
| 61 | + | |
| 62 | + # Probably don't change these | |
| 63 | + use_sell_signal = True | |
| 64 | + sell_profit_only = False | |
| 65 | + ignore_roi_if_buy_signal = True | |
| 66 | + | |
| 67 | + | |
| 68 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 69 | + dataframe['rsi'] = numpy.nan_to_num(ta.RSI(dataframe, timeperiod=5)) | |
| 70 | + dataframe['emarsi'] = numpy.nan_to_num(ta.EMA(dataframe['rsi'], timeperiod=5)) | |
| 71 | + | |
| 72 | + dataframe['adx'] = numpy.nan_to_num(ta.ADX(dataframe)) | |
| 73 | + | |
| 74 | + dataframe['minusdi'] = numpy.nan_to_num(ta.MINUS_DI(dataframe)) | |
| 75 | + dataframe['minusdiema'] = numpy.nan_to_num(ta.EMA(dataframe['minusdi'], timeperiod=25)) | |
| 76 | + dataframe['plusdi'] = numpy.nan_to_num(ta.PLUS_DI(dataframe)) | |
| 77 | + dataframe['plusdiema'] = numpy.nan_to_num(ta.EMA(dataframe['plusdi'], timeperiod=5)) | |
| 78 | + | |
| 79 | + dataframe['lowsma'] = numpy.nan_to_num(ta.EMA(dataframe, timeperiod=60)) | |
| 80 | + dataframe['highsma'] = numpy.nan_to_num(ta.EMA(dataframe, timeperiod=120)) | |
| 81 | + dataframe['fastsma'] = numpy.nan_to_num(ta.SMA(dataframe, timeperiod=120)) | |
| 82 | + dataframe['slowsma'] = numpy.nan_to_num(ta.SMA(dataframe, timeperiod=240)) | |
| 83 | + | |
| 84 | + dataframe['bigup'] = dataframe['fastsma'].gt(dataframe['slowsma']) & ((dataframe['fastsma'] - dataframe['slowsma']) > dataframe['close'] / 300) | |
| 85 | + dataframe['bigdown'] = ~dataframe['bigup'] | |
| 86 | + dataframe['trend'] = dataframe['fastsma'] - dataframe['slowsma'] | |
| 87 | + | |
| 88 | + dataframe['preparechangetrend'] = dataframe['trend'].gt(dataframe['trend'].shift()) | |
| 89 | + dataframe['preparechangetrendconfirm'] = dataframe['preparechangetrend'] & dataframe['trend'].shift().gt(dataframe['trend'].shift(2)) | |
| 90 | + dataframe['continueup'] = dataframe['slowsma'].gt(dataframe['slowsma'].shift()) & dataframe['slowsma'].shift().gt(dataframe['slowsma'].shift(2)) | |
| 91 | + | |
| 92 | + dataframe['delta'] = dataframe['fastsma'] - dataframe['fastsma'].shift() | |
| 93 | + dataframe['slowingdown'] = dataframe['delta'].lt(dataframe['delta'].shift()) | |
| 94 | + return dataframe | |
| 95 | + | |
| 96 | + | |
| 97 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 98 | + params = self.buy_params | |
| 99 | + | |
| 100 | + dataframe.loc[ | |
| 101 | + dataframe['slowsma'].gt(0) & | |
| 102 | + dataframe['close'].lt(dataframe['highsma']) & | |
| 103 | + dataframe['close'].lt(dataframe['lowsma']) & | |
| 104 | + dataframe['minusdi'].gt(dataframe['minusdiema']) & | |
| 105 | + dataframe['rsi'].ge(dataframe['rsi'].shift()) & | |
| 106 | + ( | |
| 107 | + ( | |
| 108 | + ~dataframe['preparechangetrend'] & | |
| 109 | + ~dataframe['continueup'] & | |
| 110 | + dataframe['adx'].gt(params['adx1']) & | |
| 111 | + dataframe['bigdown'] & | |
| 112 | + dataframe['emarsi'].le(params['emarsi1']) | |
| 113 | + ) | | |
| 114 | + ( | |
| 115 | + ~dataframe['preparechangetrend'] & | |
| 116 | + dataframe['continueup'] & | |
| 117 | + dataframe['adx'].gt(params['adx2']) & | |
| 118 | + dataframe['bigdown'] & | |
| 119 | + dataframe['emarsi'].le(params['emarsi2']) | |
| 120 | + ) | | |
| 121 | + ( | |
| 122 | + ~dataframe['continueup'] & | |
| 123 | + dataframe['adx'].gt(params['adx3']) & | |
| 124 | + dataframe['bigup'] & | |
| 125 | + dataframe['emarsi'].le(params['emarsi3']) | |
| 126 | + ) | | |
| 127 | + ( | |
| 128 | + dataframe['continueup'] & | |
| 129 | + dataframe['adx'].gt(params['adx4']) & | |
| 130 | + dataframe['bigup'] & | |
| 131 | + dataframe['emarsi'].le(params['emarsi4']) | |
| 132 | + ) | |
| 133 | + ), | |
| 134 | + 'buy'] = 1 | |
| 135 | + | |
| 136 | + return dataframe | |
| 137 | + | |
| 138 | + | |
| 139 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 140 | + params = self.sell_params | |
| 141 | + | |
| 142 | + dataframe.loc[ | |
| 143 | + ( | |
| 144 | + ( | |
| 145 | + ~dataframe['preparechangetrendconfirm'] & | |
| 146 | + ~dataframe['continueup'] & | |
| 147 | + (dataframe['close'].gt(dataframe['lowsma']) | dataframe['close'].gt(dataframe['highsma'])) & | |
| 148 | + dataframe['highsma'].gt(0) & | |
| 149 | + dataframe['bigdown'] | |
| 150 | + ) | | |
| 151 | + ( | |
| 152 | + ~dataframe['preparechangetrendconfirm'] & | |
| 153 | + ~dataframe['continueup'] & | |
| 154 | + dataframe['close'].gt(dataframe['highsma']) & | |
| 155 | + dataframe['highsma'].gt(0) & | |
| 156 | + (dataframe['emarsi'].ge(params['emarsi1']) | dataframe['close'].gt(dataframe['slowsma'])) & | |
| 157 | + dataframe['bigdown'] | |
| 158 | + ) | | |
| 159 | + ( | |
| 160 | + ~dataframe['preparechangetrendconfirm'] & | |
| 161 | + dataframe['close'].gt(dataframe['highsma']) & | |
| 162 | + dataframe['highsma'].gt(0) & | |
| 163 | + dataframe['adx'].gt(params['adx2']) & | |
| 164 | + dataframe['emarsi'].ge(params['emarsi2']) & | |
| 165 | + dataframe['bigup'] | |
| 166 | + ) | | |
| 167 | + ( | |
| 168 | + dataframe['preparechangetrendconfirm'] & | |
| 169 | + ~dataframe['continueup'] & | |
| 170 | + dataframe['slowingdown'] & | |
| 171 | + dataframe['emarsi'].ge(params['emarsi3']) & | |
| 172 | + dataframe['slowsma'].gt(0) | |
| 173 | + ) | | |
| 174 | + ( | |
| 175 | + dataframe['preparechangetrendconfirm'] & | |
| 176 | + dataframe['minusdi'].lt(dataframe['plusdi']) & | |
| 177 | + dataframe['close'].gt(dataframe['lowsma']) & | |
| 178 | + dataframe['slowsma'].gt(0) | |
| 179 | + ) | |
| 180 | + ), | |
| 181 | + 'sell'] = 1 | |
| 182 | + | |
| 183 | + return dataframe | |
| 184 | + | |
| 185 | + """ | |
| 186 | + Override for default Freqtrade ROI table functionality | |
| 187 | + """ | |
| 188 | + def poly(x, a, b): | |
| 189 | + return a + (x * b) | |
| 190 | + | |
| 191 | + def exp(x, a, b, c): | |
| 192 | + return a * np.exp(-b * x) + c | |
| 193 | + | |
| 194 | + def make_estimator(func, data): | |
| 195 | + xs, ys = zip(*sorted(data.items())) | |
| 196 | + popt, pcov = curve_fit(func, xs, ys) | |
| 197 | + return lambda x: func(x, *popt) | |
| 198 | + | |
| 199 | + def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 200 | + custom_roi = self.custom_minimal_roi | |
| 201 | + | |
| 202 | + # if the custom_roi dict is defined and enabled, do it, otherwise fallback to default functionality | |
| 203 | + if custom_roi and custom_roi['enabled']: | |
| 204 | + # linear decay: f(t) = start - (rate * t) | |
| 205 | + if custom_roi['decay-type'] == 'lin': | |
| 206 | + rate = (custom_roi['start-pct'] - custom_roi['end-pct']) / custom_roi['decay-time'] | |
| 207 | + min_roi = max(custom_roi['end-pct'], custom_roi['start-pct'] - (rate * trade_dur)) | |
| 208 | + # exponential decay: f(t) = start * e^(-rate*t) - c | |
| 209 | + elif custom_roi['decay-type'] == 'exp': | |
| 210 | + min_roi = max(custom_roi['end-pct'], custom_roi['start-pct'] * np.exp(-custom_roi['decay-rate']*time)) | |
| 211 | + # polynomial or exponential best-fit to points in defined roi table | |
| 212 | + elif custom_roi['decay-type'] == 'fit': | |
| 213 | + roi = self.minimal_roi | |
| 214 | + estimator = self.make_estimator(custom_roi['fit-type'], roi) | |
| 215 | + min_roi = estimator(trade_dur) | |
| 216 | + else: | |
| 217 | + min_roi = 0 | |
| 218 | + | |
| 219 | + return trade_dur, min_roi | |
| 220 | + | |
| 221 | + else: | |
| 222 | + # Get highest entry in ROI dict where key <= trade-duration | |
| 223 | + roi_list = list(filter(lambda x: x <= trade_dur, self.minimal_roi.keys())) | |
| 224 | + if not roi_list: | |
| 225 | + return None, None | |
| 226 | + roi_entry = max(roi_list) | |
| 227 | + return roi_entry, self.minimal_roi[roi_entry] | |
| No newline at the end of the file |
added strategies/old/BinHV45.py +89 −0
| @@ -0,0 +1,89 @@ | ||
| 1 | +# --- Do not remove these libs --- | |
| 2 | +from freqtrade.strategy.interface import IStrategy | |
| 3 | +from typing import Dict, List | |
| 4 | +from functools import reduce | |
| 5 | +from pandas import DataFrame | |
| 6 | +import numpy as np | |
| 7 | +# -------------------------------- | |
| 8 | + | |
| 9 | +import talib.abstract as ta | |
| 10 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 11 | + | |
| 12 | + | |
| 13 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 14 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 15 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 16 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 17 | + | |
| 18 | + return rolling_mean, lower_band | |
| 19 | + | |
| 20 | + | |
| 21 | +class BinHV45(IStrategy): | |
| 22 | + order_types = { | |
| 23 | + 'buy': 'limit', | |
| 24 | + 'sell': 'limit', | |
| 25 | + 'emergencysell': 'market', | |
| 26 | + 'stoploss': 'market', | |
| 27 | + 'stoploss_on_exchange': True, | |
| 28 | + 'stoploss_on_exchange_interval': 60, | |
| 29 | + 'stoploss_on_exchange_limit_ratio': 0.99 | |
| 30 | + } | |
| 31 | + | |
| 32 | + # Buy hyperspace params: | |
| 33 | + buy_params = { | |
| 34 | + 'bbdelta': 11, 'closedelta': 15, 'tail': 25 | |
| 35 | + } | |
| 36 | + | |
| 37 | + # Sell hyperspace params: | |
| 38 | + sell_params = { | |
| 39 | + | |
| 40 | + } | |
| 41 | + | |
| 42 | + # ROI table: | |
| 43 | + minimal_roi = { | |
| 44 | + '0': 0.20233, | |
| 45 | + '26': 0.06166, | |
| 46 | + '85': 0.01367, | |
| 47 | + '186': 0 | |
| 48 | + } | |
| 49 | + | |
| 50 | + # Stoploss: | |
| 51 | + stoploss = -0.13348 | |
| 52 | + | |
| 53 | + # Trailing stop: | |
| 54 | + trailing_stop = True | |
| 55 | + trailing_stop_positive = 0.30436 | |
| 56 | + trailing_stop_positive_offset = 0.31289 | |
| 57 | + trailing_only_offset_is_reached = False | |
| 58 | + | |
| 59 | + timeframe = '1m' | |
| 60 | + | |
| 61 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 62 | + mid, lower = bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 63 | + dataframe['mid'] = np.nan_to_num(mid) | |
| 64 | + dataframe['lower'] = np.nan_to_num(lower) | |
| 65 | + dataframe['bbdelta'] = (dataframe['mid'] - dataframe['lower']).abs() | |
| 66 | + dataframe['pricedelta'] = (dataframe['open'] - dataframe['close']).abs() | |
| 67 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 68 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 69 | + return dataframe | |
| 70 | + | |
| 71 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 72 | + dataframe.loc[ | |
| 73 | + ( | |
| 74 | + dataframe['lower'].shift().gt(0) & | |
| 75 | + dataframe['bbdelta'].gt(dataframe['close'] * 11 / 1000) & | |
| 76 | + dataframe['closedelta'].gt(dataframe['close'] * 15 / 1000) & | |
| 77 | + dataframe['tail'].lt(dataframe['bbdelta'] * 25 / 1000) & | |
| 78 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 79 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 80 | + ), | |
| 81 | + 'buy'] = 1 | |
| 82 | + return dataframe | |
| 83 | + | |
| 84 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 85 | + """ | |
| 86 | + no sell signal | |
| 87 | + """ | |
| 88 | + dataframe['sell'] = 0 | |
| 89 | + return dataframe |
added strategies/old/Cluc4.py +83 −0
| @@ -0,0 +1,83 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame | |
| 7 | + | |
| 8 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 9 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 10 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 11 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 12 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 13 | + | |
| 14 | +class Cluc4(IStrategy): | |
| 15 | + minimal_roi = { | |
| 16 | + "0": 0.015, | |
| 17 | + "20": 0.005, | |
| 18 | + "30": 0.001 | |
| 19 | + } | |
| 20 | + | |
| 21 | + stoploss = -0.01 | |
| 22 | + | |
| 23 | + timeframe = '1m' | |
| 24 | + | |
| 25 | + use_sell_signal = True | |
| 26 | + sell_profit_only = True | |
| 27 | + ignore_roi_if_buy_signal = True | |
| 28 | + | |
| 29 | + def informative_pairs(self): | |
| 30 | + pairs = self.dp.current_whitelist() | |
| 31 | + informative_pairs = [(pair, '1h') for pair in pairs] | |
| 32 | + return informative_pairs | |
| 33 | + | |
| 34 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 35 | + mid, lower = bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 36 | + dataframe['lower'] = lower | |
| 37 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 38 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 39 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 40 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) | |
| 41 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 42 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 43 | + dataframe['ema_slow'] = ta.EMA(dataframe, timeperiod=50) | |
| 44 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 45 | + dataframe['rocr'] = ta.ROCR(dataframe, timeperiod=28) | |
| 46 | + inf_tf = '1h' | |
| 47 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) | |
| 48 | + informative['rocr'] = ta.ROCR(informative, timeperiod=168) | |
| 49 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) | |
| 50 | + | |
| 51 | + return dataframe | |
| 52 | + | |
| 53 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 54 | + dataframe.loc[ | |
| 55 | + ( | |
| 56 | + dataframe['rocr_1h'].gt(0.65) | |
| 57 | + ) & | |
| 58 | + (( dataframe['lower'].shift().gt(0) & | |
| 59 | + dataframe['bbdelta'].gt(dataframe['close'] * 0.006) & | |
| 60 | + dataframe['closedelta'].gt(dataframe['close'] * 0.013) & | |
| 61 | + dataframe['tail'].lt(dataframe['bbdelta'] * 0.968) & | |
| 62 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 63 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 64 | + ) | | |
| 65 | + ( (dataframe['close'] < dataframe['ema_slow']) & | |
| 66 | + (dataframe['close'] < 0.013 * dataframe['bb_lowerband']) & | |
| 67 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * 28)) | |
| 68 | + )), | |
| 69 | + 'buy' | |
| 70 | + ] = 1 | |
| 71 | + return dataframe | |
| 72 | + | |
| 73 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 74 | + """ | |
| 75 | + """ | |
| 76 | + dataframe.loc[ | |
| 77 | + #((qtpylib.crossed_above(dataframe['close'],(dataframe['bb_middleband'] * 1.1))) & | |
| 78 | + ((qtpylib.crossed_above(dataframe['close'],dataframe['bb_middleband'])) & | |
| 79 | + (dataframe['volume'] > 0)) | |
| 80 | + , | |
| 81 | + 'sell' | |
| 82 | + ] = 1 | |
| 83 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/Cluc4werk.py +191 −0
| @@ -0,0 +1,191 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame | |
| 7 | + | |
| 8 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 9 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 10 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 11 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 12 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 13 | + | |
| 14 | +class Cluc4werk(IStrategy): | |
| 15 | + | |
| 16 | + """ | |
| 17 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 18 | + """ | |
| 19 | + | |
| 20 | + # 943/1000: 2423 trades. 1754/0/669 Wins/Draws/Losses. Avg profit 0.65%. Median profit 0.86%. Total profit 0.15692605 ETH ( 1566.74Σ%). Avg duration 58.4 min. Objective: -213.61288 | |
| 21 | + # Buy hyperspace params: | |
| 22 | + buy_params = { | |
| 23 | + 'bbdelta-close': 0.0085, | |
| 24 | + 'bbdelta-tail': 0.76175, | |
| 25 | + 'close-bblower': 0.01517, | |
| 26 | + 'closedelta-close': 0.01514, | |
| 27 | + 'rocr-1h': 0.58912, | |
| 28 | + 'volume': 21 | |
| 29 | + } | |
| 30 | + | |
| 31 | + # Sell hyperspace params: | |
| 32 | + sell_params = { | |
| 33 | + 'sell-bbmiddle-close': 0.99955 | |
| 34 | + } | |
| 35 | + | |
| 36 | + # ROI table: | |
| 37 | + minimal_roi = { | |
| 38 | + "0": 0.01497, | |
| 39 | + "77": 0.01321, | |
| 40 | + "130": 0.00976, | |
| 41 | + "356": 0.00709, | |
| 42 | + "464": 0.0027, | |
| 43 | + "564": 0.0016, | |
| 44 | + "697": 0 | |
| 45 | + } | |
| 46 | + | |
| 47 | + # Stoploss: | |
| 48 | + stoploss = -0.02055 | |
| 49 | + | |
| 50 | + # Trailing stop: | |
| 51 | + trailing_stop = True | |
| 52 | + trailing_stop_positive = 0.17429 | |
| 53 | + trailing_stop_positive_offset = 0.2716 | |
| 54 | + trailing_only_offset_is_reached = False | |
| 55 | + | |
| 56 | + """ | |
| 57 | + END HYPEROPT | |
| 58 | + """ | |
| 59 | + | |
| 60 | + timeframe = '1m' | |
| 61 | + | |
| 62 | + # Make sure these match or are not overridden in config | |
| 63 | + use_sell_signal = True | |
| 64 | + sell_profit_only = False | |
| 65 | + sell_profit_offset = 0.0 | |
| 66 | + ignore_roi_if_buy_signal = True | |
| 67 | + | |
| 68 | + def informative_pairs(self): | |
| 69 | + pairs = self.dp.current_whitelist() | |
| 70 | + informative_pairs = [(pair, '1h') for pair in pairs] | |
| 71 | + return informative_pairs | |
| 72 | + | |
| 73 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 74 | + # Set Up Bollinger Bands | |
| 75 | + mid, lower = bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 76 | + dataframe['lower'] = lower | |
| 77 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 78 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 79 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 80 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) | |
| 81 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 82 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 83 | + | |
| 84 | + dataframe['ema_slow'] = ta.EMA(dataframe, timeperiod=50) | |
| 85 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 86 | + dataframe['rocr'] = ta.ROCR(dataframe, timeperiod=28) | |
| 87 | + | |
| 88 | + inf_tf = '1h' | |
| 89 | + | |
| 90 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) | |
| 91 | + informative['rocr'] = ta.ROCR(informative, timeperiod=168) | |
| 92 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) | |
| 93 | + | |
| 94 | + return dataframe | |
| 95 | + | |
| 96 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 97 | + params = self.buy_params | |
| 98 | + | |
| 99 | + dataframe.loc[ | |
| 100 | + ( | |
| 101 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 102 | + ) & | |
| 103 | + (( | |
| 104 | + dataframe['lower'].shift().gt(0) & | |
| 105 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 106 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 107 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 108 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 109 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 110 | + ) | | |
| 111 | + ( | |
| 112 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 113 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 114 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 115 | + )), | |
| 116 | + 'buy' | |
| 117 | + ] = 1 | |
| 118 | + return dataframe | |
| 119 | + | |
| 120 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 121 | + params = self.sell_params | |
| 122 | + | |
| 123 | + dataframe.loc[ | |
| 124 | + (dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 125 | + (dataframe['high'].shift(1).le(dataframe['high'].shift(2))) & | |
| 126 | + (dataframe['close'].le(dataframe['close'].shift(1))) & | |
| 127 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 128 | + (dataframe['volume'] > 0) | |
| 129 | + , | |
| 130 | + 'sell' | |
| 131 | + ] = 1 | |
| 132 | + | |
| 133 | + """ | |
| 134 | + dataframe.loc[ | |
| 135 | + #(dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 136 | + #(dataframe['close'] > dataframe['bb_middleband']) & | |
| 137 | + (qtpylib.crossed_above((dataframe['close'] * params['sell-bbmiddle-close']),dataframe['bb_middleband'])) & | |
| 138 | + #(qtpylib.crossed_above(dataframe['close'],dataframe['bb_middleband'])) & | |
| 139 | + (dataframe['volume'] > 0) | |
| 140 | + , | |
| 141 | + 'sell' | |
| 142 | + ] = 1 | |
| 143 | + """ | |
| 144 | + | |
| 145 | + return dataframe | |
| 146 | + | |
| 147 | +class Cluc4werk_ETH(Cluc4werk): | |
| 148 | + | |
| 149 | + """ | |
| 150 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 151 | + """ | |
| 152 | + | |
| 153 | + # 943/1000: 2423 trades. 1754/0/669 Wins/Draws/Losses. Avg profit 0.65%. Median profit 0.86%. Total profit 0.15692605 ETH ( 1566.74Σ%). Avg duration 58.4 min. Objective: -213.61288 | |
| 154 | + # Buy hyperspace params: | |
| 155 | + buy_params = { | |
| 156 | + 'bbdelta-close': 0.0085, | |
| 157 | + 'bbdelta-tail': 0.76175, | |
| 158 | + 'close-bblower': 0.01517, | |
| 159 | + 'closedelta-close': 0.01514, | |
| 160 | + 'rocr-1h': 0.58912, | |
| 161 | + 'volume': 21 | |
| 162 | + } | |
| 163 | + | |
| 164 | + # Sell hyperspace params: | |
| 165 | + sell_params = { | |
| 166 | + 'sell-bbmiddle-close': 0.99955 | |
| 167 | + } | |
| 168 | + | |
| 169 | + # ROI table: | |
| 170 | + minimal_roi = { | |
| 171 | + "0": 0.01497, | |
| 172 | + "77": 0.01321, | |
| 173 | + "130": 0.00976, | |
| 174 | + "356": 0.00709, | |
| 175 | + "464": 0.0027, | |
| 176 | + "564": 0.0016, | |
| 177 | + "697": 0 | |
| 178 | + } | |
| 179 | + | |
| 180 | + # Stoploss: | |
| 181 | + stoploss = -0.02055 | |
| 182 | + | |
| 183 | + # Trailing stop: | |
| 184 | + trailing_stop = True | |
| 185 | + trailing_stop_positive = 0.17429 | |
| 186 | + trailing_stop_positive_offset = 0.2716 | |
| 187 | + trailing_only_offset_is_reached = False | |
| 188 | + | |
| 189 | + """ | |
| 190 | + END HYPEROPT | |
| 191 | + """ | |
| No newline at the end of the file |
added strategies/old/Cluc5werk.py +268 −0
| @@ -0,0 +1,268 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame | |
| 7 | + | |
| 8 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 9 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 10 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 11 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 12 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 13 | + | |
| 14 | +class Cluc5werk(IStrategy): | |
| 15 | + | |
| 16 | + """ | |
| 17 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 18 | + """ | |
| 19 | + | |
| 20 | + # 989/1000: 331 trades. 305/9/17 Wins/Draws/Losses. Avg profit 1.54%. Median profit 2.13%. Total profit 0.00510181 BTC ( 509.36Σ%). Avg duration 367.3 min. Objective: -0.69786 | |
| 21 | + # Buy hyperspace params: | |
| 22 | + buy_params = { | |
| 23 | + 'bbdelta-close': 0.01853, | |
| 24 | + 'bbdelta-tail': 0.78758, | |
| 25 | + 'close-bblower': 0.00931, | |
| 26 | + 'closedelta-close': 0.00169, | |
| 27 | + 'rocr-1h': 0.8973, | |
| 28 | + 'volume': 35 | |
| 29 | + } | |
| 30 | + | |
| 31 | + # Sell hyperspace params: | |
| 32 | + sell_params = { | |
| 33 | + 'sell-bbmiddle-close': 0.97103 | |
| 34 | + } | |
| 35 | + | |
| 36 | + # ROI table: | |
| 37 | + minimal_roi = { | |
| 38 | + "0": 0.02134, | |
| 39 | + "275": 0.01745, | |
| 40 | + "559": 0.01618, | |
| 41 | + "621": 0.0131, | |
| 42 | + "791": 0.00843, | |
| 43 | + "1048": 0.00443, | |
| 44 | + "1074": 0 | |
| 45 | + } | |
| 46 | + | |
| 47 | + # Stoploss: | |
| 48 | + stoploss = -0.22405 | |
| 49 | + | |
| 50 | + # Trailing stop: | |
| 51 | + trailing_stop = True | |
| 52 | + trailing_stop_positive = 0.18622 | |
| 53 | + trailing_stop_positive_offset = 0.23091 | |
| 54 | + trailing_only_offset_is_reached = False | |
| 55 | + | |
| 56 | + """ | |
| 57 | + END HYPEROPT | |
| 58 | + """ | |
| 59 | + | |
| 60 | + timeframe = '1m' | |
| 61 | + | |
| 62 | + # Make sure these match or are not overridden in config | |
| 63 | + use_sell_signal = True | |
| 64 | + sell_profit_only = False | |
| 65 | + sell_profit_offset = 0.0 | |
| 66 | + ignore_roi_if_buy_signal = True | |
| 67 | + | |
| 68 | + def informative_pairs(self): | |
| 69 | + pairs = self.dp.current_whitelist() | |
| 70 | + informative_pairs = [(pair, '1h') for pair in pairs] | |
| 71 | + return informative_pairs | |
| 72 | + | |
| 73 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 74 | + # Set Up Bollinger Bands | |
| 75 | + mid, lower = bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 76 | + dataframe['lower'] = lower | |
| 77 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 78 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 79 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 80 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) | |
| 81 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 82 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 83 | + | |
| 84 | + dataframe['ema_slow'] = ta.EMA(dataframe, timeperiod=50) | |
| 85 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 86 | + dataframe['rocr'] = ta.ROCR(dataframe, timeperiod=28) | |
| 87 | + | |
| 88 | + inf_tf = '1h' | |
| 89 | + | |
| 90 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) | |
| 91 | + informative['rocr'] = ta.ROCR(informative, timeperiod=168) | |
| 92 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) | |
| 93 | + | |
| 94 | + return dataframe | |
| 95 | + | |
| 96 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 97 | + params = self.buy_params | |
| 98 | + | |
| 99 | + dataframe.loc[ | |
| 100 | + ( | |
| 101 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 102 | + ) & | |
| 103 | + (( | |
| 104 | + dataframe['lower'].shift().gt(0) & | |
| 105 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 106 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 107 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 108 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 109 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 110 | + ) | | |
| 111 | + ( | |
| 112 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 113 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 114 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 115 | + )), | |
| 116 | + 'fake_buy' | |
| 117 | + ] = 1 | |
| 118 | + | |
| 119 | + dataframe.loc[ | |
| 120 | + (dataframe['fake_buy'].shift(1).eq(1)) & | |
| 121 | + (dataframe['fake_buy'].eq(1)) & | |
| 122 | + (dataframe['volume'] > 0) | |
| 123 | + , | |
| 124 | + 'buy' | |
| 125 | + ] = 1 | |
| 126 | + | |
| 127 | + return dataframe | |
| 128 | + | |
| 129 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 130 | + params = self.sell_params | |
| 131 | + | |
| 132 | + dataframe.loc[ | |
| 133 | + (dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 134 | + (dataframe['high'].shift(1).le(dataframe['high'].shift(2))) & | |
| 135 | + (dataframe['close'].le(dataframe['close'].shift(1))) & | |
| 136 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 137 | + (dataframe['volume'] > 0) | |
| 138 | + , | |
| 139 | + 'sell' | |
| 140 | + ] = 1 | |
| 141 | + | |
| 142 | + return dataframe | |
| 143 | + | |
| 144 | +class Cluc5werk_ETH(Cluc5werk): | |
| 145 | + | |
| 146 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_USD -e 1000 --spaces buy --timeframe 1m --timerange 20210101- | |
| 147 | + # 677/1000: 618 trades. 581/20/17 Wins/Draws/Losses. Avg profit 1.23%. Median profit 1.65%. Total profit 379.36403713 USD ( 757.52Σ%). Avg duration 297.5 min. Objective: -1.52505 | |
| 148 | + # Buy hyperspace params: | |
| 149 | + buy_params = { | |
| 150 | + 'bbdelta-close': 0.00902, | |
| 151 | + 'bbdelta-tail': 0.91508, | |
| 152 | + 'close-bblower': 0.00603, | |
| 153 | + 'closedelta-close': 0.00424, | |
| 154 | + 'rocr-1h': 0.93725, | |
| 155 | + 'volume': 38 | |
| 156 | + } | |
| 157 | + | |
| 158 | + # Sell hyperspace params: | |
| 159 | + sell_params = { | |
| 160 | + 'sell-bbmiddle-close': 0.97181 | |
| 161 | + } | |
| 162 | + | |
| 163 | + # ROI table: | |
| 164 | + minimal_roi = { | |
| 165 | + "0": 0.01648, | |
| 166 | + "38": 0.01484, | |
| 167 | + "303": 0.01317, | |
| 168 | + "597": 0.00952, | |
| 169 | + "869": 0.00724, | |
| 170 | + "896": 0.00253, | |
| 171 | + "1062": 0 | |
| 172 | + } | |
| 173 | + | |
| 174 | + # Stoploss: | |
| 175 | + stoploss = -0.33703 | |
| 176 | + | |
| 177 | + # Trailing stop: | |
| 178 | + trailing_stop = True | |
| 179 | + trailing_stop_positive = 0.29564 | |
| 180 | + trailing_stop_positive_offset = 0.38855 | |
| 181 | + trailing_only_offset_is_reached = False | |
| 182 | + | |
| 183 | +class Cluc5werk_BTC(Cluc5werk): | |
| 184 | + | |
| 185 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_BTC -e 500 --spaces all --timeframe 1m --timerange 20210101- | |
| 186 | + # 125/500: 422 trades. 369/14/39 Wins/Draws/Losses. Avg profit 0.97%. Median profit 2.18%. Total profit 0.00408737 BTC ( 408.13Σ%). Avg duration 307.8 min. Objective: -0.36043 | |
| 187 | + # Buy hyperspace params: | |
| 188 | + buy_params = { | |
| 189 | + 'bbdelta-close': 0.01511, | |
| 190 | + 'bbdelta-tail': 0.90705, | |
| 191 | + 'close-bblower': 0.01972, | |
| 192 | + 'closedelta-close': 0.00099, | |
| 193 | + 'rocr-1h': 0.97131, | |
| 194 | + 'volume': 27 | |
| 195 | + } | |
| 196 | + | |
| 197 | + # Sell hyperspace params: | |
| 198 | + sell_params = { | |
| 199 | + 'sell-bbmiddle-close': 0.97906 | |
| 200 | + } | |
| 201 | + | |
| 202 | + # ROI table: | |
| 203 | + minimal_roi = { | |
| 204 | + "0": 0.0218, | |
| 205 | + "242": 0.02079, | |
| 206 | + "308": 0.01803, | |
| 207 | + "372": 0.01325, | |
| 208 | + "390": 0.00905, | |
| 209 | + "619": 0.00467, | |
| 210 | + "737": 0 | |
| 211 | + } | |
| 212 | + | |
| 213 | + # Stoploss: | |
| 214 | + stoploss = -0.14515 | |
| 215 | + | |
| 216 | + # Trailing stop: | |
| 217 | + trailing_stop = True | |
| 218 | + trailing_stop_positive = 0.03046 | |
| 219 | + trailing_stop_positive_offset = 0.04631 | |
| 220 | + trailing_only_offset_is_reached = True | |
| 221 | + | |
| 222 | + | |
| 223 | + """ | |
| 224 | + END HYPEROPT | |
| 225 | + """ | |
| 226 | + | |
| 227 | +class Cluc5werk_USD(Cluc5werk): | |
| 228 | + | |
| 229 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_USD -e 1000 --spaces buy --timeframe 1m --timerange 20210101- | |
| 230 | + # 677/1000: 618 trades. 581/20/17 Wins/Draws/Losses. Avg profit 1.23%. Median profit 1.65%. Total profit 379.36403713 USD ( 757.52Σ%). Avg duration 297.5 min. Objective: -1.52505 | |
| 231 | + # Buy hyperspace params: | |
| 232 | + buy_params = { | |
| 233 | + 'bbdelta-close': 0.00902, | |
| 234 | + 'bbdelta-tail': 0.91508, | |
| 235 | + 'close-bblower': 0.00603, | |
| 236 | + 'closedelta-close': 0.00424, | |
| 237 | + 'rocr-1h': 0.93725, | |
| 238 | + 'volume': 38 | |
| 239 | + } | |
| 240 | + | |
| 241 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_USD -e 250 --spaces sell --timeframe 1m --timerange 20210101- | |
| 242 | + # 38/250: 609 trades. 573/20/16 Wins/Draws/Losses. Avg profit 1.25%. Median profit 1.65%. Total profit 382.03235064 USD ( 762.84Σ%). Avg duration 304.3 min. Objective: -1.54281 | |
| 243 | + # Sell hyperspace params: | |
| 244 | + sell_params = { | |
| 245 | + 'sell-bbmiddle-close': 0.97008 | |
| 246 | + } | |
| 247 | + | |
| 248 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt Cluc5werkHyperopt --hyperopt-loss OnlyProfitHyperOptLoss --strategy Cluc5werk_USD -e 250 --spaces roi --timeframe 1m --timerange 20210101- | |
| 249 | + # 139/250: 575 trades. 531/28/16 Wins/Draws/Losses. Avg profit 1.38%. Median profit 1.88%. Total profit 396.08871240 USD ( 790.91Σ%). Avg duration 330.9 min. Objective: -1.63637 | |
| 250 | + # ROI table: | |
| 251 | + minimal_roi = { | |
| 252 | + "0": 0.01887, | |
| 253 | + "150": 0.016, | |
| 254 | + "243": 0.01193, | |
| 255 | + "471": 0.0103, | |
| 256 | + "475": 0.00687, | |
| 257 | + "744": 0.00271, | |
| 258 | + "793": 0 | |
| 259 | + } | |
| 260 | + | |
| 261 | + # Stoploss: | |
| 262 | + stoploss = -0.33703 | |
| 263 | + | |
| 264 | + # Trailing stop: | |
| 265 | + trailing_stop = True | |
| 266 | + trailing_stop_positive = 0.29564 | |
| 267 | + trailing_stop_positive_offset = 0.38855 | |
| 268 | + trailing_only_offset_is_reached = False | |
| No newline at the end of the file |
added strategies/old/Cluc6werk.py +161 −0
| @@ -0,0 +1,161 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame | |
| 7 | + | |
| 8 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 9 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 10 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 11 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 12 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 13 | + | |
| 14 | +class Cluc4werk(IStrategy): | |
| 15 | + | |
| 16 | + # Used for "informative pairs" | |
| 17 | + stake = 'BTC' | |
| 18 | + fiat = 'USD' | |
| 19 | + | |
| 20 | + """ | |
| 21 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 22 | + """ | |
| 23 | + | |
| 24 | + # Buy hyperspace params: | |
| 25 | + buy_params = { | |
| 26 | + 'bbdelta-close': 0.00793, | |
| 27 | + 'bbdelta-tail': 0.83802, | |
| 28 | + 'close-bblower': 0.0034, | |
| 29 | + 'closedelta-close': 0.00613, | |
| 30 | + 'rocr-1h': 0.64081, | |
| 31 | + 'volume': 21 | |
| 32 | + } | |
| 33 | + | |
| 34 | + # Sell hyperspace params: | |
| 35 | + sell_params = { | |
| 36 | + 'sell-bbmiddle-close': 0.97703 | |
| 37 | + } | |
| 38 | + | |
| 39 | + # ROI table: | |
| 40 | + minimal_roi = { | |
| 41 | + "0": 0.0155, | |
| 42 | + "109": 0.01075, | |
| 43 | + "393": 0.00771, | |
| 44 | + "587": 0.00643, | |
| 45 | + "711": 0.00377, | |
| 46 | + "770": 0.00114, | |
| 47 | + "1039": 0 | |
| 48 | + } | |
| 49 | + | |
| 50 | + # Stoploss: | |
| 51 | + stoploss = -0.31742 | |
| 52 | + | |
| 53 | + # Trailing stop: | |
| 54 | + trailing_stop = True | |
| 55 | + trailing_stop_positive = 0.31289 | |
| 56 | + trailing_stop_positive_offset = 0.33275 | |
| 57 | + trailing_only_offset_is_reached = True | |
| 58 | + | |
| 59 | + """ | |
| 60 | + END HYPEROPT | |
| 61 | + """ | |
| 62 | + | |
| 63 | + timeframe = '1m' | |
| 64 | + | |
| 65 | + # Make sure these match or are not overridden in config | |
| 66 | + use_sell_signal = True | |
| 67 | + sell_profit_only = False | |
| 68 | + sell_profit_offset = 0.0 | |
| 69 | + ignore_roi_if_buy_signal = True | |
| 70 | + | |
| 71 | + def informative_pairs(self): | |
| 72 | + pairs = self.dp.current_whitelist() | |
| 73 | + informative_pairs = [(pair, '1h') for pair in pairs] | |
| 74 | + | |
| 75 | + """ | |
| 76 | + Idea is to have "STAKE/USD" and "COIN/USD" as informative pairs as they move inverse of COIN/STAKE. | |
| 77 | + For example, stake currency is BTC, whitelist is */BTC | |
| 78 | + Current pair being examined (metadata['pair']) is XLM/BTC | |
| 79 | + Be able to have informative pairs BTC/USD and XLM/USD available for use with some indicators for all pairs in the whitelist. | |
| 80 | + Ideally have this work gracefully with a change to the stake/whitelist in the config file. | |
| 81 | + If a desired informative pair does not exist (e.g. if exchange doesnt trade XLM/USD in this example), simply ignore those indicators without errors. | |
| 82 | + """ | |
| 83 | + | |
| 84 | + coin, stake = metadata['pair'].split('/') | |
| 85 | + | |
| 86 | + informative_pairs += [("ETH/USD", timeframe), | |
| 87 | + ("BTC/USD", timeframe), | |
| 88 | + ] | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + return informative_pairs | |
| 93 | + | |
| 94 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 95 | + # Set Up Bollinger Bands | |
| 96 | + mid, lower = bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 97 | + dataframe['lower'] = lower | |
| 98 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 99 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 100 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 101 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) | |
| 102 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 103 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 104 | + | |
| 105 | + dataframe['ema_slow'] = ta.EMA(dataframe, timeperiod=50) | |
| 106 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 107 | + dataframe['rocr'] = ta.ROCR(dataframe, timeperiod=28) | |
| 108 | + | |
| 109 | + inf_tf = '1h' | |
| 110 | + | |
| 111 | + """ | |
| 112 | + informative = self.dp.get_pair_dataframe(pair="ETH/USDT", timeframe="5m") | |
| 113 | + # ETH/USDT RSI based on 5m candles | |
| 114 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 115 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, '5m', ffill=True) | |
| 116 | + """ | |
| 117 | + | |
| 118 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) | |
| 119 | + informative['rocr'] = ta.ROCR(informative, timeperiod=168) | |
| 120 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) | |
| 121 | + | |
| 122 | + return dataframe | |
| 123 | + | |
| 124 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 125 | + params = self.buy_params | |
| 126 | + | |
| 127 | + dataframe.loc[ | |
| 128 | + ( | |
| 129 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 130 | + ) & | |
| 131 | + (( | |
| 132 | + dataframe['lower'].shift().gt(0) & | |
| 133 | + dataframe['bbdelta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 134 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 135 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 136 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 137 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 138 | + ) | | |
| 139 | + ( | |
| 140 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 141 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 142 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 143 | + )), | |
| 144 | + 'buy' | |
| 145 | + ] = 1 | |
| 146 | + return dataframe | |
| 147 | + | |
| 148 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 149 | + params = self.sell_params | |
| 150 | + | |
| 151 | + dataframe.loc[ | |
| 152 | + #(dataframe['high'].le(dataframe['high'].shift(1))) & | |
| 153 | + #(dataframe['close'] > dataframe['bb_middleband']) & | |
| 154 | + (qtpylib.crossed_above((dataframe['close'] * params['sell-bbmiddle-close']),dataframe['bb_middleband'])) & | |
| 155 | + #(qtpylib.crossed_above(dataframe['close'],dataframe['bb_middleband'])) & | |
| 156 | + (dataframe['volume'] > 0) | |
| 157 | + , | |
| 158 | + 'sell' | |
| 159 | + ] = 1 | |
| 160 | + | |
| 161 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/Cluc7werk.py +126 −0
| @@ -0,0 +1,126 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | + | |
| 8 | +class Cluc7werk(IStrategy): | |
| 9 | + | |
| 10 | + """ | |
| 11 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 12 | + """ | |
| 13 | + # Buy hyperspace params: | |
| 14 | + buy_params = { | |
| 15 | + 'bbdelta-close': 0.00732, | |
| 16 | + 'bbdelta-tail': 0.94138, | |
| 17 | + 'close-bblower': 0.0199, | |
| 18 | + 'closedelta-close': 0.01825, | |
| 19 | + 'fisher': -0.22987, | |
| 20 | + 'volume': 16 | |
| 21 | + } | |
| 22 | + | |
| 23 | + # Sell hyperspace params: | |
| 24 | + sell_params = { | |
| 25 | + 'sell-bbmiddle-close': 0.99184, | |
| 26 | + 'sell-fisher': 0.26832 | |
| 27 | + } | |
| 28 | + | |
| 29 | + # ROI table: | |
| 30 | + minimal_roi = { | |
| 31 | + "0": 0.15373, | |
| 32 | + "14": 0.1105, | |
| 33 | + "57": 0.08376, | |
| 34 | + "147": 0.03427, | |
| 35 | + "201": 0.01352, | |
| 36 | + "366": 0.00667, | |
| 37 | + "469": 0 | |
| 38 | + } | |
| 39 | + | |
| 40 | + # Stoploss: | |
| 41 | + stoploss = -0.02 | |
| 42 | + | |
| 43 | + # Trailing stop: | |
| 44 | + trailing_stop = True | |
| 45 | + trailing_stop_positive = 0.01007 | |
| 46 | + trailing_stop_positive_offset = 0.01258 | |
| 47 | + trailing_only_offset_is_reached = False | |
| 48 | + | |
| 49 | + """ | |
| 50 | + END HYPEROPT | |
| 51 | + """ | |
| 52 | + | |
| 53 | + timeframe = '1m' | |
| 54 | + | |
| 55 | + startup_candle_count: int = 72 | |
| 56 | + | |
| 57 | + # Make sure these match or are not overridden in config | |
| 58 | + use_sell_signal = True | |
| 59 | + sell_profit_only = True | |
| 60 | + sell_profit_offset = 0.01 | |
| 61 | + ignore_roi_if_buy_signal = True | |
| 62 | + | |
| 63 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 64 | + | |
| 65 | + # Set Up Bollinger Bands | |
| 66 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'], timeperiod=40) | |
| 67 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(dataframe), timeperiod=20) | |
| 68 | + | |
| 69 | + # only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 70 | + dataframe['lower-bb1'] = lower_bb1 | |
| 71 | + dataframe['lower-bb2'] = lower_bb2 | |
| 72 | + dataframe['mid-bb2'] = mid_bb2 | |
| 73 | + | |
| 74 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 75 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 76 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 77 | + | |
| 78 | + dataframe['ema_fast'] = ta.EMA(dataframe['close'], timeperiod=6) | |
| 79 | + dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48) | |
| 80 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 81 | + | |
| 82 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=9) | |
| 83 | + | |
| 84 | + # # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) | |
| 85 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 86 | + dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 87 | + | |
| 88 | + return dataframe | |
| 89 | + | |
| 90 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 91 | + params = self.buy_params | |
| 92 | + | |
| 93 | + dataframe.loc[ | |
| 94 | + ( | |
| 95 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 96 | + ) & | |
| 97 | + (( | |
| 98 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 99 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 100 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 101 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 102 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 103 | + ) | | |
| 104 | + ( | |
| 105 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 106 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 107 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 108 | + )), | |
| 109 | + 'buy' | |
| 110 | + ] = 1 | |
| 111 | + | |
| 112 | + return dataframe | |
| 113 | + | |
| 114 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 115 | + params = self.sell_params | |
| 116 | + | |
| 117 | + dataframe.loc[ | |
| 118 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 119 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 120 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 121 | + dataframe['volume'].gt(0) | |
| 122 | + , | |
| 123 | + 'sell' | |
| 124 | + ] = 1 | |
| 125 | + | |
| 126 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/ClucCrypROI.py +292 −0
| @@ -0,0 +1,292 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +from functools import reduce | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from datetime import datetime | |
| 8 | +from freqtrade.persistence import Trade | |
| 9 | +from pandas import DataFrame, Series | |
| 10 | + | |
| 11 | +class ClucCrypROI(IStrategy): | |
| 12 | + | |
| 13 | + # Used for "informative pairs" | |
| 14 | + fiat = 'USD' | |
| 15 | + | |
| 16 | + startup_candle_count: int = 48 | |
| 17 | + | |
| 18 | + def informative_pairs(self): | |
| 19 | + """ | |
| 20 | + Add informative pairs as follows | |
| 21 | + coin to fiat @ same candle as base strategy | |
| 22 | + stake to fiat @ same candle as base strategy | |
| 23 | + """ | |
| 24 | + pairs = self.dp.current_whitelist() | |
| 25 | + informative_pairs = [] | |
| 26 | + | |
| 27 | + for pair in pairs: | |
| 28 | + coin, stake = pair.split('/') | |
| 29 | + coin_fiat = f"{coin}/{self.fiat}" | |
| 30 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 31 | + | |
| 32 | + stake_fiat = f"{stake}/{self.fiat}" | |
| 33 | + | |
| 34 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 35 | + | |
| 36 | + return informative_pairs | |
| 37 | + | |
| 38 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 39 | + | |
| 40 | + # Set Up Bollinger Bands | |
| 41 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'], timeperiod=36) | |
| 42 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(dataframe), timeperiod=12) | |
| 43 | + | |
| 44 | + # Only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 45 | + dataframe['lower-bb1'] = lower_bb1 | |
| 46 | + dataframe['lower-bb2'] = lower_bb2 | |
| 47 | + dataframe['mid-bb2'] = mid_bb2 | |
| 48 | + | |
| 49 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 50 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 51 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 52 | + | |
| 53 | + # Additional indicators | |
| 54 | + dataframe['ema_fast'] = ta.EMA(dataframe['close'], timeperiod=6) | |
| 55 | + dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48) | |
| 56 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 57 | + | |
| 58 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) | |
| 59 | + | |
| 60 | + # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) | |
| 61 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 62 | + dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 63 | + | |
| 64 | + # Informative Pair Indicators | |
| 65 | + coin, stake = metadata['pair'].split('/') | |
| 66 | + fiat = self.fiat | |
| 67 | + stake_fiat = f"{stake}/{self.fiat}" | |
| 68 | + coin_fiat = f"{coin}/{self.fiat}" | |
| 69 | + | |
| 70 | + coin_fiat_inf = self.dp.get_pair_dataframe(pair=f"{coin}/{fiat}", timeframe=self.timeframe) | |
| 71 | + dataframe['coin-fiat-adx'] = ta.ADX(coin_fiat_inf, timeperiod=21) | |
| 72 | + coin_aroon = ta.AROON(coin_fiat_inf, timeperiod=25) | |
| 73 | + dataframe['coin-fiat-aroon-down'] = coin_aroon['aroondown'] | |
| 74 | + dataframe['coin-fiat-aroon-up'] = coin_aroon['aroonup'] | |
| 75 | + | |
| 76 | + stake_fiat_inf = self.dp.get_pair_dataframe(pair=f"{stake}/{fiat}", timeframe=self.timeframe) | |
| 77 | + dataframe['stake-fiat-adx'] = ta.ADX(stake_fiat_inf, timeperiod=21) | |
| 78 | + stake_aroon = ta.AROON(stake_fiat_inf, timeperiod=25) | |
| 79 | + dataframe['stake-fiat-aroon-down'] = stake_aroon['aroondown'] | |
| 80 | + dataframe['stake-fiat-aroon-up'] = stake_aroon['aroonup'] | |
| 81 | + | |
| 82 | + # These indicators are used to persist a buy signal in live trading only | |
| 83 | + # They dramatically slow backtesting down | |
| 84 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 85 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 86 | + | |
| 87 | + return dataframe | |
| 88 | + | |
| 89 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 90 | + params = self.buy_params | |
| 91 | + active_trade = False | |
| 92 | + | |
| 93 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 94 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 95 | + | |
| 96 | + conditions = [] | |
| 97 | + | |
| 98 | + """ | |
| 99 | + If this is a fresh buy, apple additional conditions. | |
| 100 | + Idea is to leverage "ignore_roi_if_buy_signal = True" functionality by using certain | |
| 101 | + indicators for active trades while applying additional protections to new trades. | |
| 102 | + """ | |
| 103 | + if not active_trade: | |
| 104 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 105 | + conditions.append( | |
| 106 | + (( | |
| 107 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 108 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 109 | + ) | ( | |
| 110 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 111 | + )) & (( | |
| 112 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 113 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 114 | + ) | ( | |
| 115 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 116 | + )) | |
| 117 | + ) | |
| 118 | + | |
| 119 | + conditions.append( | |
| 120 | + ( | |
| 121 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 122 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 123 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 124 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 125 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 126 | + ) | | |
| 127 | + ( | |
| 128 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 129 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 130 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 131 | + ) | |
| 132 | + ) | |
| 133 | + | |
| 134 | + else: | |
| 135 | + conditions.append(dataframe['close'] > dataframe['close'].shift()) | |
| 136 | + conditions.append(dataframe['close'] > dataframe['sar']) | |
| 137 | + | |
| 138 | + conditions.append(dataframe['volume'].gt(0)) | |
| 139 | + | |
| 140 | + if conditions: | |
| 141 | + dataframe.loc[ | |
| 142 | + reduce(lambda x, y: x & y, conditions), | |
| 143 | + 'buy'] = 1 | |
| 144 | + | |
| 145 | + return dataframe | |
| 146 | + | |
| 147 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 148 | + params = self.sell_params | |
| 149 | + | |
| 150 | + conditions = [] | |
| 151 | + | |
| 152 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 153 | + conditions.append( | |
| 154 | + (( | |
| 155 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 156 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 157 | + ) | ( | |
| 158 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 159 | + )) & (( | |
| 160 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 161 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 162 | + ) | ( | |
| 163 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 164 | + )) | |
| 165 | + ) | |
| 166 | + | |
| 167 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 168 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 169 | + conditions.append(dataframe['volume'].gt(0)) | |
| 170 | + | |
| 171 | + if conditions: | |
| 172 | + dataframe.loc[ | |
| 173 | + reduce(lambda x, y: x & y, conditions), | |
| 174 | + 'sell'] = 1 | |
| 175 | + | |
| 176 | + return dataframe | |
| 177 | + | |
| 178 | + """ | |
| 179 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 180 | + | |
| 181 | + Custom Order Timeouts | |
| 182 | + """ | |
| 183 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 184 | + ob = self.dp.orderbook(pair, 1) | |
| 185 | + current_price = ob['bids'][0][0] | |
| 186 | + # Cancel buy order if price is more than 1% above the order. | |
| 187 | + if current_price > order['price'] * 1.01: | |
| 188 | + return True | |
| 189 | + return False | |
| 190 | + | |
| 191 | + | |
| 192 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 193 | + ob = self.dp.orderbook(pair, 1) | |
| 194 | + current_price = ob['asks'][0][0] | |
| 195 | + # Cancel sell order if price is more than 1% below the order. | |
| 196 | + if current_price < order['price'] * 0.99: | |
| 197 | + return True | |
| 198 | + return False | |
| 199 | + | |
| 200 | +# Overriding strategy with optimized values when ETH is the stake currency | |
| 201 | +class ClucCrypROI_ETH(ClucCrypROI): | |
| 202 | + | |
| 203 | + timeframe = '15m' | |
| 204 | + | |
| 205 | + use_sell_signal = True | |
| 206 | + sell_profit_only = False | |
| 207 | + ignore_roi_if_buy_signal = True | |
| 208 | + | |
| 209 | + # Buy hyperspace params: | |
| 210 | + buy_params = { | |
| 211 | + 'adx': 46, | |
| 212 | + 'aroon': 51, | |
| 213 | + 'bbdelta-close': 0.01775, | |
| 214 | + 'bbdelta-tail': 0.84013, | |
| 215 | + 'close-bblower': 0.01096, | |
| 216 | + 'closedelta-close': 0.01068, | |
| 217 | + 'volume': 15 | |
| 218 | + } | |
| 219 | + | |
| 220 | + # Sell hyperspace params: | |
| 221 | + sell_params = { | |
| 222 | + 'sell-adx': 39, | |
| 223 | + 'sell-aroon': 65, | |
| 224 | + 'sell-bbmiddle-close': 0.98656 | |
| 225 | + } | |
| 226 | + | |
| 227 | + # ROI table: | |
| 228 | + minimal_roi = { | |
| 229 | + "0": 0.11487, | |
| 230 | + "4": 0.10783, | |
| 231 | + "5": 0.07209, | |
| 232 | + "15": 0.03179, | |
| 233 | + "60": 0.01044, | |
| 234 | + "112": 0.00541, | |
| 235 | + "270": 0 | |
| 236 | + } | |
| 237 | + | |
| 238 | + # Stoploss: | |
| 239 | + stoploss = -0.32238 | |
| 240 | + | |
| 241 | + # Trailing stop: | |
| 242 | + trailing_stop = True | |
| 243 | + trailing_stop_positive = 0.0102 | |
| 244 | + trailing_stop_positive_offset = 0.02872 | |
| 245 | + trailing_only_offset_is_reached = False | |
| 246 | + | |
| 247 | +# Overriding strategy with optimized values when BTC is the stake currency | |
| 248 | +class ClucCrypROI_BTC(ClucCrypROI): | |
| 249 | + | |
| 250 | + timeframe = '15m' | |
| 251 | + | |
| 252 | + use_sell_signal = True | |
| 253 | + sell_profit_only = False | |
| 254 | + ignore_roi_if_buy_signal = True | |
| 255 | + | |
| 256 | + # Buy hyperspace params: | |
| 257 | + buy_params = { | |
| 258 | + 'adx': 47, | |
| 259 | + 'aroon': 34, | |
| 260 | + 'bbdelta-close': 0.01957, | |
| 261 | + 'bbdelta-tail': 0.86961, | |
| 262 | + 'close-bblower': 0.00257, | |
| 263 | + 'closedelta-close': 0.01381, | |
| 264 | + 'volume': 27 | |
| 265 | + } | |
| 266 | + | |
| 267 | + # Sell hyperspace params: | |
| 268 | + sell_params = { | |
| 269 | + 'sell-adx': 20, | |
| 270 | + 'sell-aroon': 63, | |
| 271 | + 'sell-bbmiddle-close': 0.95563 | |
| 272 | + } | |
| 273 | + | |
| 274 | + # ROI table: | |
| 275 | + minimal_roi = { | |
| 276 | + "0": 0.08449, | |
| 277 | + "7": 0.04432, | |
| 278 | + "28": 0.0387, | |
| 279 | + "30": 0.0137, | |
| 280 | + "145": 0.0086, | |
| 281 | + "318": 0.00344, | |
| 282 | + "600": 0 | |
| 283 | + } | |
| 284 | + | |
| 285 | + # Stoploss: | |
| 286 | + stoploss = -0.33807 | |
| 287 | + | |
| 288 | + # Trailing stop: | |
| 289 | + trailing_stop = True | |
| 290 | + trailing_stop_positive = 0.01001 | |
| 291 | + trailing_stop_positive_offset = 0.02495 | |
| 292 | + trailing_only_offset_is_reached = False | |
| No newline at the end of the file |
added strategies/old/ClucCrypSlow.py +271 −0
| @@ -0,0 +1,271 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +from functools import reduce | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from datetime import datetime | |
| 8 | +from freqtrade.persistence import Trade | |
| 9 | +from pandas import DataFrame, Series | |
| 10 | + | |
| 11 | +class ClucCrypSlow(IStrategy): | |
| 12 | + | |
| 13 | + # Used for "informative pairs" | |
| 14 | + fiat = 'USD' | |
| 15 | + | |
| 16 | + startup_candle_count: int = 48 | |
| 17 | + | |
| 18 | + def informative_pairs(self): | |
| 19 | + """ | |
| 20 | + Add informative pairs as follows | |
| 21 | + coin to fiat @ same candle as base strategy | |
| 22 | + stake to fiat @ same candle as base strategy | |
| 23 | + """ | |
| 24 | + pairs = self.dp.current_whitelist() | |
| 25 | + informative_pairs = [] | |
| 26 | + | |
| 27 | + for pair in pairs: | |
| 28 | + coin, stake = pair.split('/') | |
| 29 | + coin_fiat = f"{coin}/{self.fiat}" | |
| 30 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 31 | + | |
| 32 | + stake_fiat = f"{stake}/{self.fiat}" | |
| 33 | + | |
| 34 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 35 | + | |
| 36 | + return informative_pairs | |
| 37 | + | |
| 38 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 39 | + | |
| 40 | + # Set Up Bollinger Bands | |
| 41 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'], timeperiod=36) | |
| 42 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(dataframe), timeperiod=12) | |
| 43 | + | |
| 44 | + # Only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 45 | + dataframe['lower-bb1'] = lower_bb1 | |
| 46 | + dataframe['lower-bb2'] = lower_bb2 | |
| 47 | + dataframe['mid-bb2'] = mid_bb2 | |
| 48 | + | |
| 49 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 50 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 51 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 52 | + | |
| 53 | + # Additional indicators | |
| 54 | + dataframe['ema_fast'] = ta.EMA(dataframe['close'], timeperiod=6) | |
| 55 | + dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48) | |
| 56 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 57 | + | |
| 58 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) | |
| 59 | + | |
| 60 | + # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) | |
| 61 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 62 | + dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 63 | + | |
| 64 | + # Informative Pair Indicators | |
| 65 | + coin, stake = metadata['pair'].split('/') | |
| 66 | + fiat = self.fiat | |
| 67 | + stake_fiat = f"{stake}/{self.fiat}" | |
| 68 | + coin_fiat = f"{coin}/{self.fiat}" | |
| 69 | + | |
| 70 | + coin_fiat_inf = self.dp.get_pair_dataframe(pair=f"{coin}/{fiat}", timeframe=self.timeframe) | |
| 71 | + dataframe['coin-fiat-adx'] = ta.ADX(coin_fiat_inf, timeperiod=21) | |
| 72 | + coin_aroon = ta.AROON(coin_fiat_inf, timeperiod=25) | |
| 73 | + dataframe['coin-fiat-aroon-down'] = coin_aroon['aroondown'] | |
| 74 | + dataframe['coin-fiat-aroon-up'] = coin_aroon['aroonup'] | |
| 75 | + | |
| 76 | + stake_fiat_inf = self.dp.get_pair_dataframe(pair=f"{stake}/{fiat}", timeframe=self.timeframe) | |
| 77 | + dataframe['stake-fiat-adx'] = ta.ADX(stake_fiat_inf, timeperiod=21) | |
| 78 | + stake_aroon = ta.AROON(stake_fiat_inf, timeperiod=25) | |
| 79 | + dataframe['stake-fiat-aroon-down'] = stake_aroon['aroondown'] | |
| 80 | + dataframe['stake-fiat-aroon-up'] = stake_aroon['aroonup'] | |
| 81 | + | |
| 82 | + return dataframe | |
| 83 | + | |
| 84 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 85 | + params = self.buy_params | |
| 86 | + | |
| 87 | + conditions = [] | |
| 88 | + | |
| 89 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 90 | + conditions.append((( | |
| 91 | + (dataframe['stake-fiat-adx'] > params['adx']) & | |
| 92 | + (dataframe['stake-fiat-aroon-down'] > params['aroon']) | |
| 93 | + ) | ( | |
| 94 | + (dataframe['stake-fiat-adx'] < params['adx']) | |
| 95 | + )) & (( | |
| 96 | + (dataframe['coin-fiat-adx'] > params['adx']) & | |
| 97 | + (dataframe['coin-fiat-aroon-up'] > params['aroon']) | |
| 98 | + ) | ( | |
| 99 | + (dataframe['coin-fiat-adx'] < params['adx']) | |
| 100 | + )) | |
| 101 | + ) | |
| 102 | + | |
| 103 | + conditions.append( | |
| 104 | + ( | |
| 105 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 106 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 107 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 108 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 109 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 110 | + ) | | |
| 111 | + ( | |
| 112 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 113 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 114 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 115 | + ) | |
| 116 | + ) | |
| 117 | + | |
| 118 | + conditions.append(dataframe['volume'].gt(0)) | |
| 119 | + | |
| 120 | + if conditions: | |
| 121 | + dataframe.loc[ | |
| 122 | + reduce(lambda x, y: x & y, conditions), | |
| 123 | + 'buy'] = 1 | |
| 124 | + | |
| 125 | + return dataframe | |
| 126 | + | |
| 127 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 128 | + params = self.sell_params | |
| 129 | + | |
| 130 | + conditions = [] | |
| 131 | + | |
| 132 | + if 'stake-fiat-adx' in dataframe.columns and 'coin-fiat-adx' in dataframe.columns: | |
| 133 | + conditions.append((( | |
| 134 | + (dataframe['stake-fiat-adx'] > params['sell-adx']) & | |
| 135 | + (dataframe['stake-fiat-aroon-up'] > params['sell-aroon']) | |
| 136 | + ) | ( | |
| 137 | + (dataframe['stake-fiat-adx'] < params['sell-adx']) | |
| 138 | + )) & (( | |
| 139 | + (dataframe['coin-fiat-adx'] > params['sell-adx']) & | |
| 140 | + (dataframe['coin-fiat-aroon-down'] > params['sell-aroon']) | |
| 141 | + ) | ( | |
| 142 | + (dataframe['coin-fiat-adx'] < params['sell-adx']) | |
| 143 | + )) | |
| 144 | + ) | |
| 145 | + | |
| 146 | + conditions.append((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) | |
| 147 | + conditions.append(dataframe['ema_fast'].gt(dataframe['close'])) | |
| 148 | + conditions.append(dataframe['volume'].gt(0)) | |
| 149 | + | |
| 150 | + if conditions: | |
| 151 | + dataframe.loc[ | |
| 152 | + reduce(lambda x, y: x & y, conditions), | |
| 153 | + 'sell'] = 1 | |
| 154 | + | |
| 155 | + return dataframe | |
| 156 | + | |
| 157 | + """ | |
| 158 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 159 | + | |
| 160 | + Custom Order Timeouts | |
| 161 | + """ | |
| 162 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 163 | + ob = self.dp.orderbook(pair, 1) | |
| 164 | + current_price = ob['bids'][0][0] | |
| 165 | + # Cancel buy order if price is more than 1% above the order. | |
| 166 | + if current_price > order['price'] * 1.01: | |
| 167 | + return True | |
| 168 | + return False | |
| 169 | + | |
| 170 | + | |
| 171 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 172 | + ob = self.dp.orderbook(pair, 1) | |
| 173 | + current_price = ob['asks'][0][0] | |
| 174 | + # Cancel sell order if price is more than 1% below the order. | |
| 175 | + if current_price < order['price'] * 0.99: | |
| 176 | + return True | |
| 177 | + return False | |
| 178 | + | |
| 179 | +# Overriding strategy with optimized values when ETH is the stake currency | |
| 180 | +class ClucCrypSlow_ETH(ClucCrypSlow): | |
| 181 | + | |
| 182 | + timeframe = '15m' | |
| 183 | + | |
| 184 | + use_sell_signal = True | |
| 185 | + sell_profit_only = False | |
| 186 | + ignore_roi_if_buy_signal = True | |
| 187 | + | |
| 188 | + # Buy hyperspace params: | |
| 189 | + buy_params = { | |
| 190 | + 'adx': 46, | |
| 191 | + 'aroon': 51, | |
| 192 | + 'bbdelta-close': 0.01775, | |
| 193 | + 'bbdelta-tail': 0.84013, | |
| 194 | + 'close-bblower': 0.01096, | |
| 195 | + 'closedelta-close': 0.01068, | |
| 196 | + 'volume': 15 | |
| 197 | + } | |
| 198 | + | |
| 199 | + # Sell hyperspace params: | |
| 200 | + sell_params = { | |
| 201 | + 'sell-adx': 39, | |
| 202 | + 'sell-aroon': 65, | |
| 203 | + 'sell-bbmiddle-close': 0.98656 | |
| 204 | + } | |
| 205 | + | |
| 206 | + # ROI table: | |
| 207 | + minimal_roi = { | |
| 208 | + "0": 0.11487, | |
| 209 | + "4": 0.10783, | |
| 210 | + "5": 0.07209, | |
| 211 | + "15": 0.03179, | |
| 212 | + "60": 0.01044, | |
| 213 | + "112": 0.00541, | |
| 214 | + "270": 0 | |
| 215 | + } | |
| 216 | + | |
| 217 | + # Stoploss: | |
| 218 | + stoploss = -0.32238 | |
| 219 | + | |
| 220 | + # Trailing stop: | |
| 221 | + trailing_stop = True | |
| 222 | + trailing_stop_positive = 0.0102 | |
| 223 | + trailing_stop_positive_offset = 0.02872 | |
| 224 | + trailing_only_offset_is_reached = False | |
| 225 | + | |
| 226 | +# Overriding strategy with optimized values when BTC is the stake currency | |
| 227 | +class ClucCrypSlow_BTC(ClucCrypSlow): | |
| 228 | + | |
| 229 | + timeframe = '15m' | |
| 230 | + | |
| 231 | + use_sell_signal = True | |
| 232 | + sell_profit_only = False | |
| 233 | + ignore_roi_if_buy_signal = True | |
| 234 | + | |
| 235 | + # Buy hyperspace params: | |
| 236 | + buy_params = { | |
| 237 | + 'adx': 47, | |
| 238 | + 'aroon': 34, | |
| 239 | + 'bbdelta-close': 0.01957, | |
| 240 | + 'bbdelta-tail': 0.86961, | |
| 241 | + 'close-bblower': 0.00257, | |
| 242 | + 'closedelta-close': 0.01381, | |
| 243 | + 'volume': 27 | |
| 244 | + } | |
| 245 | + | |
| 246 | + # Sell hyperspace params: | |
| 247 | + sell_params = { | |
| 248 | + 'sell-adx': 20, | |
| 249 | + 'sell-aroon': 63, | |
| 250 | + 'sell-bbmiddle-close': 0.95563 | |
| 251 | + } | |
| 252 | + | |
| 253 | + # ROI table: | |
| 254 | + minimal_roi = { | |
| 255 | + "0": 0.08449, | |
| 256 | + "7": 0.04432, | |
| 257 | + "28": 0.0387, | |
| 258 | + "30": 0.0137, | |
| 259 | + "145": 0.0086, | |
| 260 | + "318": 0.00344, | |
| 261 | + "600": 0 | |
| 262 | + } | |
| 263 | + | |
| 264 | + # Stoploss: | |
| 265 | + stoploss = -0.33807 | |
| 266 | + | |
| 267 | + # Trailing stop: | |
| 268 | + trailing_stop = True | |
| 269 | + trailing_stop_positive = 0.01001 | |
| 270 | + trailing_stop_positive_offset = 0.02495 | |
| 271 | + trailing_only_offset_is_reached = False | |
| No newline at the end of the file |
added strategies/old/ClucFiatROI.py +175 −0
| @@ -0,0 +1,175 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +from functools import reduce | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from datetime import datetime | |
| 8 | +from freqtrade.persistence import Trade | |
| 9 | +from pandas import DataFrame, Series | |
| 10 | + | |
| 11 | +class ClucFiatROI(IStrategy): | |
| 12 | + | |
| 13 | + # Buy hyperspace params: | |
| 14 | + buy_params = { | |
| 15 | + 'bbdelta-close': 0.00642, | |
| 16 | + 'bbdelta-tail': 0.75559, | |
| 17 | + 'close-bblower': 0.01415, | |
| 18 | + 'closedelta-close': 0.00883, | |
| 19 | + 'fisher': -0.97101, | |
| 20 | + 'volume': 18 | |
| 21 | + } | |
| 22 | + | |
| 23 | + # Sell hyperspace params: | |
| 24 | + sell_params = { | |
| 25 | + 'sell-bbmiddle-close': 0.95153, | |
| 26 | + 'sell-fisher': 0.60924 | |
| 27 | + } | |
| 28 | + | |
| 29 | + # ROI table: | |
| 30 | + minimal_roi = { | |
| 31 | + "0": 0.04354, | |
| 32 | + "5": 0.03734, | |
| 33 | + "8": 0.02569, | |
| 34 | + "10": 0.019, | |
| 35 | + "76": 0.01283, | |
| 36 | + "235": 0.007, | |
| 37 | + "415": 0 | |
| 38 | + } | |
| 39 | + | |
| 40 | + # Stoploss: | |
| 41 | + stoploss = -0.34299 | |
| 42 | + | |
| 43 | + # Trailing stop: | |
| 44 | + trailing_stop = True | |
| 45 | + trailing_stop_positive = 0.01057 | |
| 46 | + trailing_stop_positive_offset = 0.03668 | |
| 47 | + trailing_only_offset_is_reached = True | |
| 48 | + | |
| 49 | + """ | |
| 50 | + END HYPEROPT | |
| 51 | + """ | |
| 52 | + | |
| 53 | + timeframe = '5m' | |
| 54 | + | |
| 55 | + use_sell_signal = True | |
| 56 | + sell_profit_only = False | |
| 57 | + sell_profit_offset = 0.01 | |
| 58 | + ignore_roi_if_buy_signal = True | |
| 59 | + | |
| 60 | + startup_candle_count: int = 48 | |
| 61 | + | |
| 62 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + # Set Up Bollinger Bands | |
| 65 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'], timeperiod=40) | |
| 66 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(dataframe), timeperiod=20) | |
| 67 | + | |
| 68 | + # only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 69 | + dataframe['lower-bb1'] = lower_bb1 | |
| 70 | + dataframe['lower-bb2'] = lower_bb2 | |
| 71 | + dataframe['mid-bb2'] = mid_bb2 | |
| 72 | + | |
| 73 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 74 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 75 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 76 | + | |
| 77 | + dataframe['ema_fast'] = ta.EMA(dataframe['close'], timeperiod=6) | |
| 78 | + dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48) | |
| 79 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 80 | + | |
| 81 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=9) | |
| 82 | + | |
| 83 | + # # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) | |
| 84 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 85 | + dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 86 | + | |
| 87 | + # These indicators are used to persist a buy signal in live trading only | |
| 88 | + # They dramatically slow backtesting down | |
| 89 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 90 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 91 | + | |
| 92 | + return dataframe | |
| 93 | + | |
| 94 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 95 | + params = self.buy_params | |
| 96 | + active_trade = False | |
| 97 | + | |
| 98 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 99 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 100 | + | |
| 101 | + conditions = [] | |
| 102 | + | |
| 103 | + """ | |
| 104 | + If this is a fresh buy, apple additional conditions. | |
| 105 | + Idea is to leverage "ignore_roi_if_buy_signal = True" functionality by using certain | |
| 106 | + indicators for active trades while applying additional protections to new trades. | |
| 107 | + """ | |
| 108 | + if not active_trade: | |
| 109 | + conditions.append( | |
| 110 | + ( | |
| 111 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 112 | + ) & | |
| 113 | + (( | |
| 114 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 115 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 116 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 117 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 118 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 119 | + ) | | |
| 120 | + ( | |
| 121 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 122 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 123 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 124 | + )) | |
| 125 | + ) | |
| 126 | + | |
| 127 | + else: | |
| 128 | + conditions.append(dataframe['close'] > dataframe['close'].shift()) | |
| 129 | + conditions.append(dataframe['close'] > dataframe['sar']) | |
| 130 | + | |
| 131 | + conditions.append(dataframe['volume'].gt(0)) | |
| 132 | + | |
| 133 | + if conditions: | |
| 134 | + dataframe.loc[ | |
| 135 | + reduce(lambda x, y: x & y, conditions), | |
| 136 | + 'buy'] = 1 | |
| 137 | + | |
| 138 | + return dataframe | |
| 139 | + | |
| 140 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 141 | + params = self.sell_params | |
| 142 | + | |
| 143 | + dataframe.loc[ | |
| 144 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 145 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 146 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 147 | + dataframe['volume'].gt(0) | |
| 148 | + , | |
| 149 | + 'sell' | |
| 150 | + ] = 1 | |
| 151 | + | |
| 152 | + return dataframe | |
| 153 | + | |
| 154 | + """ | |
| 155 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 156 | + | |
| 157 | + Custom Order Timeouts | |
| 158 | + """ | |
| 159 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 160 | + ob = self.dp.orderbook(pair, 1) | |
| 161 | + current_price = ob['bids'][0][0] | |
| 162 | + # Cancel buy order if price is more than 1% above the order. | |
| 163 | + if current_price > order['price'] * 1.01: | |
| 164 | + return True | |
| 165 | + return False | |
| 166 | + | |
| 167 | + | |
| 168 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 169 | + ob = self.dp.orderbook(pair, 1) | |
| 170 | + current_price = ob['asks'][0][0] | |
| 171 | + # Cancel sell order if price is more than 1% below the order. | |
| 172 | + if current_price < order['price'] * 0.99: | |
| 173 | + return True | |
| 174 | + return False | |
| 175 | + |
added strategies/old/ClucFiatSlow.py +147 −0
| @@ -0,0 +1,147 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from datetime import datetime | |
| 7 | +from freqtrade.persistence import Trade | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | + | |
| 10 | +class ClucFiatSlow(IStrategy): | |
| 11 | + | |
| 12 | + # Buy hyperspace params: | |
| 13 | + buy_params = { | |
| 14 | + 'bbdelta-close': 0.00642, | |
| 15 | + 'bbdelta-tail': 0.75559, | |
| 16 | + 'close-bblower': 0.01415, | |
| 17 | + 'closedelta-close': 0.00883, | |
| 18 | + 'fisher': -0.97101, | |
| 19 | + 'volume': 18 | |
| 20 | + } | |
| 21 | + | |
| 22 | + # Sell hyperspace params: | |
| 23 | + sell_params = { | |
| 24 | + 'sell-bbmiddle-close': 0.95153, | |
| 25 | + 'sell-fisher': 0.60924 | |
| 26 | + } | |
| 27 | + | |
| 28 | + # ROI table: | |
| 29 | + minimal_roi = { | |
| 30 | + "0": 0.04354, | |
| 31 | + "5": 0.03734, | |
| 32 | + "8": 0.02569, | |
| 33 | + "10": 0.019, | |
| 34 | + "76": 0.01283, | |
| 35 | + "235": 0.007, | |
| 36 | + "415": 0 | |
| 37 | + } | |
| 38 | + | |
| 39 | + # Stoploss: | |
| 40 | + stoploss = -0.34299 | |
| 41 | + | |
| 42 | + # Trailing stop: | |
| 43 | + trailing_stop = True | |
| 44 | + trailing_stop_positive = 0.01057 | |
| 45 | + trailing_stop_positive_offset = 0.03668 | |
| 46 | + trailing_only_offset_is_reached = True | |
| 47 | + | |
| 48 | + """ | |
| 49 | + END HYPEROPT | |
| 50 | + """ | |
| 51 | + | |
| 52 | + timeframe = '5m' | |
| 53 | + | |
| 54 | + use_sell_signal = True | |
| 55 | + sell_profit_only = False | |
| 56 | + sell_profit_offset = 0.01 | |
| 57 | + ignore_roi_if_buy_signal = True | |
| 58 | + | |
| 59 | + startup_candle_count: int = 48 | |
| 60 | + | |
| 61 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 62 | + | |
| 63 | + # Set Up Bollinger Bands | |
| 64 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'], timeperiod=40) | |
| 65 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(dataframe), timeperiod=20) | |
| 66 | + | |
| 67 | + # only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 68 | + dataframe['lower-bb1'] = lower_bb1 | |
| 69 | + dataframe['lower-bb2'] = lower_bb2 | |
| 70 | + dataframe['mid-bb2'] = mid_bb2 | |
| 71 | + | |
| 72 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 73 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 74 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 75 | + | |
| 76 | + dataframe['ema_fast'] = ta.EMA(dataframe['close'], timeperiod=6) | |
| 77 | + dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48) | |
| 78 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 79 | + | |
| 80 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=9) | |
| 81 | + | |
| 82 | + # # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) | |
| 83 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 84 | + dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 85 | + | |
| 86 | + return dataframe | |
| 87 | + | |
| 88 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 89 | + params = self.buy_params | |
| 90 | + | |
| 91 | + dataframe.loc[ | |
| 92 | + ( | |
| 93 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 94 | + ) & | |
| 95 | + (( | |
| 96 | + dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close']) & | |
| 97 | + dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close']) & | |
| 98 | + dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail']) & | |
| 99 | + dataframe['close'].lt(dataframe['lower-bb1'].shift()) & | |
| 100 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 101 | + ) | | |
| 102 | + ( | |
| 103 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 104 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 105 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 106 | + )), | |
| 107 | + 'buy' | |
| 108 | + ] = 1 | |
| 109 | + | |
| 110 | + return dataframe | |
| 111 | + | |
| 112 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 113 | + params = self.sell_params | |
| 114 | + | |
| 115 | + dataframe.loc[ | |
| 116 | + ((dataframe['close'] * params['sell-bbmiddle-close']) > dataframe['mid-bb2']) & | |
| 117 | + dataframe['ema_fast'].gt(dataframe['close']) & | |
| 118 | + dataframe['fisher-rsi'].gt(params['sell-fisher']) & | |
| 119 | + dataframe['volume'].gt(0) | |
| 120 | + , | |
| 121 | + 'sell' | |
| 122 | + ] = 1 | |
| 123 | + | |
| 124 | + return dataframe | |
| 125 | + | |
| 126 | + """ | |
| 127 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 128 | + | |
| 129 | + Custom Order Timeouts | |
| 130 | + """ | |
| 131 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 132 | + ob = self.dp.orderbook(pair, 1) | |
| 133 | + current_price = ob['bids'][0][0] | |
| 134 | + # Cancel buy order if price is more than 1% above the order. | |
| 135 | + if current_price > order['price'] * 1.01: | |
| 136 | + return True | |
| 137 | + return False | |
| 138 | + | |
| 139 | + | |
| 140 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 141 | + ob = self.dp.orderbook(pair, 1) | |
| 142 | + current_price = ob['asks'][0][0] | |
| 143 | + # Cancel sell order if price is more than 1% below the order. | |
| 144 | + if current_price < order['price'] * 0.99: | |
| 145 | + return True | |
| 146 | + return False | |
| 147 | + |
added strategies/old/ClucHAnix.py +273 −0
| @@ -0,0 +1,273 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | + | |
| 8 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 9 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 10 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 11 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 12 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 13 | + | |
| 14 | +def ha_typical_price(bars): | |
| 15 | + res = (bars['ha_high'] + bars['ha_low'] + bars['ha_close']) / 3. | |
| 16 | + return Series(index=bars.index, data=res) | |
| 17 | + | |
| 18 | +class ClucHAnix(IStrategy): | |
| 19 | + | |
| 20 | + """ | |
| 21 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 22 | + Can be overridden for specific sub-strategies (stake currencies) at the bottom. | |
| 23 | + """ | |
| 24 | + | |
| 25 | + # Buy hyperspace params: | |
| 26 | + buy_params = { | |
| 27 | + 'bbdelta-close': 0.01965, | |
| 28 | + 'bbdelta-tail': 0.95089, | |
| 29 | + 'close-bblower': 0.00799, | |
| 30 | + 'closedelta-close': 0.00556, | |
| 31 | + 'rocr-1h': 0.54904 | |
| 32 | + } | |
| 33 | + | |
| 34 | + # Sell hyperspace params: | |
| 35 | + sell_params = { | |
| 36 | + 'sell-fisher': 0.38414, | |
| 37 | + 'sell-bbmiddle-close': 1.07634 | |
| 38 | + } | |
| 39 | + | |
| 40 | + # ROI table: | |
| 41 | + minimal_roi = { | |
| 42 | + "0": 0.02139, | |
| 43 | + "36": 0.01666, | |
| 44 | + "174": 0.01191, | |
| 45 | + "463": 0.00874, | |
| 46 | + "593": 0.00514, | |
| 47 | + "604": 0.00031, | |
| 48 | + "786": 0 | |
| 49 | + } | |
| 50 | + | |
| 51 | + # Stoploss: | |
| 52 | + stoploss = -0.23144 | |
| 53 | + | |
| 54 | + # Trailing stop: | |
| 55 | + trailing_stop = True | |
| 56 | + trailing_stop_positive = 0.3207 | |
| 57 | + trailing_stop_positive_offset = 0.3849 | |
| 58 | + trailing_only_offset_is_reached = True | |
| 59 | + | |
| 60 | + """ | |
| 61 | + END HYPEROPT | |
| 62 | + """ | |
| 63 | + | |
| 64 | + timeframe = '1m' | |
| 65 | + | |
| 66 | + # Make sure these match or are not overridden in config | |
| 67 | + use_sell_signal = True | |
| 68 | + sell_profit_only = False | |
| 69 | + ignore_roi_if_buy_signal = True | |
| 70 | + | |
| 71 | + def informative_pairs(self): | |
| 72 | + pairs = self.dp.current_whitelist() | |
| 73 | + informative_pairs = [(pair, '1h') for pair in pairs] | |
| 74 | + return informative_pairs | |
| 75 | + | |
| 76 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 77 | + # # Heikin Ashi Candles | |
| 78 | + heikinashi = qtpylib.heikinashi(dataframe) | |
| 79 | + dataframe['ha_open'] = heikinashi['open'] | |
| 80 | + dataframe['ha_close'] = heikinashi['close'] | |
| 81 | + dataframe['ha_high'] = heikinashi['high'] | |
| 82 | + dataframe['ha_low'] = heikinashi['low'] | |
| 83 | + | |
| 84 | + | |
| 85 | + # Set Up Bollinger Bands | |
| 86 | + mid, lower = bollinger_bands(ha_typical_price(dataframe), window_size=40, num_of_std=2) | |
| 87 | + dataframe['lower'] = lower | |
| 88 | + dataframe['mid'] = mid | |
| 89 | + | |
| 90 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 91 | + dataframe['closedelta'] = (dataframe['ha_close'] - dataframe['ha_close'].shift()).abs() | |
| 92 | + dataframe['tail'] = (dataframe['ha_close'] - dataframe['ha_low']).abs() | |
| 93 | + | |
| 94 | + dataframe['bb_lowerband'] = dataframe['lower'] | |
| 95 | + dataframe['bb_middleband'] = dataframe['mid'] | |
| 96 | + | |
| 97 | + dataframe['ema_fast'] = ta.EMA(dataframe['ha_close'], timeperiod=3) | |
| 98 | + dataframe['ema_slow'] = ta.EMA(dataframe['ha_close'], timeperiod=50) | |
| 99 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 100 | + dataframe['rocr'] = ta.ROCR(dataframe['ha_close'], timeperiod=28) | |
| 101 | + | |
| 102 | + rsi = ta.RSI(dataframe) | |
| 103 | + dataframe["rsi"] = rsi | |
| 104 | + rsi = 0.1 * (rsi - 50) | |
| 105 | + dataframe["fisher"] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 106 | + | |
| 107 | + inf_tf = '1h' | |
| 108 | + | |
| 109 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) | |
| 110 | + | |
| 111 | + inf_heikinashi = qtpylib.heikinashi(informative) | |
| 112 | + | |
| 113 | + informative['ha_close'] = inf_heikinashi['close'] | |
| 114 | + informative['rocr'] = ta.ROCR(informative['ha_close'], timeperiod=168) | |
| 115 | + | |
| 116 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) | |
| 117 | + | |
| 118 | + return dataframe | |
| 119 | + | |
| 120 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 121 | + params = self.buy_params | |
| 122 | + | |
| 123 | + dataframe.loc[ | |
| 124 | + ( | |
| 125 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 126 | + ) & | |
| 127 | + (( | |
| 128 | + (dataframe['lower'].shift().gt(0)) & | |
| 129 | + (dataframe['bbdelta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 130 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 131 | + (dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail'])) & | |
| 132 | + (dataframe['ha_close'].lt(dataframe['lower'].shift())) & | |
| 133 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift())) | |
| 134 | + ) | | |
| 135 | + ( | |
| 136 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 137 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['bb_lowerband']) | |
| 138 | + )), | |
| 139 | + 'buy' | |
| 140 | + ] = 1 | |
| 141 | + | |
| 142 | + return dataframe | |
| 143 | + | |
| 144 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 145 | + params = self.sell_params | |
| 146 | + | |
| 147 | + dataframe.loc[ | |
| 148 | + (dataframe['fisher'] > params['sell-fisher']) & | |
| 149 | + (dataframe['ha_high'].le(dataframe['ha_high'].shift(1))) & | |
| 150 | + (dataframe['ha_high'].shift(1).le(dataframe['ha_high'].shift(2))) & | |
| 151 | + (dataframe['ha_close'].le(dataframe['ha_close'].shift(1))) & | |
| 152 | + (dataframe['ema_fast'] > dataframe['ha_close']) & | |
| 153 | + ((dataframe['ha_close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 154 | + (dataframe['volume'] > 0) | |
| 155 | + , | |
| 156 | + 'sell' | |
| 157 | + ] = 1 | |
| 158 | + | |
| 159 | + return dataframe | |
| 160 | + | |
| 161 | +class ClucHAnix_ETH(ClucHAnix): | |
| 162 | + | |
| 163 | + # Buy hyperspace params: | |
| 164 | + buy_params = { | |
| 165 | + 'bbdelta-close': 0.01566, | |
| 166 | + 'bbdelta-tail': 0.8478, | |
| 167 | + 'close-bblower': 0.00998, | |
| 168 | + 'closedelta-close': 0.00614, | |
| 169 | + 'rocr-1h': 0.61579, | |
| 170 | + 'volume': 27 | |
| 171 | + } | |
| 172 | + | |
| 173 | + # Sell hyperspace params: | |
| 174 | + sell_params = { | |
| 175 | + 'sell-bbmiddle-close': 1.02894, | |
| 176 | + 'sell-fisher': 0.38414 | |
| 177 | + } | |
| 178 | + | |
| 179 | + # ROI table: | |
| 180 | + minimal_roi = { | |
| 181 | + "0": 0.14414, | |
| 182 | + "13": 0.10123, | |
| 183 | + "20": 0.03256, | |
| 184 | + "47": 0.0177, | |
| 185 | + "132": 0.01016, | |
| 186 | + "177": 0.00328, | |
| 187 | + "277": 0 | |
| 188 | + } | |
| 189 | + | |
| 190 | + # Stoploss: | |
| 191 | + stoploss = -0.02 | |
| 192 | + | |
| 193 | + # Trailing stop: | |
| 194 | + trailing_stop = True | |
| 195 | + trailing_stop_positive = 0.01 | |
| 196 | + trailing_stop_positive_offset = 0.0116 | |
| 197 | + trailing_only_offset_is_reached = False | |
| 198 | + | |
| 199 | +class ClucHAnix_BTC(ClucHAnix): | |
| 200 | + | |
| 201 | + # Buy hyperspace params: | |
| 202 | + buy_params = { | |
| 203 | + 'bbdelta-close': 0.01192, | |
| 204 | + 'bbdelta-tail': 0.96183, | |
| 205 | + 'close-bblower': 0.01212, | |
| 206 | + 'closedelta-close': 0.01039, | |
| 207 | + 'rocr-1h': 0.53422, | |
| 208 | + 'volume': 27 | |
| 209 | + } | |
| 210 | + | |
| 211 | + # Sell hyperspace params: | |
| 212 | + sell_params = { | |
| 213 | + 'sell-bbmiddle-close': 0.98016, | |
| 214 | + 'sell-fisher': 0.38414 | |
| 215 | + } | |
| 216 | + | |
| 217 | + # ROI table: | |
| 218 | + minimal_roi = { | |
| 219 | + "0": 0.19724, | |
| 220 | + "15": 0.14323, | |
| 221 | + "33": 0.07688, | |
| 222 | + "52": 0.03011, | |
| 223 | + "144": 0.01616, | |
| 224 | + "307": 0.0063, | |
| 225 | + "449": 0 | |
| 226 | + } | |
| 227 | + | |
| 228 | + # Stoploss: | |
| 229 | + stoploss = -0.11356 | |
| 230 | + | |
| 231 | + # Trailing stop: | |
| 232 | + trailing_stop = True | |
| 233 | + trailing_stop_positive = 0.01544 | |
| 234 | + trailing_stop_positive_offset = 0.11438 | |
| 235 | + trailing_only_offset_is_reached = False | |
| 236 | + | |
| 237 | +class ClucHAnix_USD(ClucHAnix): | |
| 238 | + | |
| 239 | + # Buy hyperspace params: | |
| 240 | + buy_params = { | |
| 241 | + 'bbdelta-close': 0.01806, | |
| 242 | + 'bbdelta-tail': 0.85912, | |
| 243 | + 'close-bblower': 0.01158, | |
| 244 | + 'closedelta-close': 0.01466, | |
| 245 | + 'rocr-1h': 0.51901, | |
| 246 | + 'volume': 26 | |
| 247 | + } | |
| 248 | + | |
| 249 | + # Sell hyperspace params: | |
| 250 | + sell_params = { | |
| 251 | + 'sell-bbmiddle-close': 0.96094, | |
| 252 | + 'sell-fisher': 0.38414 | |
| 253 | + } | |
| 254 | + | |
| 255 | + # ROI table: | |
| 256 | + minimal_roi = { | |
| 257 | + "0": 0.16139, | |
| 258 | + "11": 0.12608, | |
| 259 | + "54": 0.08335, | |
| 260 | + "140": 0.03423, | |
| 261 | + "197": 0.0123, | |
| 262 | + "325": 0.00649, | |
| 263 | + "417": 0 | |
| 264 | + } | |
| 265 | + | |
| 266 | + # Stoploss: | |
| 267 | + stoploss = -0.17654 | |
| 268 | + | |
| 269 | + # Trailing stop: | |
| 270 | + trailing_stop = True | |
| 271 | + trailing_stop_positive = 0.0101 | |
| 272 | + trailing_stop_positive_offset = 0.02952 | |
| 273 | + trailing_only_offset_is_reached = False | |
| No newline at the end of the file |
added strategies/old/ClucHAwerk.py +300 −0
| @@ -0,0 +1,300 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | + | |
| 8 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 9 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 10 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 11 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 12 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 13 | + | |
| 14 | +def ha_typical_price(bars): | |
| 15 | + res = (bars['ha_high'] + bars['ha_low'] + bars['ha_close']) / 3. | |
| 16 | + return Series(index=bars.index, data=res) | |
| 17 | + | |
| 18 | +class ClucHAwerk(IStrategy): | |
| 19 | + | |
| 20 | + """ | |
| 21 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 22 | + Can be overridden for specific sub-strategies (stake currencies) at the bottom. | |
| 23 | + """ | |
| 24 | + # Buy hyperspace params: | |
| 25 | + buy_params = { | |
| 26 | + 'bbdelta-close': 0.01021, | |
| 27 | + 'bbdelta-tail': 0.88118, | |
| 28 | + 'close-bblower': 0.0022, | |
| 29 | + 'closedelta-close': 0.00519, | |
| 30 | + 'rocr-1h': 0.50931, | |
| 31 | + 'volume': 35 | |
| 32 | + } | |
| 33 | + | |
| 34 | + # Sell hyperspace params: | |
| 35 | + sell_params = { | |
| 36 | + 'sell-bbmiddle-close': 1.01283, | |
| 37 | + 'sell-rocr-1h': 0.95269 | |
| 38 | + } | |
| 39 | + | |
| 40 | + # ROI table: | |
| 41 | + minimal_roi = { | |
| 42 | + "0": 0.11054, | |
| 43 | + "2": 0.05569, | |
| 44 | + "10": 0.03055, | |
| 45 | + "16": 0.02311, | |
| 46 | + "82": 0.01267, | |
| 47 | + "238": 0.00301, | |
| 48 | + "480": 0 | |
| 49 | + } | |
| 50 | + | |
| 51 | + # Stoploss: | |
| 52 | + stoploss = -0.02139 | |
| 53 | + | |
| 54 | + # Trailing stop: | |
| 55 | + trailing_stop = True | |
| 56 | + trailing_stop_positive = 0.09291 | |
| 57 | + trailing_stop_positive_offset = 0.10651 | |
| 58 | + trailing_only_offset_is_reached = False | |
| 59 | + | |
| 60 | + """ | |
| 61 | + END HYPEROPT | |
| 62 | + """ | |
| 63 | + | |
| 64 | + timeframe = '1m' | |
| 65 | + | |
| 66 | + startup_candle_count: int = 168 | |
| 67 | + | |
| 68 | + # Make sure these match or are not overridden in config | |
| 69 | + use_sell_signal = True | |
| 70 | + sell_profit_only = False | |
| 71 | + sell_profit_offset = 0.0 | |
| 72 | + ignore_roi_if_buy_signal = True | |
| 73 | + | |
| 74 | + def informative_pairs(self): | |
| 75 | + pairs = self.dp.current_whitelist() | |
| 76 | + informative_pairs = [(pair, '1h') for pair in pairs] | |
| 77 | + return informative_pairs | |
| 78 | + | |
| 79 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 80 | + # # Heikin Ashi Candles | |
| 81 | + heikinashi = qtpylib.heikinashi(dataframe) | |
| 82 | + dataframe['ha_open'] = heikinashi['open'] | |
| 83 | + dataframe['ha_close'] = heikinashi['close'] | |
| 84 | + dataframe['ha_high'] = heikinashi['high'] | |
| 85 | + dataframe['ha_low'] = heikinashi['low'] | |
| 86 | + | |
| 87 | + | |
| 88 | + # Set Up Bollinger Bands | |
| 89 | + mid, lower = bollinger_bands(dataframe['ha_close'], window_size=40, num_of_std=2) | |
| 90 | + dataframe['lower'] = lower | |
| 91 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 92 | + dataframe['closedelta'] = (dataframe['ha_close'] - dataframe['ha_close'].shift()).abs() | |
| 93 | + dataframe['tail'] = (dataframe['ha_close'] - dataframe['ha_low']).abs() | |
| 94 | + bollinger = qtpylib.bollinger_bands(ha_typical_price(dataframe), window=20, stds=2) | |
| 95 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 96 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 97 | + | |
| 98 | + dataframe['ema_slow'] = ta.EMA(dataframe['ha_close'], timeperiod=50) | |
| 99 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 100 | + dataframe['rocr'] = ta.ROCR(dataframe['ha_close'], timeperiod=28) | |
| 101 | + | |
| 102 | + inf_tf = '1h' | |
| 103 | + | |
| 104 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) | |
| 105 | + | |
| 106 | + inf_heikinashi = qtpylib.heikinashi(informative) | |
| 107 | + | |
| 108 | + informative['ha_close'] = inf_heikinashi['close'] | |
| 109 | + informative['rocr'] = ta.ROCR(informative['ha_close'], timeperiod=168) | |
| 110 | + | |
| 111 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) | |
| 112 | + | |
| 113 | + return dataframe | |
| 114 | + | |
| 115 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + params = self.buy_params | |
| 117 | + | |
| 118 | + dataframe.loc[ | |
| 119 | + ( | |
| 120 | + dataframe['rocr_1h'].gt(params['rocr-1h']) | |
| 121 | + ) & | |
| 122 | + (( | |
| 123 | + dataframe['lower'].shift().gt(0) & | |
| 124 | + dataframe['bbdelta'].gt(dataframe['ha_close'] * params['bbdelta-close']) & | |
| 125 | + dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close']) & | |
| 126 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['bbdelta-tail']) & | |
| 127 | + dataframe['ha_close'].lt(dataframe['lower'].shift()) & | |
| 128 | + dataframe['ha_close'].le(dataframe['ha_close'].shift()) | |
| 129 | + ) | | |
| 130 | + ( | |
| 131 | + (dataframe['ha_close'] < dataframe['ema_slow']) & | |
| 132 | + (dataframe['ha_close'] < params['close-bblower'] * dataframe['bb_lowerband']) & | |
| 133 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 134 | + )), | |
| 135 | + 'buy' | |
| 136 | + ] = 1 | |
| 137 | + | |
| 138 | + return dataframe | |
| 139 | + | |
| 140 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 141 | + params = self.sell_params | |
| 142 | + | |
| 143 | + dataframe.loc[ | |
| 144 | + dataframe['rocr_1h'].lt(params['sell-rocr-1h']) & | |
| 145 | + ((dataframe['ha_close'] * params['sell-bbmiddle-close']) > dataframe['bb_middleband']) & | |
| 146 | + (dataframe['volume'] > 0) | |
| 147 | + , | |
| 148 | + 'sell' | |
| 149 | + ] = 1 | |
| 150 | + | |
| 151 | + return dataframe | |
| 152 | + | |
| 153 | +class ClucHAwerk_ETH(ClucHAwerk): | |
| 154 | + | |
| 155 | + use_sell_signal = True | |
| 156 | + sell_profit_only = True | |
| 157 | + sell_profit_offset = 0.02 | |
| 158 | + ignore_roi_if_buy_signal = True | |
| 159 | + | |
| 160 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_ETH -e 500 --spaces buy --timeframe 1m --timerange 20210101- | |
| 161 | + # 483/500: 1880 trades. 1054/0/826 Wins/Draws/Losses. Avg profit 0.76%. Median profit 1.12%. Total profit 0.14286503 ETH ( 1426.37Σ%). Avg duration 45.3 min. Objective: -623.10584 | |
| 162 | + # Buy hyperspace params: | |
| 163 | + buy_params = { | |
| 164 | + 'bbdelta-close': 0.01566, | |
| 165 | + 'bbdelta-tail': 0.8478, | |
| 166 | + 'close-bblower': 0.00998, | |
| 167 | + 'closedelta-close': 0.00614, | |
| 168 | + 'rocr-1h': 0.61579, | |
| 169 | + 'volume': 27 | |
| 170 | + } | |
| 171 | + | |
| 172 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_ETH -e 500 --spaces sell --timeframe 1m --timerange 20210101- | |
| 173 | + # 210/500: 1881 trades. 1055/0/826 Wins/Draws/Losses. Avg profit 0.76%. Median profit 1.12%. Total profit 0.14316974 ETH ( 1429.41Σ%). Avg duration 45.3 min. Objective: -624.58371 | |
| 174 | + # Sell hyperspace params: | |
| 175 | + sell_params = { | |
| 176 | + 'sell-bbmiddle-close': 1.02894, | |
| 177 | + 'sell-rocr-1h': 0.94925 | |
| 178 | + } | |
| 179 | + | |
| 180 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_ETH -e 250 --spaces roi --timeframe 1m --timerange 20210101- | |
| 181 | + # 479/500: 1890 trades. 1209/0/681 Wins/Draws/Losses. Avg profit 0.86%. Median profit 0.74%. Total profit 0.16228997 ETH ( 1620.31Σ%). Avg duration 45.6 min. Objective: -258.91551 | |
| 182 | + # ROI table: | |
| 183 | + minimal_roi = { | |
| 184 | + "0": 0.14414, | |
| 185 | + "13": 0.10123, | |
| 186 | + "20": 0.03256, | |
| 187 | + "47": 0.0177, | |
| 188 | + "132": 0.01016, | |
| 189 | + "177": 0.00328, | |
| 190 | + "277": 0 | |
| 191 | + } | |
| 192 | + | |
| 193 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss OnlyProfitHyperOptLoss --strategy ClucHAwerk_ETH -e 500 --spaces stoploss --timeframe 1m --timerange 20210101- | |
| 194 | + # 292/500: 1890 trades. 1209/0/681 Wins/Draws/Losses. Avg profit 0.86%. Median profit 0.74%. Total profit 0.16251312 ETH ( 1622.53Σ%). Avg duration 45.6 min. Objective: -4.40843 | |
| 195 | + # Stoploss: | |
| 196 | + stoploss = -0.02 | |
| 197 | + | |
| 198 | + # hyperopt --config user_data/config-backtest-ETH.json --hyperopt ClucHAwerkHyperopt_ETH --hyperopt-loss OnlyProfitHyperOptLoss --strategy ClucHAwerk_ETH -e 500 --spaces trailing --timeframe 1m --timerange 20210101- | |
| 199 | + # 443/500: 1883 trades. 1193/0/690 Wins/Draws/Losses. Avg profit 0.86%. Median profit 0.76%. Total profit 0.16275524 ETH ( 1624.95Σ%). Avg duration 46.0 min. Objective: -4.41651 | |
| 200 | + # Trailing stop: | |
| 201 | + trailing_stop = True | |
| 202 | + trailing_stop_positive = 0.01018 | |
| 203 | + trailing_stop_positive_offset = 0.01203 | |
| 204 | + trailing_only_offset_is_reached = False | |
| 205 | + | |
| 206 | +class ClucHAwerk_BTC(ClucHAwerk): | |
| 207 | + | |
| 208 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_BTC -e 500 --spaces buy --timeframe 1m --timerange 20210101- | |
| 209 | + # 412/500: 572 trades. 505/17/50 Wins/Draws/Losses. Avg profit 1.80%. Median profit 2.27%. Total profit 0.01028714 BTC ( 1027.06Σ%). Avg duration 281.3 min. Objective: -152.09192 | |
| 210 | + # Buy hyperspace params: | |
| 211 | + buy_params = { | |
| 212 | + 'bbdelta-close': 0.01192, | |
| 213 | + 'bbdelta-tail': 0.96183, | |
| 214 | + 'close-bblower': 0.01212, | |
| 215 | + 'closedelta-close': 0.01039, | |
| 216 | + 'rocr-1h': 0.53422, | |
| 217 | + 'volume': 27 | |
| 218 | + } | |
| 219 | + | |
| 220 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_BTC -e 500 --spaces sell --timeframe 1m --timerange 20210101- | |
| 221 | + # 284/500: 575 trades. 508/17/50 Wins/Draws/Losses. Avg profit 1.80%. Median profit 2.25%. Total profit 0.01036281 BTC ( 1034.62Σ%). Avg duration 279.4 min. Objective: -100.84858 | |
| 222 | + # Sell hyperspace params: | |
| 223 | + sell_params = { | |
| 224 | + 'sell-bbmiddle-close': 0.98016, | |
| 225 | + 'sell-rocr-1h': 0.86823 | |
| 226 | + } | |
| 227 | + | |
| 228 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss OnlyProfitHyperOptLoss --strategy ClucHAwerk_BTC -e 500 --spaces roi --timeframe 1m --timerange 20210101- | |
| 229 | + # 304/500: 627 trades. 563/10/54 Wins/Draws/Losses. Avg profit 1.71%. Median profit 2.18%. Total profit 0.01075130 BTC ( 1073.41Σ%). Avg duration 248.0 min. Objective: -2.57804 | |
| 230 | + # ROI table: | |
| 231 | + minimal_roi = { | |
| 232 | + "0": 0.18105, | |
| 233 | + "9": 0.10391, | |
| 234 | + "49": 0.0447, | |
| 235 | + "53": 0.02747, | |
| 236 | + "141": 0.01265, | |
| 237 | + "312": 0.00499, | |
| 238 | + "466": 0 | |
| 239 | + } | |
| 240 | + | |
| 241 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_BTC -e 250 --spaces stoploss --timeframe 1m --timerange 20210101- | |
| 242 | + # 192/250: 568 trades. 505/17/46 Wins/Draws/Losses. Avg profit 1.80%. Median profit 2.18%. Total profit 0.01023698 BTC ( 1022.05Σ%). Avg duration 280.1 min. Objective: -99.33155 | |
| 243 | + # Stoploss: | |
| 244 | + stoploss = -0.11356 | |
| 245 | + | |
| 246 | + # hyperopt --config user_data/config-backtest-BTC.json --hyperopt ClucHAwerkHyperopt_BTC --hyperopt-loss OnlyProfitHyperOptLoss --strategy ClucHAwerk_BTC -e 500 --spaces trailing --timeframe 1m --timerange 20210101- | |
| 247 | + # 313/500: 637 trades. 573/10/54 Wins/Draws/Losses. Avg profit 1.69%. Median profit 2.50%. Total profit 0.01079683 BTC ( 1077.96Σ%). Avg duration 242.7 min. Objective: -2.59319 | |
| 248 | + # Trailing stop: | |
| 249 | + trailing_stop = True | |
| 250 | + trailing_stop_positive = 0.01008 | |
| 251 | + trailing_stop_positive_offset = 0.04585 | |
| 252 | + trailing_only_offset_is_reached = False | |
| 253 | + | |
| 254 | +class ClucHAwerk_USD(ClucHAwerk): | |
| 255 | + | |
| 256 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces buy --timeframe 1m --timerange 20210101- | |
| 257 | + # 470/500: 680 trades. 631/27/22 Wins/Draws/Losses. Avg profit 2.91%. Median profit 2.93%. Total profit 991.61804628 USD ( 1980.07Σ%). Avg duration 184.2 min. Objective: -186.95550 | |
| 258 | + # Buy hyperspace params: | |
| 259 | + buy_params = { | |
| 260 | + 'bbdelta-close': 0.01806, | |
| 261 | + 'bbdelta-tail': 0.85912, | |
| 262 | + 'close-bblower': 0.01158, | |
| 263 | + 'closedelta-close': 0.01466, | |
| 264 | + 'rocr-1h': 0.51901, | |
| 265 | + 'volume': 26 | |
| 266 | + } | |
| 267 | + | |
| 268 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss SortinoHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces sell --timeframe 1m --timerange 20210101- | |
| 269 | + # 1/500: 679 trades. 630/27/22 Wins/Draws/Losses. Avg profit 2.90%. Median profit 2.93%. Total profit 986.25885773 USD ( 1969.37Σ%). Avg duration 184.6 min. Objective: -277.19845 | |
| 270 | + # Sell hyperspace params: | |
| 271 | + sell_params = { | |
| 272 | + 'sell-bbmiddle-close': 1.06163, | |
| 273 | + 'sell-rocr-1h': 0.63285 | |
| 274 | + } | |
| 275 | + | |
| 276 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss OnlyProfitHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces roi --timeframe 1m --timerange 20210101- | |
| 277 | + # 334/500: 715 trades. 674/22/19 Wins/Draws/Losses. Avg profit 2.90%. Median profit 2.80%. Total profit 1037.85838537 USD ( 2072.40Σ%). Avg duration 166.5 min. Objective: -5.90800 | |
| 278 | + # ROI table: | |
| 279 | + minimal_roi = { | |
| 280 | + "0": 0.19315, | |
| 281 | + "13": 0.13189, | |
| 282 | + "24": 0.08358, | |
| 283 | + "103": 0.03894, | |
| 284 | + "148": 0.0148, | |
| 285 | + "201": 0.00506, | |
| 286 | + "447": 0 | |
| 287 | + } | |
| 288 | + | |
| 289 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss SharpeHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces stoploss --timeframe 1m --timerange 20210101- | |
| 290 | + # 352/500: 729 trades. 688/22/19 Wins/Draws/Losses. Avg profit 2.91%. Median profit 2.79%. Total profit 1060.61902930 USD ( 2117.85Σ%). Avg duration 167.6 min. Objective: -198.19711 | |
| 291 | + # Stoploss: | |
| 292 | + stoploss = -0.17725 | |
| 293 | + | |
| 294 | + # hyperopt --config user_data/config-backtest-USD.json --hyperopt ClucHAwerkHyperopt_USD --hyperopt-loss OnlyProfitHyperOptLoss --strategy ClucHAwerk_USD -e 500 --spaces trailing --timeframe 1m --timerange 20210101- | |
| 295 | + # 366/500: 730 trades. 689/22/19 Wins/Draws/Losses. Avg profit 2.91%. Median profit 2.80%. Total profit 1062.06091250 USD ( 2120.73Σ%). Avg duration 167.3 min. Objective: -6.06910 | |
| 296 | + # Trailing stop: | |
| 297 | + trailing_stop = True | |
| 298 | + trailing_stop_positive = 0.01 | |
| 299 | + trailing_stop_positive_offset = 0.02946 | |
| 300 | + trailing_only_offset_is_reached = False | |
| No newline at the end of the file |
added strategies/old/Cluckie.py +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from datetime import datetime | |
| 8 | +from freqtrade.persistence import Trade | |
| 9 | + | |
| 10 | +class Cluckie(IStrategy): | |
| 11 | + | |
| 12 | + """ | |
| 13 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 14 | + """ | |
| 15 | + # Buy hyperspace params: | |
| 16 | + buy_params = { | |
| 17 | + 'bbdelta-close': 0.01118, | |
| 18 | + 'bbdelta-tail': 0.88481, | |
| 19 | + 'close-bblower': 0.00396, | |
| 20 | + 'closedelta-close': 0.01232, | |
| 21 | + 'fisher': -0.8167, | |
| 22 | + 'volume': 29 | |
| 23 | + } | |
| 24 | + | |
| 25 | + # Sell hyperspace params: | |
| 26 | + sell_params = { | |
| 27 | + 'sell-adx': 70, | |
| 28 | + 'sell-fisher': 0.95954 | |
| 29 | + } | |
| 30 | + | |
| 31 | + # ROI table: | |
| 32 | + minimal_roi = { | |
| 33 | + "0": 100 | |
| 34 | + } | |
| 35 | + | |
| 36 | + # Stoploss: | |
| 37 | + stoploss = -0.015 | |
| 38 | + | |
| 39 | + """ | |
| 40 | + END HYPEROPT | |
| 41 | + """ | |
| 42 | + | |
| 43 | + timeframe = '5m' | |
| 44 | + | |
| 45 | + | |
| 46 | + # Make sure these match or are not overridden in config | |
| 47 | + use_sell_signal = True | |
| 48 | + #sell_profit_only = True | |
| 49 | + #sell_profit_offset = 0.01 | |
| 50 | + ignore_roi_if_buy_signal = True | |
| 51 | + | |
| 52 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 53 | + ob = self.dp.orderbook(pair, 1) | |
| 54 | + current_price = ob['bids'][0][0] | |
| 55 | + # Cancel buy order if price is more than 1% above the order. | |
| 56 | + if current_price > order['price'] * 1.01: | |
| 57 | + return True | |
| 58 | + return False | |
| 59 | + | |
| 60 | + | |
| 61 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 62 | + ob = self.dp.orderbook(pair, 1) | |
| 63 | + current_price = ob['asks'][0][0] | |
| 64 | + # Cancel sell order if price is more than 1% below the order. | |
| 65 | + if current_price < order['price'] * 0.99: | |
| 66 | + return True | |
| 67 | + return False | |
| 68 | + | |
| 69 | + | |
| 70 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 71 | + | |
| 72 | + # Set Up Bollinger Bands | |
| 73 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'], timeperiod=40) | |
| 74 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(dataframe), timeperiod=20) | |
| 75 | + | |
| 76 | + # only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 77 | + dataframe['lower-bb1'] = lower_bb1 | |
| 78 | + dataframe['lower-bb2'] = lower_bb2 | |
| 79 | + dataframe['mid-bb2'] = mid_bb2 | |
| 80 | + | |
| 81 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 82 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 83 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 84 | + | |
| 85 | + dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48) | |
| 86 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 87 | + | |
| 88 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) | |
| 89 | + | |
| 90 | + # # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) | |
| 91 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 92 | + dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 93 | + | |
| 94 | + dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) | |
| 95 | + dataframe['adx'] = ta.ADX(dataframe) | |
| 96 | + | |
| 97 | + return dataframe | |
| 98 | + | |
| 99 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 100 | + params = self.buy_params | |
| 101 | + | |
| 102 | + dataframe.loc[ | |
| 103 | + ( | |
| 104 | + dataframe['fisher-rsi'].lt(params['fisher']) | |
| 105 | + ) & | |
| 106 | + (( | |
| 107 | + (dataframe['bb1-delta'].gt(dataframe['close'] * params['bbdelta-close'])) & | |
| 108 | + (dataframe['closedelta'].gt(dataframe['close'] * params['closedelta-close'])) & | |
| 109 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 110 | + (dataframe['close'].lt(dataframe['lower-bb1'].shift())) & | |
| 111 | + (dataframe['close'].le(dataframe['close'].shift())) & | |
| 112 | + (dataframe['tema'] > dataframe['tema'].shift(1)) | |
| 113 | + ) | | |
| 114 | + ( | |
| 115 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 116 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 117 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 118 | + )), | |
| 119 | + 'buy' | |
| 120 | + ] = 1 | |
| 121 | + | |
| 122 | + return dataframe | |
| 123 | + | |
| 124 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 125 | + params = self.sell_params | |
| 126 | + | |
| 127 | + dataframe.loc[ | |
| 128 | + ( | |
| 129 | + (dataframe['adx'] > params['sell-adx']) & | |
| 130 | + (dataframe['tema'] > dataframe['mid-bb2']) & | |
| 131 | + (dataframe['tema'] < dataframe['tema'].shift(1)) & | |
| 132 | + (dataframe['fisher-rsi'].gt(params['sell-fisher'])) | |
| 133 | + ) | |
| 134 | + , | |
| 135 | + 'sell' | |
| 136 | + ] = 1 | |
| 137 | + | |
| 138 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/Enchilada.py +225 −0
| @@ -0,0 +1,225 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import technical.tradingview as tv | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | + | |
| 12 | +""" | |
| 13 | +TODO: | |
| 14 | + - Better buy signal. | |
| 15 | + - Potentially leverage external data sources in our signals (cryptobubbles, etc.) | |
| 16 | +""" | |
| 17 | + | |
| 18 | +class Enchilada(IStrategy): | |
| 19 | + | |
| 20 | + timeframe = '5m' | |
| 21 | + inf_timeframe = '1h' | |
| 22 | + | |
| 23 | + # ROI table: | |
| 24 | + minimal_roi = { | |
| 25 | + "0": 0.15, | |
| 26 | + "5": 0.025, | |
| 27 | + "10": 0.015 | |
| 28 | + } | |
| 29 | + | |
| 30 | + # Stoploss: | |
| 31 | + stoploss = -0.085 | |
| 32 | + | |
| 33 | + use_sell_signal = True | |
| 34 | + sell_profit_only = False | |
| 35 | + ignore_roi_if_buy_signal = True | |
| 36 | + | |
| 37 | + startup_candle_count: int = 24 | |
| 38 | + | |
| 39 | + custom_trade_info = {} | |
| 40 | + | |
| 41 | + def informative_pairs(self): | |
| 42 | + pairs = self.dp.current_whitelist() | |
| 43 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 44 | + return informative_pairs | |
| 45 | + | |
| 46 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 47 | + | |
| 48 | + # Misc calculations regarding existing open positions | |
| 49 | + self.custom_trade_info[metadata['pair']] = trade_data = {} | |
| 50 | + trade_data['active_trade'] = trade_data['other_trades'] = False | |
| 51 | + | |
| 52 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 53 | + | |
| 54 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 55 | + other_trades = Trade.get_trades([Trade.pair != metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 56 | + | |
| 57 | + if active_trade: | |
| 58 | + trade_data['active_trade'] = True | |
| 59 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(rate=self.get_current_price(metadata['pair'])) | |
| 60 | + trade_data['peak_profit'] = active_trade[0].calc_profit_ratio(rate=active_trade[0].max_rate) | |
| 61 | + trade_data['current_peak_ratio'] = (trade_data['current_profit'] / trade_data['peak_profit']) | |
| 62 | + | |
| 63 | + if other_trades: | |
| 64 | + trade_data['other_trades'] = True | |
| 65 | + total_other_profit = sum(trade.calc_profit_ratio(rate=self.get_current_price(trade.pair)) for trade in other_trades) | |
| 66 | + trade_data['avg_other_profit'] = total_other_profit / len(other_trades) | |
| 67 | + | |
| 68 | + self.custom_trade_info[metadata['pair']] = trade_data | |
| 69 | + | |
| 70 | + # Set up other indicators | |
| 71 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 72 | + dataframe['rmi-slow'] = RMI(dataframe, length=20, mom=5) | |
| 73 | + dataframe['rmi-fast'] = RMI(dataframe, length=9, mom=3) | |
| 74 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 75 | + | |
| 76 | + # Trend calculations | |
| 77 | + dataframe['max'] = dataframe['high'].rolling(12).max() | |
| 78 | + dataframe['min'] = dataframe['low'].rolling(12).min() | |
| 79 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 80 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 81 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 82 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 83 | + | |
| 84 | + # Consensus dashboard based on default timeframe and informative pair | |
| 85 | + # Example: https://www.tradingview.com/symbols/BTCUSD/technicals/ | |
| 86 | + # Code: https://github.com/freqtrade/technical/blob/master/technical/tradingview/__init__.py | |
| 87 | + | |
| 88 | + consensus = tv.SummaryConsensus(dataframe).score() | |
| 89 | + dataframe['tv-consensus-sell'] = consensus['sell_agreement'] | |
| 90 | + dataframe['tv-consensus-buy'] = consensus['buy_agreement'] | |
| 91 | + | |
| 92 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 93 | + consensus_inf = tv.SummaryConsensus(informative).score() | |
| 94 | + informative['tv-consensus-sell'] = consensus_inf['sell_agreement'] | |
| 95 | + informative['tv-consensus-buy'] = consensus_inf['buy_agreement'] | |
| 96 | + | |
| 97 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 98 | + | |
| 99 | + # dataframe.to_csv('user_data/foo.csv') | |
| 100 | + | |
| 101 | + return dataframe | |
| 102 | + | |
| 103 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 104 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 105 | + conditions = [] | |
| 106 | + | |
| 107 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 108 | + # when this buy signal is not present a sell can happen according to ROI table | |
| 109 | + if trade_data['active_trade']: | |
| 110 | + conditions.append(trade_data['current_peak_ratio'] > 0.8) | |
| 111 | + conditions.append(dataframe['rmi-slow'] >= 60) | |
| 112 | + | |
| 113 | + # Normal buy triggers that apply to new trades we want to enter | |
| 114 | + else: | |
| 115 | + # if bull market: | |
| 116 | + conditions.append( | |
| 117 | + (dataframe['tv-consensus-buy'] > X) & | |
| 118 | + (dataframe['tv-consensus-buy_1h'] > X) & | |
| 119 | + (dataframe['up_trend'] == 1) & | |
| 120 | + (dataframe['rmi-slow'] >= 55) & | |
| 121 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * 30)) & | |
| 122 | + | |
| 123 | + (dataframe['rmi-slow'] >= dataframe['rmi-slow'].rolling(3).mean()) & | |
| 124 | + (dataframe['close'] > dataframe['close'].shift()) & | |
| 125 | + (dataframe['close'].shift() > dataframe['close'].shift(2)) & | |
| 126 | + (dataframe['sar'] < dataframe['close']) & | |
| 127 | + (dataframe['sar'].shift() < dataframe['close'].shift()) | |
| 128 | + ) | |
| 129 | + # if bear market: | |
| 130 | + | |
| 131 | + # applies to both new buys and persisting buy signal | |
| 132 | + conditions.append(dataframe['volume'].gt(0)) | |
| 133 | + | |
| 134 | + if conditions: | |
| 135 | + dataframe.loc[ | |
| 136 | + reduce(lambda x, y: x & y, conditions), | |
| 137 | + 'buy'] = 1 | |
| 138 | + | |
| 139 | + return dataframe | |
| 140 | + | |
| 141 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 142 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 143 | + conditions = [] | |
| 144 | + | |
| 145 | + # if we are in an active trade for this pair | |
| 146 | + if trade_data['active_trade']: | |
| 147 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 148 | + conditions.append( | |
| 149 | + (trade_data['current_profit'] < 0) & | |
| 150 | + (trade_data['current_profit'] > self.stoploss) & | |
| 151 | + (dataframe['dn_trend'] == 1) & | |
| 152 | + (dataframe['rmi-fast'] < 50) & | |
| 153 | + (dataframe['volume'].gt(0)) | |
| 154 | + ) | |
| 155 | + | |
| 156 | + # if there are other open trades in addition to this one, consider the average profit | |
| 157 | + # across them all (not including this one), don't sell if entire market is down big and wait for recovery | |
| 158 | + if trade_data['other_trades']: | |
| 159 | + conditions.append(trade_data['avg_other_profit'] >= -0.005) | |
| 160 | + | |
| 161 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 162 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 163 | + # clogging up the charts and not having one leads the bot to crash | |
| 164 | + else: | |
| 165 | + conditions.append(dataframe['volume'].lt(0)) | |
| 166 | + | |
| 167 | + if conditions: | |
| 168 | + dataframe.loc[ | |
| 169 | + reduce(lambda x, y: x & y, conditions), | |
| 170 | + 'sell'] = 1 | |
| 171 | + | |
| 172 | + return dataframe | |
| 173 | + | |
| 174 | + """ | |
| 175 | + Custom methods | |
| 176 | + """ | |
| 177 | + def get_current_price(self, pair: str, side="asks") -> float: | |
| 178 | + ob = self.dp.orderbook(pair, 1) | |
| 179 | + current_price = ob[side][0][0] | |
| 180 | + | |
| 181 | + return current_price | |
| 182 | + | |
| 183 | + """ | |
| 184 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 185 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 186 | + """ | |
| 187 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 188 | + ob = self.dp.orderbook(pair, 1) | |
| 189 | + current_price = ob['bids'][0][0] | |
| 190 | + # Cancel buy order if price is more than 1% above the order. | |
| 191 | + if current_price > order['price'] * 1.01: | |
| 192 | + return True | |
| 193 | + return False | |
| 194 | + | |
| 195 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 196 | + ob = self.dp.orderbook(pair, 1) | |
| 197 | + current_price = ob['asks'][0][0] | |
| 198 | + # Cancel sell order if price is more than 1% below the order. | |
| 199 | + if current_price < order['price'] * 0.99: | |
| 200 | + return True | |
| 201 | + return False | |
| 202 | + | |
| 203 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 204 | + ob = self.dp.orderbook(pair, 1) | |
| 205 | + current_price = ob['asks'][0][0] | |
| 206 | + # Cancel buy order if price is more than 1% above the order. | |
| 207 | + if current_price > rate * 1.01: | |
| 208 | + return False | |
| 209 | + return True | |
| 210 | + | |
| 211 | +class Enchilada_Slow(Enchilada): | |
| 212 | + | |
| 213 | + timeframe = '1h' | |
| 214 | + inf_timeframe = '4h' | |
| 215 | + | |
| 216 | + # ROI table: | |
| 217 | + minimal_roi = { | |
| 218 | + "0": 0.15, | |
| 219 | + "30": 0.05, | |
| 220 | + "60": 0.025, | |
| 221 | + "120": 0.015 | |
| 222 | + } | |
| 223 | + | |
| 224 | + # Stoploss: | |
| 225 | + stoploss = -0.085 |
added strategies/old/Fakebuy.py +249 −0
| @@ -0,0 +1,249 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | +from statistics import mean | |
| 12 | + | |
| 13 | +""" | |
| 14 | +TODO: | |
| 15 | + - Better buy signal. | |
| 16 | + - Potentially leverage an external data source? | |
| 17 | +""" | |
| 18 | + | |
| 19 | +def bollinger_bands(stock_price, window_size, num_of_std): | |
| 20 | + rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 21 | + rolling_std = stock_price.rolling(window=window_size).std() | |
| 22 | + lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 23 | + return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 24 | + | |
| 25 | +class Fakebuy(IStrategy): | |
| 26 | + | |
| 27 | + timeframe = '5m' | |
| 28 | + inf_timeframe = '1h' | |
| 29 | + | |
| 30 | + buy_params = { | |
| 31 | + 'bbdelta-close': 0.01697, | |
| 32 | + 'bbdelta-tail': 0.85522, | |
| 33 | + 'close-bblower': 0.01167, | |
| 34 | + 'closedelta-close': 0.00513, | |
| 35 | + 'rocr-1h': 0.54614, | |
| 36 | + 'volume': 32 | |
| 37 | + } | |
| 38 | + | |
| 39 | + # ROI table: | |
| 40 | + minimal_roi = { | |
| 41 | + "0": 0.15, | |
| 42 | + "5": 0.025, | |
| 43 | + "10": 0.015, | |
| 44 | + "30": 0.005 | |
| 45 | + } | |
| 46 | + | |
| 47 | + # Stoploss: | |
| 48 | + stoploss = -0.085 | |
| 49 | + | |
| 50 | + use_sell_signal = True | |
| 51 | + sell_profit_only = False | |
| 52 | + ignore_roi_if_buy_signal = True | |
| 53 | + | |
| 54 | + startup_candle_count: int = 168 | |
| 55 | + | |
| 56 | + custom_trade_info = {} | |
| 57 | + | |
| 58 | + def informative_pairs(self): | |
| 59 | + pairs = self.dp.current_whitelist() | |
| 60 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 61 | + return informative_pairs | |
| 62 | + | |
| 63 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 64 | + | |
| 65 | + # Misc. calculations regarding existing open positions (reset on every loop iteration) | |
| 66 | + self.custom_trade_info[metadata['pair']] = trade_data = {} | |
| 67 | + trade_data['active_trade'] = trade_data['other_trades'] = False | |
| 68 | + | |
| 69 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 70 | + | |
| 71 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 72 | + other_trades = Trade.get_trades([Trade.pair != metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 73 | + | |
| 74 | + if active_trade: | |
| 75 | + current_rate = self.get_current_price(metadata['pair']) | |
| 76 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 77 | + trade_data['active_trade'] = True | |
| 78 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 79 | + trade_data['peak_profit'] = active_trade[0].calc_profit_ratio(active_trade[0].max_rate) | |
| 80 | + | |
| 81 | + if other_trades: | |
| 82 | + trade_data['other_trades'] = True | |
| 83 | + total_other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair)) for trade in other_trades) | |
| 84 | + trade_data['avg_other_profit'] = mean(total_other_profit) | |
| 85 | + | |
| 86 | + self.custom_trade_info[metadata['pair']] = trade_data | |
| 87 | + | |
| 88 | + # Set up Bollinger Bands | |
| 89 | + mid, lower = bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 90 | + dataframe['lower'] = lower | |
| 91 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 92 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 93 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 94 | + | |
| 95 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) | |
| 96 | + dataframe['bb-lowerband'] = bollinger['lower'] | |
| 97 | + dataframe['bb-middleband'] = bollinger['mid'] | |
| 98 | + | |
| 99 | + # Set up other indicators | |
| 100 | + dataframe['volume-mean-slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 101 | + dataframe['rmi-slow'] = RMI(dataframe, length=20, mom=5) | |
| 102 | + dataframe['rmi-fast'] = RMI(dataframe, length=9, mom=3) | |
| 103 | + dataframe['rocr'] = ta.ROCR(dataframe, timeperiod=28) | |
| 104 | + dataframe['ema-slow'] = ta.EMA(dataframe, timeperiod=50) | |
| 105 | + | |
| 106 | + # Trend Calculations | |
| 107 | + dataframe['max'] = dataframe['high'].rolling(12).max() | |
| 108 | + dataframe['min'] = dataframe['low'].rolling(12).min() | |
| 109 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 110 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 111 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 112 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 113 | + | |
| 114 | + # Informative Pair Indicators | |
| 115 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 116 | + informative['rocr'] = ta.ROCR(informative, timeperiod=168) | |
| 117 | + | |
| 118 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 119 | + | |
| 120 | + return dataframe | |
| 121 | + | |
| 122 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 123 | + params = self.buy_params | |
| 124 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 125 | + conditions = [] | |
| 126 | + | |
| 127 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 128 | + # when this buy signal is not present a sell can happen according to ROI table | |
| 129 | + if trade_data['active_trade']: | |
| 130 | + if (trade_data['peak_profit'] > 0): | |
| 131 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * 0.8)) | |
| 132 | + conditions.append(dataframe['rmi-slow'] >= 60) | |
| 133 | + | |
| 134 | + # Normal buy triggers that apply to new trades we want to enter | |
| 135 | + else: | |
| 136 | + dataframe.loc[ | |
| 137 | + ( | |
| 138 | + (dataframe['rocr_1h'] > params['rocr-1h']) | |
| 139 | + ) & | |
| 140 | + (( | |
| 141 | + (dataframe['lower'].shift() > 0) & | |
| 142 | + (dataframe['bbdelta'] > (dataframe['close'] * params['bbdelta-close'])) & | |
| 143 | + (dataframe['closedelta'] > (dataframe['close'] * params['closedelta-close'])) & | |
| 144 | + (dataframe['tail'] < (dataframe['bbdelta'] * params['bbdelta-tail'])) & | |
| 145 | + (dataframe['close'] < dataframe['lower'].shift()) & | |
| 146 | + (dataframe['close'] <= dataframe['close'].shift()) | |
| 147 | + ) | | |
| 148 | + ( | |
| 149 | + (dataframe['close'] < dataframe['ema-slow']) & | |
| 150 | + (dataframe['close'] < params['close-bblower'] * dataframe['bb-lowerband']) & | |
| 151 | + (dataframe['volume'] < (dataframe['volume-mean-slow'].shift(1) * params['volume'])) | |
| 152 | + )), | |
| 153 | + 'fake_buy' | |
| 154 | + ] = 1 | |
| 155 | + | |
| 156 | + conditions.append(dataframe['fake_buy'].shift(1).eq(1)) | |
| 157 | + conditions.append(dataframe['fake_buy'].eq(1)) | |
| 158 | + | |
| 159 | + # applies to both new buys and persisting buy signal | |
| 160 | + conditions.append(dataframe['volume'].gt(0)) | |
| 161 | + | |
| 162 | + if conditions: | |
| 163 | + dataframe.loc[ | |
| 164 | + reduce(lambda x, y: x & y, conditions), | |
| 165 | + 'buy'] = 1 | |
| 166 | + | |
| 167 | + return dataframe | |
| 168 | + | |
| 169 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 170 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 171 | + conditions = [] | |
| 172 | + | |
| 173 | + # if we are in an active trade for this pair | |
| 174 | + if trade_data['active_trade']: | |
| 175 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 176 | + conditions.append( | |
| 177 | + (trade_data['current_profit'] < 0) & | |
| 178 | + (trade_data['current_profit'] > self.stoploss) & | |
| 179 | + (dataframe['dn_trend'] == 1) & | |
| 180 | + (dataframe['rmi-fast'] < 50) & | |
| 181 | + (dataframe['volume'].gt(0)) | |
| 182 | + ) | |
| 183 | + | |
| 184 | + # if there are other open trades in addition to this one, consider the average profit | |
| 185 | + # across them all (not including this one), don't sell if entire market is down big and wait for recovery | |
| 186 | + if trade_data['other_trades']: | |
| 187 | + conditions.append(trade_data['avg_other_profit'] >= -0.005) | |
| 188 | + | |
| 189 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 190 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 191 | + # clogging up the charts and not having one leads the bot to crash | |
| 192 | + else: | |
| 193 | + conditions.append(dataframe['volume'].lt(0)) | |
| 194 | + | |
| 195 | + if conditions: | |
| 196 | + dataframe.loc[ | |
| 197 | + reduce(lambda x, y: x & y, conditions), | |
| 198 | + 'sell'] = 1 | |
| 199 | + | |
| 200 | + return dataframe | |
| 201 | + | |
| 202 | + """ | |
| 203 | + Custom methods | |
| 204 | + """ | |
| 205 | + def get_current_price(self, pair: str) -> float: | |
| 206 | + """ | |
| 207 | + # Using ticker seems significantly faster than orderbook. | |
| 208 | + side = "asks" | |
| 209 | + if (self.config['ask_strategy']['price_side'] == "bid"): | |
| 210 | + side = "bids" | |
| 211 | + | |
| 212 | + ob = self.dp.orderbook(pair, 1) | |
| 213 | + current_price = ob[side][0][0] | |
| 214 | + """ | |
| 215 | + | |
| 216 | + ticker = self.dp.ticker(pair) | |
| 217 | + current_price = ticker['last'] | |
| 218 | + | |
| 219 | + return current_price | |
| 220 | + | |
| 221 | + """ | |
| 222 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 223 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 224 | + """ | |
| 225 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 226 | + ob = self.dp.orderbook(pair, 1) | |
| 227 | + current_price = ob['bids'][0][0] | |
| 228 | + # Cancel buy order if price is more than 1% above the order. | |
| 229 | + if current_price > order['price'] * 1.01: | |
| 230 | + return True | |
| 231 | + return False | |
| 232 | + | |
| 233 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 234 | + ob = self.dp.orderbook(pair, 1) | |
| 235 | + current_price = ob['asks'][0][0] | |
| 236 | + # Cancel sell order if price is more than 1% below the order. | |
| 237 | + if current_price < order['price'] * 0.99: | |
| 238 | + return True | |
| 239 | + return False | |
| 240 | + | |
| 241 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 242 | + ob = self.dp.orderbook(pair, 1) | |
| 243 | + current_price = ob['asks'][0][0] | |
| 244 | + # Cancel buy order if price is more than 1% above the order. | |
| 245 | + if current_price > rate * 1.01: | |
| 246 | + return False | |
| 247 | + return True | |
| 248 | + | |
| 249 | + |
added strategies/old/FisherHull.py +91 −0
| @@ -0,0 +1,91 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from pandas import DataFrame, DatetimeIndex, merge, Series | |
| 6 | +from technical.indicators import hull_moving_average | |
| 7 | + | |
| 8 | +""" | |
| 9 | +def hull_moving_average(dataframe, period, field='close') -> ndarray: | |
| 10 | + from pyti.hull_moving_average import hull_moving_average as hma | |
| 11 | + return hma(dataframe[field], period) | |
| 12 | +""" | |
| 13 | + | |
| 14 | +class YOLO(IStrategy): | |
| 15 | + | |
| 16 | + # Buy hyperspace params: | |
| 17 | + buy_params = { | |
| 18 | + | |
| 19 | + } | |
| 20 | + | |
| 21 | + # Sell hyperspace params: | |
| 22 | + sell_params = { | |
| 23 | + | |
| 24 | + } | |
| 25 | + | |
| 26 | + # ROI table: | |
| 27 | + minimal_roi = { | |
| 28 | + '0': 1000 | |
| 29 | + } | |
| 30 | + | |
| 31 | + # Stoploss: | |
| 32 | + stoploss = -0.27654 | |
| 33 | + | |
| 34 | + # Trailing stop: | |
| 35 | + trailing_stop = True | |
| 36 | + trailing_stop_positive = 0.32606 | |
| 37 | + trailing_stop_positive_offset = 0.33314 | |
| 38 | + trailing_only_offset_is_reached = True | |
| 39 | + """ | |
| 40 | + END HYPEROPT | |
| 41 | + """ | |
| 42 | + | |
| 43 | + timeframe = '1m' | |
| 44 | + | |
| 45 | + use_sell_signal = False | |
| 46 | + sell_profit_only = False | |
| 47 | + ignore_roi_if_buy_signal = True | |
| 48 | + | |
| 49 | + | |
| 50 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 51 | + | |
| 52 | + dataframe['hma'] = hull_moving_average(dataframe, 14, 'close') | |
| 53 | + dataframe['cci'] = ta.CCI(dataframe, timeperiod=14) | |
| 54 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) | |
| 55 | + | |
| 56 | + | |
| 57 | + rsi = 0.1 * (dataframe['rsi'] - 50) | |
| 58 | + dataframe['fisher_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) | |
| 59 | + | |
| 60 | + return dataframe | |
| 61 | + | |
| 62 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + dataframe.loc[ | |
| 65 | + | |
| 66 | + ( | |
| 67 | + (dataframe['hma'] < dataframe['hma'].shift()) & | |
| 68 | + (dataframe['cci'] <= -50.0) & | |
| 69 | + (dataframe['fisher_rsi'] < -0.5) & | |
| 70 | + (dataframe['volume'] > 0) | |
| 71 | + ) | |
| 72 | + | |
| 73 | + , | |
| 74 | + 'buy' | |
| 75 | + ] = 1 | |
| 76 | + | |
| 77 | + return dataframe | |
| 78 | + | |
| 79 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 80 | + | |
| 81 | + dataframe.loc[ | |
| 82 | + ( | |
| 83 | + (dataframe['hma'] > dataframe['hma'].shift()) & | |
| 84 | + (dataframe['cci'] >= 100.0) & | |
| 85 | + (dataframe['fisher_rsi'] > 0.5) & | |
| 86 | + (dataframe['volume'] > 0) | |
| 87 | + ), | |
| 88 | + 'sell' | |
| 89 | + ] = 1 | |
| 90 | + | |
| 91 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/Guacamole.py +178 −0
| @@ -0,0 +1,178 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 3 | +import numpy as np | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI, VIDYA | |
| 12 | + | |
| 13 | + | |
| 14 | +class Guacamole(IStrategy): | |
| 15 | + | |
| 16 | + """ | |
| 17 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 18 | + """ | |
| 19 | + | |
| 20 | + # Buy hyperspace params: | |
| 21 | + buy_params = { | |
| 22 | + 'macd': -0.75454, | |
| 23 | + 'macdhist': -1, | |
| 24 | + 'rmi': 49 | |
| 25 | + } | |
| 26 | + | |
| 27 | + # Sell hyperspace params: | |
| 28 | + sell_params = { | |
| 29 | + | |
| 30 | + } | |
| 31 | + | |
| 32 | + # ROI table: | |
| 33 | + minimal_roi = { | |
| 34 | + "0": 0.13336, | |
| 35 | + "19": 0.07455, | |
| 36 | + "37": 0.04206, | |
| 37 | + "57": 0.02682, | |
| 38 | + "73": 0.01225, | |
| 39 | + "125": 0.0037, | |
| 40 | + "244": 0.0025 | |
| 41 | + } | |
| 42 | + | |
| 43 | + stoploss = -0.99 | |
| 44 | + | |
| 45 | + # Trailing stop: | |
| 46 | + trailing_stop = True | |
| 47 | + trailing_stop_positive = 0.01673 | |
| 48 | + trailing_stop_positive_offset = 0.01851 | |
| 49 | + trailing_only_offset_is_reached = False | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + """ | |
| 54 | + END HYPEROPT | |
| 55 | + """ | |
| 56 | + | |
| 57 | + timeframe = '5m' | |
| 58 | + | |
| 59 | + use_sell_signal = True | |
| 60 | + sell_profit_only = False | |
| 61 | + # sell_profit_offset = 0.01 | |
| 62 | + ignore_roi_if_buy_signal = True | |
| 63 | + | |
| 64 | + process_only_new_candles = False | |
| 65 | + | |
| 66 | + startup_candle_count: int = 20 | |
| 67 | + | |
| 68 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 69 | + | |
| 70 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 71 | + dataframe['rmi'] = RMI(dataframe) | |
| 72 | + dataframe['kama-3'] = ta.KAMA(dataframe, timeperiod=3) | |
| 73 | + dataframe['kama-21'] = ta.KAMA(dataframe, timeperiod=21) | |
| 74 | + | |
| 75 | + macd = ta.MACD(dataframe) | |
| 76 | + dataframe['macd'] = macd['macd'] | |
| 77 | + dataframe['macdsignal'] = macd['macdsignal'] | |
| 78 | + dataframe['macdhist'] = macd['macdhist'] | |
| 79 | + | |
| 80 | + dataframe['volume_ma'] = dataframe['volume'].rolling(window=24).mean() | |
| 81 | + | |
| 82 | + | |
| 83 | + return dataframe | |
| 84 | + | |
| 85 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 86 | + params = self.buy_params | |
| 87 | + conditions = [] | |
| 88 | + | |
| 89 | + active_trade = False | |
| 90 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 91 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 92 | + | |
| 93 | + if not active_trade: | |
| 94 | + conditions.append(dataframe['kama-3'] > dataframe['kama-21']) | |
| 95 | + conditions.append(dataframe['macd'] > dataframe['macdsignal']) | |
| 96 | + conditions.append(dataframe['macd'] > params['macd']) | |
| 97 | + conditions.append(dataframe['macdhist'] > params['macdhist']) | |
| 98 | + conditions.append(dataframe['rmi'] > dataframe['rmi'].shift()) | |
| 99 | + conditions.append(dataframe['rmi'] > params['rmi']) | |
| 100 | + conditions.append(dataframe['volume'] < (dataframe['volume_ma'] * 20)) | |
| 101 | + else: | |
| 102 | + conditions.append(dataframe['close'] > dataframe['sar']) | |
| 103 | + conditions.append(dataframe['rmi'] >= 75) | |
| 104 | + | |
| 105 | + conditions.append(dataframe['volume'] > 0) | |
| 106 | + | |
| 107 | + if conditions: | |
| 108 | + dataframe.loc[ | |
| 109 | + reduce(lambda x, y: x & y, conditions), | |
| 110 | + 'buy'] = 1 | |
| 111 | + | |
| 112 | + return dataframe | |
| 113 | + | |
| 114 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 115 | + params = self.sell_params | |
| 116 | + conditions = [] | |
| 117 | + | |
| 118 | + active_trade = False | |
| 119 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 120 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 121 | + | |
| 122 | + if active_trade: | |
| 123 | + ob = self.dp.orderbook(metadata['pair'], 1) | |
| 124 | + current_price = ob['asks'][0][0] | |
| 125 | + current_profit = active_trade[0].calc_profit_ratio(rate=current_price) | |
| 126 | + | |
| 127 | + conditions.append( | |
| 128 | + (dataframe['rmi'] < 30) & | |
| 129 | + (current_profit > -0.03) & | |
| 130 | + (dataframe['volume'].gt(0)) | |
| 131 | + ) | |
| 132 | + | |
| 133 | + if conditions: | |
| 134 | + dataframe.loc[ | |
| 135 | + reduce(lambda x, y: x & y, conditions), | |
| 136 | + 'sell'] = 1 | |
| 137 | + else: | |
| 138 | + dataframe['sell'] = 0 | |
| 139 | + | |
| 140 | + return dataframe | |
| 141 | + | |
| 142 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 143 | + ob = self.dp.orderbook(pair, 1) | |
| 144 | + current_price = ob['bids'][0][0] | |
| 145 | + # Cancel buy order if price is more than 1% above the order. | |
| 146 | + if current_price > order['price'] * 1.01: | |
| 147 | + return True | |
| 148 | + return False | |
| 149 | + | |
| 150 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 151 | + ob = self.dp.orderbook(pair, 1) | |
| 152 | + current_price = ob['asks'][0][0] | |
| 153 | + # Cancel sell order if price is more than 1% below the order. | |
| 154 | + if current_price < order['price'] * 0.99: | |
| 155 | + return True | |
| 156 | + return False | |
| 157 | + | |
| 158 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 159 | + ob = self.dp.orderbook(pair, 1) | |
| 160 | + current_price = ob['asks'][0][0] | |
| 161 | + # Cancel buy order if price is more than 1% above the order. | |
| 162 | + if current_price > rate * 1.01: | |
| 163 | + return False | |
| 164 | + return True | |
| 165 | + | |
| 166 | + """ | |
| 167 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 168 | + _, roi = self.min_roi_reached_entry(0) | |
| 169 | + | |
| 170 | + if roi is None: | |
| 171 | + if Trade.max_rate >= Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 172 | + return False | |
| 173 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate < Trade.open_rate: | |
| 174 | + return False | |
| 175 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 176 | + return current_profit > roi | |
| 177 | + return False | |
| 178 | + """ | |
| No newline at the end of the file |
added strategies/old/Hacklemore.py +246 −0
| @@ -0,0 +1,246 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | +from statistics import mean | |
| 12 | + | |
| 13 | +""" | |
| 14 | +TODO: | |
| 15 | + - Better buy signal. | |
| 16 | + - Potentially leverage an external data source? | |
| 17 | +""" | |
| 18 | + | |
| 19 | +class Hacklemore(IStrategy): | |
| 20 | + | |
| 21 | + timeframe = '5m' | |
| 22 | + inf_timeframe = '1h' | |
| 23 | + | |
| 24 | + # ROI table: | |
| 25 | + minimal_roi = { | |
| 26 | + "0": 0.15, | |
| 27 | + "5": 0.025, | |
| 28 | + "10": 0.015, | |
| 29 | + "30": 0.005 | |
| 30 | + } | |
| 31 | + | |
| 32 | + # Stoploss: | |
| 33 | + stoploss = -0.085 | |
| 34 | + | |
| 35 | + use_sell_signal = True | |
| 36 | + sell_profit_only = False | |
| 37 | + ignore_roi_if_buy_signal = True | |
| 38 | + | |
| 39 | + startup_candle_count: int = 24 | |
| 40 | + | |
| 41 | + custom_trade_info = {} | |
| 42 | + | |
| 43 | + def informative_pairs(self): | |
| 44 | + pairs = self.dp.current_whitelist() | |
| 45 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 46 | + return informative_pairs | |
| 47 | + | |
| 48 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 49 | + | |
| 50 | + # Misc. calculations regarding existing open positions (reset on every loop iteration) | |
| 51 | + self.custom_trade_info[metadata['pair']] = trade_data = {} | |
| 52 | + trade_data['active_trade'] = trade_data['other_trades'] = False | |
| 53 | + | |
| 54 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 55 | + | |
| 56 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 57 | + other_trades = Trade.get_trades([Trade.pair != metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 58 | + | |
| 59 | + if active_trade: | |
| 60 | + current_rate = self.get_current_price(metadata['pair']) | |
| 61 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 62 | + trade_data['active_trade'] = True | |
| 63 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 64 | + trade_data['peak_profit'] = active_trade[0].calc_profit_ratio(active_trade[0].max_rate) | |
| 65 | + | |
| 66 | + if other_trades: | |
| 67 | + trade_data['other_trades'] = True | |
| 68 | + total_other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair)) for trade in other_trades) | |
| 69 | + trade_data['avg_other_profit'] = mean(total_other_profit) | |
| 70 | + | |
| 71 | + self.custom_trade_info[metadata['pair']] = trade_data | |
| 72 | + | |
| 73 | + # Set up other indicators | |
| 74 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 75 | + dataframe['rmi-slow'] = RMI(dataframe, length=20, mom=5) | |
| 76 | + dataframe['rmi-fast'] = RMI(dataframe, length=9, mom=3) | |
| 77 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 78 | + | |
| 79 | + macd = ta.MACD(dataframe) | |
| 80 | + dataframe['macd'] = macd['macd'] | |
| 81 | + dataframe['macdsignal'] = macd['macdsignal'] | |
| 82 | + dataframe['macdhist'] = macd['macdhist'] | |
| 83 | + | |
| 84 | + # Trend calculations | |
| 85 | + dataframe['max'] = dataframe['high'].rolling(12).max() | |
| 86 | + dataframe['min'] = dataframe['low'].rolling(12).min() | |
| 87 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 88 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 89 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 90 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 91 | + | |
| 92 | + # Informative Pair Indicators | |
| 93 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 94 | + | |
| 95 | + informative['ema3'] = ta.EMA(informative, timeperiod=3) | |
| 96 | + informative['ema12'] = ta.EMA(informative, timeperiod=12) | |
| 97 | + | |
| 98 | + inf_macd = ta.MACD(informative) | |
| 99 | + informative['macd'] = inf_macd['macd'] | |
| 100 | + informative['macdsignal'] = inf_macd['macdsignal'] | |
| 101 | + informative['macdhist'] = inf_macd['macdhist'] | |
| 102 | + | |
| 103 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 104 | + | |
| 105 | + return dataframe | |
| 106 | + | |
| 107 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 108 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 109 | + conditions = [] | |
| 110 | + | |
| 111 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 112 | + # when this buy signal is not present a sell can happen according to ROI table | |
| 113 | + if trade_data['active_trade']: | |
| 114 | + if (trade_data['peak_profit'] > 0): | |
| 115 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * 0.8)) | |
| 116 | + conditions.append(dataframe['rmi-slow'] >= 60) | |
| 117 | + | |
| 118 | + # Normal buy triggers that apply to new trades we want to enter | |
| 119 | + else: | |
| 120 | + conditions.append( | |
| 121 | + # informative timeframe conditions | |
| 122 | + (dataframe[f"ema3_{self.inf_timeframe}"] > dataframe[f"ema12_{self.inf_timeframe}"]) & | |
| 123 | + (dataframe[f"macd_{self.inf_timeframe}"] > dataframe[f"macdsignal_{self.inf_timeframe}"]) & | |
| 124 | + | |
| 125 | + # default timeframe conditions | |
| 126 | + (dataframe['up_trend'] == 1) & | |
| 127 | + (dataframe['rmi-slow'] >= 55) & | |
| 128 | + (dataframe['macdhist'] > 0) & | |
| 129 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * 30)) & | |
| 130 | + | |
| 131 | + (dataframe['macd'] > dataframe['macdsignal']) & | |
| 132 | + (dataframe['rmi-slow'] >= dataframe['rmi-slow'].rolling(3).mean()) & | |
| 133 | + (dataframe['close'] > dataframe['close'].shift()) & | |
| 134 | + (dataframe['close'].shift() > dataframe['close'].shift(2)) & | |
| 135 | + (dataframe['sar'] < dataframe['close']) & | |
| 136 | + (dataframe['sar'].shift() < dataframe['close'].shift()) | |
| 137 | + ) | |
| 138 | + | |
| 139 | + # applies to both new buys and persisting buy signal | |
| 140 | + conditions.append(dataframe['volume'].gt(0)) | |
| 141 | + | |
| 142 | + if conditions: | |
| 143 | + dataframe.loc[ | |
| 144 | + reduce(lambda x, y: x & y, conditions), | |
| 145 | + 'buy'] = 1 | |
| 146 | + | |
| 147 | + return dataframe | |
| 148 | + | |
| 149 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 150 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 151 | + conditions = [] | |
| 152 | + | |
| 153 | + # if we are in an active trade for this pair | |
| 154 | + if trade_data['active_trade']: | |
| 155 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 156 | + conditions.append( | |
| 157 | + (trade_data['current_profit'] < 0) & | |
| 158 | + (trade_data['current_profit'] > self.stoploss) & | |
| 159 | + (dataframe['dn_trend'] == 1) & | |
| 160 | + (dataframe['rmi-fast'] < 50) & | |
| 161 | + (dataframe['volume'].gt(0)) | |
| 162 | + ) | |
| 163 | + | |
| 164 | + # if there are other open trades in addition to this one, consider the average profit | |
| 165 | + # across them all (not including this one), don't sell if entire market is down big and wait for recovery | |
| 166 | + if trade_data['other_trades']: | |
| 167 | + conditions.append(trade_data['avg_other_profit'] >= -0.005) | |
| 168 | + | |
| 169 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 170 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 171 | + # clogging up the charts and not having one leads the bot to crash | |
| 172 | + else: | |
| 173 | + conditions.append(dataframe['volume'].lt(0)) | |
| 174 | + | |
| 175 | + if conditions: | |
| 176 | + dataframe.loc[ | |
| 177 | + reduce(lambda x, y: x & y, conditions), | |
| 178 | + 'sell'] = 1 | |
| 179 | + | |
| 180 | + return dataframe | |
| 181 | + | |
| 182 | + """ | |
| 183 | + Custom methods | |
| 184 | + """ | |
| 185 | + def get_current_price(self, pair: str) -> float: | |
| 186 | + """ | |
| 187 | + # Using ticker seems significantly faster than orderbook. | |
| 188 | + side = "asks" | |
| 189 | + if (self.config['ask_strategy']['price_side'] == "bid"): | |
| 190 | + side = "bids" | |
| 191 | + | |
| 192 | + ob = self.dp.orderbook(pair, 1) | |
| 193 | + current_price = ob[side][0][0] | |
| 194 | + """ | |
| 195 | + | |
| 196 | + ticker = self.dp.ticker(pair) | |
| 197 | + current_price = ticker['last'] | |
| 198 | + | |
| 199 | + return current_price | |
| 200 | + | |
| 201 | + """ | |
| 202 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 203 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 204 | + """ | |
| 205 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 206 | + ob = self.dp.orderbook(pair, 1) | |
| 207 | + current_price = ob['bids'][0][0] | |
| 208 | + # Cancel buy order if price is more than 1% above the order. | |
| 209 | + if current_price > order['price'] * 1.01: | |
| 210 | + return True | |
| 211 | + return False | |
| 212 | + | |
| 213 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 214 | + ob = self.dp.orderbook(pair, 1) | |
| 215 | + current_price = ob['asks'][0][0] | |
| 216 | + # Cancel sell order if price is more than 1% below the order. | |
| 217 | + if current_price < order['price'] * 0.99: | |
| 218 | + return True | |
| 219 | + return False | |
| 220 | + | |
| 221 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 222 | + ob = self.dp.orderbook(pair, 1) | |
| 223 | + current_price = ob['asks'][0][0] | |
| 224 | + # Cancel buy order if price is more than 1% above the order. | |
| 225 | + if current_price > rate * 1.01: | |
| 226 | + return False | |
| 227 | + return True | |
| 228 | + | |
| 229 | +class Hacklemore_Slow(Hacklemore): | |
| 230 | + | |
| 231 | + timeframe = '1h' | |
| 232 | + inf_timeframe = '4h' | |
| 233 | + | |
| 234 | + # ROI table: | |
| 235 | + minimal_roi = { | |
| 236 | + "0": 0.15, | |
| 237 | + "10": 0.10, | |
| 238 | + "20": 0.05, | |
| 239 | + "30": 0.025, | |
| 240 | + "60": 0.015, | |
| 241 | + "120": 0.005 | |
| 242 | + } | |
| 243 | + | |
| 244 | + # Stoploss: | |
| 245 | + stoploss = -0.085 | |
| 246 | + |
added strategies/old/Hacklemore2.py +167 −0
| @@ -0,0 +1,167 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | + | |
| 12 | +class Hacklemore2(IStrategy): | |
| 13 | + | |
| 14 | + """ | |
| 15 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 16 | + """ | |
| 17 | + # ROI table: | |
| 18 | + minimal_roi = { | |
| 19 | + "0": 0.14509, | |
| 20 | + "9": 0.07666, | |
| 21 | + "23": 0.0378, | |
| 22 | + "36": 0.01987, | |
| 23 | + "60": 0.0128, | |
| 24 | + "145": 0.00467, | |
| 25 | + "285": 0 | |
| 26 | + } | |
| 27 | + | |
| 28 | + # Stoploss: | |
| 29 | + stoploss = -0.99 | |
| 30 | + | |
| 31 | + trailing_stop = True | |
| 32 | + trailing_stop_positive = 0.02 | |
| 33 | + trailing_stop_positive_offset = 0.03 | |
| 34 | + trailing_only_offset_is_reached = True | |
| 35 | + | |
| 36 | + """ | |
| 37 | + END HYPEROPT | |
| 38 | + """ | |
| 39 | + | |
| 40 | + timeframe = '15m' | |
| 41 | + | |
| 42 | + use_sell_signal = True | |
| 43 | + sell_profit_only = False | |
| 44 | + #sell_profit_offset = 0.01 | |
| 45 | + ignore_roi_if_buy_signal = True | |
| 46 | + | |
| 47 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 48 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 49 | + | |
| 50 | + dataframe['RMI'] = RMI(dataframe) | |
| 51 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 52 | + | |
| 53 | + dataframe['max'] = dataframe['high'].rolling(60).max() | |
| 54 | + | |
| 55 | + dataframe['min'] = dataframe['low'].rolling(60).min() | |
| 56 | + | |
| 57 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 58 | + | |
| 59 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 60 | + | |
| 61 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(10, min_periods=1).sum() != 0,1,0) | |
| 62 | + | |
| 63 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(10, min_periods=1).sum() != 0,1,0) | |
| 64 | + | |
| 65 | + return dataframe | |
| 66 | + | |
| 67 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 68 | + active_trade = False | |
| 69 | + | |
| 70 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 71 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 72 | + | |
| 73 | + conditions = [] | |
| 74 | + | |
| 75 | + if not active_trade: | |
| 76 | + conditions.append( | |
| 77 | + ( (dataframe['up_trend'] == True) & | |
| 78 | + (dataframe['RMI'] > 55) & | |
| 79 | + (dataframe['RMI'] >= dataframe['RMI'].rolling(3).mean()) & | |
| 80 | + (dataframe['close'] > dataframe['close'].shift()) & | |
| 81 | + (dataframe['close'].shift() > dataframe['close'].shift(2)) & | |
| 82 | + (dataframe['sar'] < dataframe['close']) & | |
| 83 | + (dataframe['sar'].shift() < dataframe['close'].shift()) & | |
| 84 | + (dataframe['sar'].shift(2) < dataframe['close'].shift(2)) & | |
| 85 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * 30)) | |
| 86 | + )) | |
| 87 | + | |
| 88 | + else: | |
| 89 | + conditions.append(dataframe['RMI'] >= 75) | |
| 90 | + | |
| 91 | + conditions.append(dataframe['volume'].gt(0)) | |
| 92 | + | |
| 93 | + if conditions: | |
| 94 | + dataframe.loc[ | |
| 95 | + reduce(lambda x, y: x & y, conditions), | |
| 96 | + 'buy'] = 1 | |
| 97 | + | |
| 98 | + return dataframe | |
| 99 | + | |
| 100 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 101 | + active_trade = False | |
| 102 | + | |
| 103 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 104 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 105 | + | |
| 106 | + conditions = [] | |
| 107 | + | |
| 108 | + if active_trade: | |
| 109 | + ob = self.dp.orderbook(metadata['pair'], 1) | |
| 110 | + current_price = ob['asks'][0][0] | |
| 111 | + # current_profit = Trade.calc_profit_ratio(active_trade[0], rate=current_price) | |
| 112 | + current_profit = active_trade[0].calc_profit_ratio(rate=current_price) | |
| 113 | + | |
| 114 | + conditions.append( | |
| 115 | + (dataframe['buy'] == 0) & | |
| 116 | + (dataframe['dn_trend'] == True) & | |
| 117 | + (dataframe['RMI'] < 30) & | |
| 118 | + (current_profit > -0.03) & | |
| 119 | + (dataframe['volume'].gt(0)) | |
| 120 | + ) | |
| 121 | + | |
| 122 | + if conditions: | |
| 123 | + dataframe.loc[ | |
| 124 | + reduce(lambda x, y: x & y, conditions), | |
| 125 | + 'sell'] = 1 | |
| 126 | + else: | |
| 127 | + dataframe['sell'] = 0 | |
| 128 | + | |
| 129 | + return dataframe | |
| 130 | + | |
| 131 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 132 | + ob = self.dp.orderbook(pair, 1) | |
| 133 | + current_price = ob['bids'][0][0] | |
| 134 | + # Cancel buy order if price is more than 1% above the order. | |
| 135 | + if current_price > order['price'] * 1.01: | |
| 136 | + return True | |
| 137 | + return False | |
| 138 | + | |
| 139 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 140 | + ob = self.dp.orderbook(pair, 1) | |
| 141 | + current_price = ob['asks'][0][0] | |
| 142 | + # Cancel sell order if price is more than 1% below the order. | |
| 143 | + if current_price < order['price'] * 0.99: | |
| 144 | + return True | |
| 145 | + return False | |
| 146 | + | |
| 147 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 148 | + ob = self.dp.orderbook(pair, 1) | |
| 149 | + current_price = ob['asks'][0][0] | |
| 150 | + # Cancel buy order if price is more than 1% above the order. | |
| 151 | + if current_price > rate * 1.01: | |
| 152 | + return False | |
| 153 | + return True | |
| 154 | + | |
| 155 | + """ | |
| 156 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 157 | + _, roi = self.min_roi_reached_entry(0) | |
| 158 | + | |
| 159 | + if roi is None: | |
| 160 | + if Trade.max_rate >= Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 161 | + return False | |
| 162 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate < Trade.open_rate: | |
| 163 | + return False | |
| 164 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 165 | + return current_profit > roi | |
| 166 | + return False | |
| 167 | + """ | |
| No newline at the end of the file |
added strategies/old/Hacklemore3.py +167 −0
| @@ -0,0 +1,167 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | + | |
| 12 | +class Hacklemore3(IStrategy): | |
| 13 | + | |
| 14 | + """ | |
| 15 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 16 | + """ | |
| 17 | + # ROI table: | |
| 18 | + minimal_roi = { | |
| 19 | + "0": 0.15, | |
| 20 | + "5": 0.015 | |
| 21 | + } | |
| 22 | + | |
| 23 | + # Stoploss: | |
| 24 | + stoploss = -0.99 | |
| 25 | + | |
| 26 | + trailing_stop = True | |
| 27 | + trailing_stop_positive = 0.02 | |
| 28 | + trailing_stop_positive_offset = 0.03 | |
| 29 | + trailing_only_offset_is_reached = True | |
| 30 | + | |
| 31 | + """ | |
| 32 | + END HYPEROPT | |
| 33 | + """ | |
| 34 | + | |
| 35 | + timeframe = '5m' | |
| 36 | + | |
| 37 | + use_sell_signal = True | |
| 38 | + sell_profit_only = False | |
| 39 | + sell_profit_offset = 0.01 | |
| 40 | + ignore_roi_if_buy_signal = True | |
| 41 | + | |
| 42 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 43 | + | |
| 44 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 45 | + dataframe['rmi'] = RMI(dataframe) | |
| 46 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 47 | + dataframe['max'] = dataframe['high'].rolling(12).max() | |
| 48 | + dataframe['min'] = dataframe['low'].rolling(12).min() | |
| 49 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 50 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 51 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 52 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 53 | + | |
| 54 | + return dataframe | |
| 55 | + | |
| 56 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 57 | + | |
| 58 | + conditions = [] | |
| 59 | + | |
| 60 | + active_trade = False | |
| 61 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 62 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 63 | + | |
| 64 | + # Normal buy triggers that apply to new trades we want to enter | |
| 65 | + if not active_trade: | |
| 66 | + conditions.append( | |
| 67 | + (dataframe['up_trend'] == 1) & | |
| 68 | + (dataframe['rmi'] > 55) & | |
| 69 | + (dataframe['rmi'] >= dataframe['rmi'].rolling(3).mean()) & | |
| 70 | + (dataframe['close'] > dataframe['close'].shift()) & | |
| 71 | + (dataframe['close'].shift() > dataframe['close'].shift(2)) & | |
| 72 | + (dataframe['sar'] < dataframe['close']) & | |
| 73 | + (dataframe['sar'].shift() < dataframe['close'].shift()) & | |
| 74 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * 30)) | |
| 75 | + ) | |
| 76 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 77 | + # when this buy signal is not present a sell will happen according to ROI table | |
| 78 | + else: | |
| 79 | + conditions.append(dataframe['rmi'] >= 75) | |
| 80 | + | |
| 81 | + conditions.append(dataframe['volume'].gt(0)) | |
| 82 | + | |
| 83 | + if conditions: | |
| 84 | + dataframe.loc[ | |
| 85 | + reduce(lambda x, y: x & y, conditions), | |
| 86 | + 'buy'] = 1 | |
| 87 | + | |
| 88 | + return dataframe | |
| 89 | + | |
| 90 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 91 | + | |
| 92 | + conditions = [] | |
| 93 | + | |
| 94 | + active_trade = False | |
| 95 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 96 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 97 | + | |
| 98 | + # if we are in an active trade for this pair consider various things in our sell signal | |
| 99 | + if active_trade: | |
| 100 | + ob = self.dp.orderbook(metadata['pair'], 1) | |
| 101 | + current_price = ob['asks'][0][0] | |
| 102 | + current_profit = active_trade[0].calc_profit_ratio(rate=current_price) | |
| 103 | + max_price = active_trade[0].max_rate | |
| 104 | + # if we are at a loss, consider what the trend looks like in the sell | |
| 105 | + if current_profit < 0: | |
| 106 | + conditions.append( | |
| 107 | + (dataframe['dn_trend'] == 1) & | |
| 108 | + (dataframe['rmi'] < 50) & | |
| 109 | + (dataframe['volume'].gt(0)) | |
| 110 | + # custom sell-reason: dynamic-stop-loss | |
| 111 | + ) | |
| 112 | + # if we are in a profit, produce a sort of dynamic trailing stoploss | |
| 113 | + else: | |
| 114 | + conditions.append( | |
| 115 | + (current_price > (max_price * 0.8)) & | |
| 116 | + (dataframe['close'] < dataframe['close'].shift()) & | |
| 117 | + (dataframe['high'] < dataframe['high'].shift()) | |
| 118 | + # custom sell-reason: dynamic-trailing-stop | |
| 119 | + ) | |
| 120 | + else: | |
| 121 | + # impossible condition needed for some reason? | |
| 122 | + conditions.append(dataframe['volume'].lt(0)) | |
| 123 | + | |
| 124 | + if conditions: | |
| 125 | + dataframe.loc[ | |
| 126 | + reduce(lambda x, y: x & y, conditions), | |
| 127 | + 'sell'] = 1 | |
| 128 | + | |
| 129 | + return dataframe | |
| 130 | + | |
| 131 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 132 | + ob = self.dp.orderbook(pair, 1) | |
| 133 | + current_price = ob['bids'][0][0] | |
| 134 | + # Cancel buy order if price is more than 1% above the order. | |
| 135 | + if current_price > order['price'] * 1.01: | |
| 136 | + return True | |
| 137 | + return False | |
| 138 | + | |
| 139 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 140 | + ob = self.dp.orderbook(pair, 1) | |
| 141 | + current_price = ob['asks'][0][0] | |
| 142 | + # Cancel sell order if price is more than 1% below the order. | |
| 143 | + if current_price < order['price'] * 0.99: | |
| 144 | + return True | |
| 145 | + return False | |
| 146 | + | |
| 147 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 148 | + ob = self.dp.orderbook(pair, 1) | |
| 149 | + current_price = ob['asks'][0][0] | |
| 150 | + # Cancel buy order if price is more than 1% above the order. | |
| 151 | + if current_price > rate * 1.01: | |
| 152 | + return False | |
| 153 | + return True | |
| 154 | + | |
| 155 | + """ | |
| 156 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 157 | + _, roi = self.min_roi_reached_entry(0) | |
| 158 | + | |
| 159 | + if roi is None: | |
| 160 | + if Trade.max_rate >= Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 161 | + return False | |
| 162 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate < Trade.open_rate: | |
| 163 | + return False | |
| 164 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 165 | + return current_profit > roi | |
| 166 | + return False | |
| 167 | + """ | |
| No newline at the end of the file |
added strategies/old/HacklemoreX.py +212 −0
| @@ -0,0 +1,212 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | + | |
| 12 | +""" | |
| 13 | +TODO: | |
| 14 | + - Better buy signal. | |
| 15 | +""" | |
| 16 | + | |
| 17 | +class Hacklemore(IStrategy): | |
| 18 | + | |
| 19 | + timeframe = '5m' | |
| 20 | + | |
| 21 | + # ROI table: | |
| 22 | + minimal_roi = { | |
| 23 | + "0": 0.15, | |
| 24 | + "5": 0.025, | |
| 25 | + "10": 0.015 | |
| 26 | + } | |
| 27 | + | |
| 28 | + # Stoploss: | |
| 29 | + stoploss = -0.085 | |
| 30 | + | |
| 31 | + use_sell_signal = True | |
| 32 | + sell_profit_only = False | |
| 33 | + ignore_roi_if_buy_signal = True | |
| 34 | + | |
| 35 | + startup_candle_count: int = 24 | |
| 36 | + | |
| 37 | + custom_trade_info = {} | |
| 38 | + | |
| 39 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 40 | + | |
| 41 | + # Misc calculations regarding existing open positions | |
| 42 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 43 | + | |
| 44 | + self.custom_trade_info[metadata['pair']] = trade_data = {} | |
| 45 | + trade_data['active_trade'] = trade_data['other_trades'] = False | |
| 46 | + | |
| 47 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 48 | + other_trades = Trade.get_trades([Trade.pair != metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 49 | + | |
| 50 | + if active_trade: | |
| 51 | + trade_data['active_trade'] = True | |
| 52 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(rate=self.get_current_price(metadata['pair'])) | |
| 53 | + trade_data['peak_profit'] = active_trade[0].calc_profit_ratio(rate=active_trade[0].max_rate) | |
| 54 | + trade_data['current_peak_ratio'] = (trade_data['current_profit'] / trade_data['peak_profit']) | |
| 55 | + | |
| 56 | + if other_trades: | |
| 57 | + trade_data['other_trades'] = True | |
| 58 | + total_other_profit = sum(trade.calc_profit_ratio(rate=self.get_current_price(trade.pair)) for trade in other_trades) | |
| 59 | + trade_data['avg_other_profit'] = total_other_profit / len(other_trades) | |
| 60 | + | |
| 61 | + self.custom_trade_info[metadata['pair']] = trade_data | |
| 62 | + | |
| 63 | + # Set up other indicators | |
| 64 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 65 | + dataframe['rmi-slow'] = RMI(dataframe, length=20, mom=5) | |
| 66 | + dataframe['rmi-fast'] = RMI(dataframe, length=9, mom=3) | |
| 67 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 68 | + | |
| 69 | + macd = ta.MACD(dataframe) | |
| 70 | + dataframe['macd'] = macd['macd'] | |
| 71 | + dataframe['macdsignal'] = macd['macdsignal'] | |
| 72 | + dataframe['macdhist'] = macd['macdhist'] | |
| 73 | + | |
| 74 | + # Trend calculations | |
| 75 | + dataframe['max'] = dataframe['high'].rolling(12).max() | |
| 76 | + dataframe['min'] = dataframe['low'].rolling(12).min() | |
| 77 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 78 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 79 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 80 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(3, min_periods=1).sum() != 0,1,0) | |
| 81 | + | |
| 82 | + # Set Up Bollinger Bands | |
| 83 | + upper_bb, mid_bb, lower_bb = ta.BBANDS(dataframe['close'], timeperiod=20) | |
| 84 | + | |
| 85 | + dataframe['upper-bb'] = upper_bb | |
| 86 | + dataframe['lower-bb'] = lower_bb | |
| 87 | + dataframe['mid-bb'] = mid_bb | |
| 88 | + | |
| 89 | + # did candle low break-out of bottom bband? | |
| 90 | + dataframe['breakout-low'] = np.where(dataframe['low'] <= dataframe['lower-bb'], True, False) | |
| 91 | + | |
| 92 | + last = np.nan | |
| 93 | + for i in range(len(dataframe)): | |
| 94 | + if dataframe.loc[i, 'breakout-low']: | |
| 95 | + last = i | |
| 96 | + dataframe.loc[i, 'breakout-low-last'] = i - last | |
| 97 | + | |
| 98 | + return dataframe | |
| 99 | + | |
| 100 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 101 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 102 | + conditions = [] | |
| 103 | + | |
| 104 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 105 | + # when this buy signal is not present a sell can happen according to ROI table | |
| 106 | + if trade_data['active_trade']: | |
| 107 | + conditions.append(trade_data['current_peak_ratio'] > 0.8) | |
| 108 | + conditions.append(dataframe['rmi-slow'] >= 60) | |
| 109 | + | |
| 110 | + # Normal buy triggers that apply to new trades we want to enter | |
| 111 | + else: | |
| 112 | + conditions.append( | |
| 113 | + (dataframe['up_trend'] == 1) & | |
| 114 | + (dataframe['rmi-slow'] >= 55) & | |
| 115 | + (dataframe['macdhist'] > 0) & | |
| 116 | + (dataframe['breakout-low-last'] >= 2) & | |
| 117 | + (dataframe['breakout-low-last'] <= 10) & | |
| 118 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * 30)) & | |
| 119 | + | |
| 120 | + (dataframe['macd'] > dataframe['macdsignal']) & | |
| 121 | + (dataframe['rmi-slow'] >= dataframe['rmi-slow'].rolling(3).mean()) & | |
| 122 | + (dataframe['close'] > dataframe['close'].shift()) & | |
| 123 | + (dataframe['close'].shift() > dataframe['close'].shift(2)) & | |
| 124 | + (dataframe['sar'] < dataframe['close']) & | |
| 125 | + (dataframe['sar'].shift() < dataframe['close'].shift()) | |
| 126 | + ) | |
| 127 | + # if there are other open trades consider their performance before we enter a new position | |
| 128 | + if trade_data['other_trades']: | |
| 129 | + conditions.append(trade_data['avg_other_profit'] >= 0) | |
| 130 | + | |
| 131 | + # applies to both new buys and persisting buy signal | |
| 132 | + conditions.append(dataframe['volume'].gt(0)) | |
| 133 | + | |
| 134 | + if conditions: | |
| 135 | + dataframe.loc[ | |
| 136 | + reduce(lambda x, y: x & y, conditions), | |
| 137 | + 'buy'] = 1 | |
| 138 | + | |
| 139 | + return dataframe | |
| 140 | + | |
| 141 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 142 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 143 | + conditions = [] | |
| 144 | + | |
| 145 | + # if we are in an active trade for this pair | |
| 146 | + if trade_data['active_trade']: | |
| 147 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 148 | + conditions.append( | |
| 149 | + (trade_data['current_profit'] < 0) & | |
| 150 | + (trade_data['current_profit'] > self.stoploss) & | |
| 151 | + (dataframe['dn_trend'] == 1) & | |
| 152 | + (dataframe['rmi-fast'] < 50) & | |
| 153 | + (dataframe['volume'].gt(0)) | |
| 154 | + # custom sell-reason: dynamic-stop-loss | |
| 155 | + ) | |
| 156 | + | |
| 157 | + # if there are other open trades in addition to this one, consider the average profit | |
| 158 | + # across them all (not including this one), don't sell if entire market is down big and wait for recovery | |
| 159 | + if trade_data['other_trades']: | |
| 160 | + conditions.append(trade_data['avg_other_profit'] >= -0.005) | |
| 161 | + | |
| 162 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 163 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 164 | + # clogging up the charts and not having one leads the bot to crash | |
| 165 | + else: | |
| 166 | + conditions.append(dataframe['volume'].lt(0)) | |
| 167 | + | |
| 168 | + if conditions: | |
| 169 | + dataframe.loc[ | |
| 170 | + reduce(lambda x, y: x & y, conditions), | |
| 171 | + 'sell'] = 1 | |
| 172 | + | |
| 173 | + return dataframe | |
| 174 | + | |
| 175 | + """ | |
| 176 | + Custom methods | |
| 177 | + """ | |
| 178 | + def get_current_price(self, pair: str, side="asks") -> float: | |
| 179 | + ob = self.dp.orderbook(pair, 1) | |
| 180 | + current_price = ob[side][0][0] | |
| 181 | + | |
| 182 | + return current_price | |
| 183 | + | |
| 184 | + """ | |
| 185 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 186 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 187 | + """ | |
| 188 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 189 | + ob = self.dp.orderbook(pair, 1) | |
| 190 | + current_price = ob['bids'][0][0] | |
| 191 | + # Cancel buy order if price is more than 1% above the order. | |
| 192 | + if current_price > order['price'] * 1.01: | |
| 193 | + return True | |
| 194 | + return False | |
| 195 | + | |
| 196 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 197 | + ob = self.dp.orderbook(pair, 1) | |
| 198 | + current_price = ob['asks'][0][0] | |
| 199 | + # Cancel sell order if price is more than 1% below the order. | |
| 200 | + if current_price < order['price'] * 0.99: | |
| 201 | + return True | |
| 202 | + return False | |
| 203 | + | |
| 204 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 205 | + ob = self.dp.orderbook(pair, 1) | |
| 206 | + current_price = ob['asks'][0][0] | |
| 207 | + # Cancel buy order if price is more than 1% above the order. | |
| 208 | + if current_price > rate * 1.01: | |
| 209 | + return False | |
| 210 | + return True | |
| 211 | + | |
| 212 | + |
added strategies/old/Hacklemost.py +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | + | |
| 12 | +class Hacklemost(IStrategy): | |
| 13 | + | |
| 14 | + """ | |
| 15 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 16 | + """ | |
| 17 | + # Buy hyperspace params: | |
| 18 | + buy_params = { | |
| 19 | + 'bbdelta-close': 0.02514, | |
| 20 | + 'bbdelta-tail': 1.19782, | |
| 21 | + 'buy-rmi': 1, | |
| 22 | + 'closedelta-close': 0.01671, | |
| 23 | + 'volume': 9 | |
| 24 | + } | |
| 25 | + | |
| 26 | + # Sell hyperspace params: | |
| 27 | + sell_params = { | |
| 28 | + 'sell-adx': 5 | |
| 29 | + } | |
| 30 | + | |
| 31 | + # ROI table: | |
| 32 | + minimal_roi = { | |
| 33 | + "0": 0.14034, | |
| 34 | + "1": 0.06487, | |
| 35 | + "21": 0.03861, | |
| 36 | + "36": 0.02318, | |
| 37 | + "57": 0.01272, | |
| 38 | + "126": 0.00494, | |
| 39 | + "255": 0.0025 | |
| 40 | + } | |
| 41 | + | |
| 42 | + # Stoploss: | |
| 43 | + stoploss = -0.31765 | |
| 44 | + | |
| 45 | + # Trailing stop: | |
| 46 | + trailing_stop = True | |
| 47 | + trailing_stop_positive = 0.20185 | |
| 48 | + trailing_stop_positive_offset = 0.22421 | |
| 49 | + trailing_only_offset_is_reached = True | |
| 50 | + | |
| 51 | + | |
| 52 | + """ | |
| 53 | + END HYPEROPT | |
| 54 | + """ | |
| 55 | + | |
| 56 | + timeframe = '5m' | |
| 57 | + | |
| 58 | + use_sell_signal = True | |
| 59 | + sell_profit_only = False | |
| 60 | + sell_profit_offset = 0.01 | |
| 61 | + ignore_roi_if_buy_signal = True | |
| 62 | + | |
| 63 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 64 | + | |
| 65 | + # Heikin Ashi Candles | |
| 66 | + heikinashi = qtpylib.heikinashi(dataframe) | |
| 67 | + dataframe['ha_open'] = heikinashi['open'] | |
| 68 | + dataframe['ha_close'] = heikinashi['close'] | |
| 69 | + dataframe['ha_high'] = heikinashi['high'] | |
| 70 | + dataframe['ha_low'] = heikinashi['low'] | |
| 71 | + | |
| 72 | + # Set Up Bollinger Bands | |
| 73 | + upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['ha_close'], timeperiod=40) | |
| 74 | + upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(qtpylib.typical_price(heikinashi), timeperiod=20) | |
| 75 | + | |
| 76 | + # only putting some bands into dataframe as the others are not used elsewhere in the strategy | |
| 77 | + dataframe['lower-bb1'] = lower_bb1 | |
| 78 | + dataframe['lower-bb2'] = lower_bb2 | |
| 79 | + dataframe['mid-bb2'] = mid_bb2 | |
| 80 | + | |
| 81 | + dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs() | |
| 82 | + dataframe['closedelta'] = (dataframe['ha_close'] - dataframe['ha_close'].shift()).abs() | |
| 83 | + dataframe['tail'] = (dataframe['ha_close'] - dataframe['ha_low']).abs() | |
| 84 | + | |
| 85 | + dataframe['ema_slow'] = ta.EMA(dataframe['ha_close'], timeperiod=48) | |
| 86 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 87 | + | |
| 88 | + dataframe['rsi'] = ta.RSI(heikinashi, timeperiod=14) | |
| 89 | + | |
| 90 | + dataframe['tema'] = ta.TEMA(heikinashi, timeperiod=9) | |
| 91 | + dataframe['adx'] = ta.ADX(heikinashi) | |
| 92 | + dataframe['rmi'] = RMI(heikinashi) | |
| 93 | + | |
| 94 | + dataframe['sar'] = ta.SAR(heikinashi) | |
| 95 | + | |
| 96 | + return dataframe | |
| 97 | + | |
| 98 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 99 | + params = self.buy_params | |
| 100 | + active_trade = False | |
| 101 | + | |
| 102 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 103 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 104 | + | |
| 105 | + conditions = [] | |
| 106 | + | |
| 107 | + if not active_trade: | |
| 108 | + conditions.append( | |
| 109 | + (dataframe['rmi'] >= params['buy-rmi']) & | |
| 110 | + (dataframe['rmi'].gt(dataframe['rmi'].shift(1))) & | |
| 111 | + (dataframe['ha_close'].gt(dataframe['sar'])) & | |
| 112 | + (dataframe['bb1-delta'].gt(dataframe['ha_close'] * params['bbdelta-close'])) & | |
| 113 | + (dataframe['closedelta'].gt(dataframe['ha_close'] * params['closedelta-close'])) & | |
| 114 | + (dataframe['tail'].lt(dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 115 | + (dataframe['ha_close'].lt(dataframe['ema_slow'])) & | |
| 116 | + (dataframe['volume'].lt(dataframe['volume_mean_slow'].shift(1) * params['volume'])) | |
| 117 | + ) | |
| 118 | + else: | |
| 119 | + conditions.append(dataframe['rmi'] >= params['buy-rmi']) | |
| 120 | + conditions.append(dataframe['rmi'].gt(dataframe['rmi'].shift(1))) | |
| 121 | + | |
| 122 | + conditions.append(dataframe['volume'].gt(0)) | |
| 123 | + | |
| 124 | + if conditions: | |
| 125 | + dataframe.loc[ | |
| 126 | + reduce(lambda x, y: x & y, conditions), | |
| 127 | + 'buy'] = 1 | |
| 128 | + | |
| 129 | + return dataframe | |
| 130 | + | |
| 131 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 132 | + params = self.sell_params | |
| 133 | + | |
| 134 | + dataframe.loc[ | |
| 135 | + ( | |
| 136 | + (dataframe['adx'] < params['sell-adx']) & | |
| 137 | + (dataframe['tema'].lt(dataframe['tema'].shift(1))) & | |
| 138 | + (dataframe['rmi'].lt(dataframe['rmi'].shift(1))) & | |
| 139 | + (dataframe['rmi'].shift(1).gt(dataframe['rmi'].shift(2))) & | |
| 140 | + (dataframe['ha_close'].lt(dataframe['sar'])) | |
| 141 | + ), | |
| 142 | + 'sell' | |
| 143 | + ] = 1 | |
| 144 | + | |
| 145 | + return dataframe | |
| 146 | + | |
| 147 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 148 | + ob = self.dp.orderbook(pair, 1) | |
| 149 | + current_price = ob['bids'][0][0] | |
| 150 | + # Cancel buy order if price is more than 1% above the order. | |
| 151 | + if current_price > order['price'] * 1.01: | |
| 152 | + return True | |
| 153 | + return False | |
| 154 | + | |
| 155 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 156 | + ob = self.dp.orderbook(pair, 1) | |
| 157 | + current_price = ob['asks'][0][0] | |
| 158 | + # Cancel sell order if price is more than 1% below the order. | |
| 159 | + if current_price < order['price'] * 0.99: | |
| 160 | + return True | |
| 161 | + return False | |
| 162 | + | |
| 163 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 164 | + ob = self.dp.orderbook(pair, 1) | |
| 165 | + current_price = ob['asks'][0][0] | |
| 166 | + # Cancel buy order if price is more than 1% above the order. | |
| 167 | + if current_price > rate * 1.01: | |
| 168 | + return False | |
| 169 | + return True | |
| No newline at the end of the file |
added strategies/old/Ichis.py +150 −0
| @@ -0,0 +1,150 @@ | ||
| 1 | +# --- Do not remove these libs --- | |
| 2 | +from freqtrade.strategy.interface import IStrategy | |
| 3 | +from pandas import DataFrame | |
| 4 | +import talib.abstract as ta | |
| 5 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 6 | + | |
| 7 | + | |
| 8 | +# -------------------------------- | |
| 9 | +import pandas as pd # noqa | |
| 10 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 11 | + | |
| 12 | +import technical.indicators as ftt | |
| 13 | +#from technical.util import resample_to_interval, resampled_merge | |
| 14 | + | |
| 15 | +from functools import reduce | |
| 16 | +from datetime import datetime, timedelta | |
| 17 | +from freqtrade.strategy import merge_informative_pair | |
| 18 | + | |
| 19 | +import numpy as np | |
| 20 | + | |
| 21 | + | |
| 22 | +class ichi(IStrategy): | |
| 23 | + | |
| 24 | + # Optimal timeframe for the strategy | |
| 25 | + timeframe = '1h' | |
| 26 | + | |
| 27 | + #startup_candle_count = 120 | |
| 28 | + process_only_new_candles = False | |
| 29 | + | |
| 30 | + # no ROI | |
| 31 | + minimal_roi = { | |
| 32 | + "0": 0.05, | |
| 33 | + "30": 0.04, | |
| 34 | + "60": 0.03, | |
| 35 | + "90": 0.025 | |
| 36 | + | |
| 37 | + } | |
| 38 | + | |
| 39 | + # Stoploss: | |
| 40 | + stoploss = -0.01 | |
| 41 | + trailing_stop = True | |
| 42 | + trailing_stop_positive = 0.002 | |
| 43 | + trailing_stop_positive_offset = 0.025 | |
| 44 | + trailing_only_offset_is_reached = True | |
| 45 | + | |
| 46 | + use_sell_signal = True | |
| 47 | + sell_profit_only = False | |
| 48 | + ignore_roi_if_buy_signal = True | |
| 49 | + | |
| 50 | + | |
| 51 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 52 | + | |
| 53 | + displacement = 30 | |
| 54 | + ichimoku = ftt.ichimoku(dataframe, | |
| 55 | + conversion_line_period=20, | |
| 56 | + base_line_periods=60, | |
| 57 | + laggin_span=120, | |
| 58 | + displacement=displacement | |
| 59 | + ) | |
| 60 | + | |
| 61 | + #dataframe['chikou_span'] = ichimoku['chikou_span'] | |
| 62 | + | |
| 63 | + # cross indicators | |
| 64 | + dataframe['tenkan_sen'] = ichimoku['tenkan_sen'] | |
| 65 | + dataframe['kijun_sen'] = ichimoku['kijun_sen'] | |
| 66 | + | |
| 67 | + # cloud, green a > b, red a < b | |
| 68 | + #dataframe['senkou_a'] = ichimoku['senkou_span_a'] | |
| 69 | + #dataframe['senkou_b'] = ichimoku['senkou_span_b'] | |
| 70 | + dataframe['leading_senkou_span_a'] = ichimoku['leading_senkou_span_a'] | |
| 71 | + dataframe['leading_senkou_span_b'] = ichimoku['leading_senkou_span_b'] | |
| 72 | + #dataframe['cloud_green'] = ichimoku['cloud_green'] * 1 | |
| 73 | + #dataframe['cloud_red'] = ichimoku['cloud_red'] * -1 | |
| 74 | + | |
| 75 | + # DANGER ZONE START | |
| 76 | + | |
| 77 | + # The cloud is normally shifted into the future visually, but it's based on present data. | |
| 78 | + # So in this case it should be ok to look at the "future" (which is actually the present) | |
| 79 | + # by shifting it back by displacement. | |
| 80 | + #dataframe['future_green'] = ichimoku['cloud_green'].shift(-displacement).fillna(0).astype('int') * 2 | |
| 81 | + | |
| 82 | + # The chikou_span is shifted into the past, so we need to be careful not to read the | |
| 83 | + # current value. But if we shift it forward again by displacement it should be safe to use. | |
| 84 | + # We're effectively "looking back" at where it normally appears on the chart. | |
| 85 | + #dataframe['chikou_high'] = ( | |
| 86 | + # (dataframe['chikou_span'] > dataframe['senkou_a']) & | |
| 87 | + # (dataframe['chikou_span'] > dataframe['senkou_b']) | |
| 88 | + # ).shift(displacement).fillna(0).astype('int') | |
| 89 | + | |
| 90 | + # DANGER ZONE END | |
| 91 | + | |
| 92 | + dataframe['go_long'] = ( | |
| 93 | + (dataframe['tenkan_sen'] > dataframe['kijun_sen']) & | |
| 94 | + (dataframe['close'] > dataframe['leading_senkou_span_a']) & | |
| 95 | + (dataframe['close'] > dataframe['leading_senkou_span_b']) | |
| 96 | + #& | |
| 97 | + #(dataframe['future_green'] > 0) & | |
| 98 | + #(dataframe['chikou_high'] > 0) | |
| 99 | + ).astype('int') * 3 | |
| 100 | + | |
| 101 | + def SSLChannels(dataframe, length = 7, mode='sma'): | |
| 102 | + df = dataframe.copy() | |
| 103 | + df['ATR'] = ta.ATR(df, timeperiod=14) | |
| 104 | + df['smaHigh'] = df['high'].rolling(length).mean() + df['ATR'] | |
| 105 | + df['smaLow'] = df['low'].rolling(length).mean() - df['ATR'] | |
| 106 | + df['hlv'] = np.where(df['close'] > df['smaHigh'], 1, np.where(df['close'] < df['smaLow'], -1, np.NAN)) | |
| 107 | + df['hlv'] = df['hlv'].ffill() | |
| 108 | + df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow']) | |
| 109 | + df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh']) | |
| 110 | + return df['sslDown'], df['sslUp'] | |
| 111 | + | |
| 112 | + ssl = SSLChannels(dataframe, 10) | |
| 113 | + dataframe['sslDown'] = ssl[0] | |
| 114 | + dataframe['sslUp'] = ssl[1] | |
| 115 | + | |
| 116 | + dataframe['max'] = dataframe['high'].rolling(3).max() | |
| 117 | + dataframe['min'] = dataframe['low'].rolling(6).min() | |
| 118 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 119 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 120 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(5, min_periods=1).sum() != 0,1,0) | |
| 121 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(5, min_periods=1).sum() != 0,1,0) | |
| 122 | + | |
| 123 | + return dataframe | |
| 124 | + | |
| 125 | + | |
| 126 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 127 | + | |
| 128 | + dataframe.loc[ | |
| 129 | + (qtpylib.crossed_above(dataframe['go_long'], 0)) & | |
| 130 | + (dataframe['sslUp'] > dataframe['sslDown']) & | |
| 131 | + (dataframe['up_trend'] == 1) | |
| 132 | + , | |
| 133 | + 'buy'] = 1 | |
| 134 | + | |
| 135 | + return dataframe | |
| 136 | + | |
| 137 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 138 | + | |
| 139 | + dataframe.loc[ | |
| 140 | + (qtpylib.crossed_above(dataframe['sslDown'], dataframe['sslUp'])) & | |
| 141 | + ( | |
| 142 | + (qtpylib.crossed_below(dataframe['tenkan_sen'], dataframe['kijun_sen'])) | |
| 143 | + | | |
| 144 | + (qtpylib.crossed_below(dataframe['close'], dataframe['kijun_sen'])) | |
| 145 | + ) | |
| 146 | + | |
| 147 | + , | |
| 148 | + 'sell'] = 1 | |
| 149 | + | |
| 150 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/Infinite_ROI.py +119 −0
| @@ -0,0 +1,119 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI | |
| 12 | +from statistics import mean | |
| 13 | +from cachetools import TTLCache | |
| 14 | +from scipy.optimize import curve_fit | |
| 15 | + | |
| 16 | + | |
| 17 | +class Schism(IStrategy): | |
| 18 | + """ | |
| 19 | + Strategy Configuration Items | |
| 20 | + """ | |
| 21 | + timeframe = '5m' | |
| 22 | + inf_timeframe = '1h' | |
| 23 | + | |
| 24 | + minimal_roi = { | |
| 25 | + "0": 0.05, | |
| 26 | + "10": 0.025, | |
| 27 | + "20": 0.015, | |
| 28 | + "30": 0.01, | |
| 29 | + "720": 0.005, | |
| 30 | + "1440": 0 | |
| 31 | + } | |
| 32 | + | |
| 33 | + dynamic_roi = { | |
| 34 | + 'enabled': True, | |
| 35 | + 'type': 'exponential', # linear, exponential, or connect | |
| 36 | + 'decay-rate': 0.015, # bigger is faster, recommended to graph f(t) = start-pct * e(-rate*t) | |
| 37 | + 'decay-time': 1440, # amount of time to reach zero, only relevant for linear decay | |
| 38 | + 'start': 0.10, # starting percentage | |
| 39 | + 'end': 0, # ending percentage | |
| 40 | + } | |
| 41 | + | |
| 42 | + """ | |
| 43 | + Informative Pair Definitions | |
| 44 | + """ | |
| 45 | + def informative_pairs(self): | |
| 46 | + | |
| 47 | + return informative_pairs | |
| 48 | + | |
| 49 | + """ | |
| 50 | + Indicator Definitions | |
| 51 | + """ | |
| 52 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 53 | + | |
| 54 | + return dataframe | |
| 55 | + | |
| 56 | + """ | |
| 57 | + Buy Trigger Signals | |
| 58 | + """ | |
| 59 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 60 | + | |
| 61 | + return dataframe | |
| 62 | + | |
| 63 | + """ | |
| 64 | + Sell Trigger Signals | |
| 65 | + """ | |
| 66 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 67 | + | |
| 68 | + return dataframe | |
| 69 | + | |
| 70 | + | |
| 71 | + """ | |
| 72 | + Override for default Freqtrade ROI table functionality | |
| 73 | + """ | |
| 74 | + def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 75 | + dynamic_roi = self.dynamic_roi | |
| 76 | + | |
| 77 | + # if the dynamic_roi dict is defined and enabled, do it, otherwise fallback to default functionality | |
| 78 | + if dynamic_roi and dynamic_roi['enabled']: | |
| 79 | + # linear decay: f(t) = start - (rate * t) | |
| 80 | + if dynamic_roi['type'] == 'linear': | |
| 81 | + rate = (dynamic_roi['start'] - dynamic_roi['end']) / dynamic_roi['decay-time'] | |
| 82 | + min_roi = max(dynamic_roi['end'], dynamic_roi['start'] - (rate * trade_dur)) | |
| 83 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 84 | + elif dynamic_roi['type'] == 'exponential': | |
| 85 | + min_roi = max(dynamic_roi['end'], dynamic_roi['start'] * np.exp(-dynamic_roi['decay-rate']*trade_dur)) | |
| 86 | + elif dynamic_roi['type'] == 'connect': | |
| 87 | + # connect the points in the defined table with lines | |
| 88 | + past_roi = list(filter(lambda x: x <= trade_dur, self.minimal_roi.keys())) | |
| 89 | + next_roi = list(filter(lambda x: x > trade_dur, self.minimal_roi.keys())) | |
| 90 | + if not past_roi: | |
| 91 | + return None, None | |
| 92 | + current_entry = max(past_roi) | |
| 93 | + # next entry | |
| 94 | + if not next_roi: | |
| 95 | + return current_entry, self.minimal_roi[current_entry] | |
| 96 | + # use the slope-intercept formula between the two points in the roi table we are between | |
| 97 | + else: | |
| 98 | + next_entry = min(next_roi) | |
| 99 | + # y = mx + b | |
| 100 | + x1 = current_entry | |
| 101 | + x2 = next_entry | |
| 102 | + y1 = self.minimal_roi[current_entry] | |
| 103 | + y2 = self.minimal_roi[next_entry] | |
| 104 | + m = (y1-y2)/(x1-x2) | |
| 105 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 106 | + min_roi = (m * trade_dur) + b | |
| 107 | + else: | |
| 108 | + min_roi = 0 | |
| 109 | + | |
| 110 | + return trade_dur, min_roi | |
| 111 | + | |
| 112 | + else: | |
| 113 | + # Get highest entry in ROI dict where key <= trade-duration | |
| 114 | + roi_list = list(filter(lambda x: x <= trade_dur, self.minimal_roi.keys())) | |
| 115 | + if not roi_list: | |
| 116 | + return None, None | |
| 117 | + roi_entry = max(roi_list) | |
| 118 | + return roi_entry, self.minimal_roi[roi_entry] | |
| 119 | + | |
| No newline at the end of the file |
added strategies/old/KAMACCIRSI.py +227 −0
| @@ -0,0 +1,227 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +import numpy as np # noqa | |
| 6 | +import pandas as pd # noqa | |
| 7 | +from pandas import DataFrame | |
| 8 | + | |
| 9 | +from freqtrade.strategy import IStrategy | |
| 10 | + | |
| 11 | +# -------------------------------- | |
| 12 | +# Add your lib to import here | |
| 13 | +import talib.abstract as ta | |
| 14 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 15 | + | |
| 16 | + | |
| 17 | +class KAMACCIRSI_new(IStrategy): | |
| 18 | + """ | |
| 19 | + author@: werkkrew | |
| 20 | + github@: https://github.com/werkkrew/freqtrade-strategies | |
| 21 | + | |
| 22 | + Strategy using 3 indicators with fully customizable parameters and full hyperopt support | |
| 23 | + including indicator periods as well as cross points. | |
| 24 | + | |
| 25 | + There is nothing groundbreaking about this strategy, how it works, or what it does. | |
| 26 | + It was mostly an experiment for me to learn Freqtrade strategies and hyperopt development. | |
| 27 | + | |
| 28 | + Default hyperopt defined parameters below were done on 60 days of data from Kraken against 20 BTC pairs | |
| 29 | + using the SharpeHyperOptLoss loss function. | |
| 30 | + | |
| 31 | + Suggestions and improvements are welcome! | |
| 32 | + | |
| 33 | + Supports selling via strategy, as well as ROI and Stoploss/Trailing Stoploss | |
| 34 | + | |
| 35 | + Indicators Used: | |
| 36 | + KAMA "Kaufman Adaptive Moving Average" (Short Duration) | |
| 37 | + KAMA (Long Duration) | |
| 38 | + CCI "Commodity Channel Index" | |
| 39 | + RSI "Relative Strength Index" | |
| 40 | + | |
| 41 | + Buy Strategy: | |
| 42 | + kama-cross OR kama-slope | |
| 43 | + kama-short > kama-long | |
| 44 | + kama-long-slope > 1 | |
| 45 | + cci-enabled? | |
| 46 | + cci > X | |
| 47 | + rsi-enabled? | |
| 48 | + rsi > Y | |
| 49 | + | |
| 50 | + Sell Strategy: | |
| 51 | + kama-cross OR kama-slope | |
| 52 | + kama-short < kama-long | |
| 53 | + kama-long-slope < 1 | |
| 54 | + cci-enabled? | |
| 55 | + cci < A | |
| 56 | + rsi-enabled? | |
| 57 | + rsi < B | |
| 58 | + """ | |
| 59 | + # Strategy interface version - allow new iterations of the strategy interface. | |
| 60 | + # Check the documentation or the Sample strategy to get the latest version. | |
| 61 | + INTERFACE_VERSION = 2 | |
| 62 | + | |
| 63 | + """ | |
| 64 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 65 | + """ | |
| 66 | + | |
| 67 | + #* 22/50: 1 trades. 0/0/1 Wins/Draws/Losses. Avg profit -7.18%. Median profit -7.18%. Total profit -0.00007190 BTC ( -7.18Σ%). Avg duration 0.0 min. Objective: 1.88236 | |
| 68 | + | |
| 69 | + # Buy hyperspace params: | |
| 70 | + buy_params = { | |
| 71 | + 'cci-enabled': True, | |
| 72 | + 'cci-limit': 187, | |
| 73 | + 'kama-trigger': 'cross', | |
| 74 | + 'rsi-enabled': True, | |
| 75 | + 'rsi-limit': 78 | |
| 76 | + } | |
| 77 | + | |
| 78 | + # Sell hyperspace params: | |
| 79 | + sell_params = { | |
| 80 | + 'sell-cci-enabled': True, | |
| 81 | + 'sell-cci-limit': -124, | |
| 82 | + 'sell-kama-trigger': 'cross', | |
| 83 | + 'sell-rsi-enabled': False, | |
| 84 | + 'sell-rsi-limit': 40 | |
| 85 | + } | |
| 86 | + | |
| 87 | + # ROI table: | |
| 88 | + minimal_roi = { | |
| 89 | + "0": 0.06674, | |
| 90 | + "14": 0.05142, | |
| 91 | + "59": 0.01717, | |
| 92 | + "137": 0 | |
| 93 | + } | |
| 94 | + | |
| 95 | + # Stoploss: | |
| 96 | + stoploss = -0.11084 | |
| 97 | + | |
| 98 | + # Trailing stop: | |
| 99 | + trailing_stop = True | |
| 100 | + trailing_stop_positive = 0.19192 | |
| 101 | + trailing_stop_positive_offset = 0.25216 | |
| 102 | + trailing_only_offset_is_reached = False | |
| 103 | + | |
| 104 | + | |
| 105 | + """ | |
| 106 | + END HYPEROPT | |
| 107 | + """ | |
| 108 | + | |
| 109 | + timeframe = '5m' | |
| 110 | + | |
| 111 | + # Make sure these match or are not overridden in config | |
| 112 | + use_sell_signal = True | |
| 113 | + sell_profit_only = False | |
| 114 | + sell_profit_offset = 0.0 | |
| 115 | + ignore_roi_if_buy_signal = True | |
| 116 | + | |
| 117 | + # Run "populate_indicators()" only for new candle. | |
| 118 | + process_only_new_candles = False | |
| 119 | + | |
| 120 | + # Number of candles the strategy requires before producing valid signals | |
| 121 | + # Set this to the highest period value in the indicator_params dict or highest of the ranges in the hyperopt settings (default: 72) | |
| 122 | + startup_candle_count: int = 72 | |
| 123 | + | |
| 124 | + """ | |
| 125 | + Populate all of the indicators we need (note: indicators are separate for buy/sell) | |
| 126 | + """ | |
| 127 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 128 | + """ | |
| 129 | + Dynamic TA indicators | |
| 130 | + Used so hyperopt can optimized around the period of various indicators | |
| 131 | + """ | |
| 132 | + dataframe['kama-short'] = ta.KAMA(dataframe, timeperiod=5) | |
| 133 | + dataframe['kama-long'] = ta.KAMA(dataframe, timeperiod=20) | |
| 134 | + | |
| 135 | + dataframe['cci'] = ta.CCI(dataframe, timeperiod=21) | |
| 136 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) | |
| 137 | + | |
| 138 | + return dataframe | |
| 139 | + | |
| 140 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 141 | + params = self.buy_params | |
| 142 | + | |
| 143 | + conditions = [] | |
| 144 | + # Guards | |
| 145 | + if params.get('rsi-enabled'): | |
| 146 | + conditions.append( | |
| 147 | + ( | |
| 148 | + qtpylib.crossed_above(dataframe['rsi'], params['rsi-limit']) | | |
| 149 | + qtpylib.crossed_above(dataframe['rsi'].shift(1), params['rsi-limit']) | | |
| 150 | + qtpylib.crossed_above(dataframe['rsi'].shift(2), params['rsi-limit']) | |
| 151 | + ) & | |
| 152 | + ( | |
| 153 | + dataframe['rsi'].gt(params['rsi-limit']) | |
| 154 | + ) | |
| 155 | + ) | |
| 156 | + if params.get('cci-enabled'): | |
| 157 | + conditions.append( | |
| 158 | + ( | |
| 159 | + qtpylib.crossed_above(dataframe['cci'], params['cci-limit']) | | |
| 160 | + qtpylib.crossed_above(dataframe['cci'].shift(1), params['cci-limit']) | | |
| 161 | + qtpylib.crossed_above(dataframe['cci'].shift(2), params['cci-limit']) | |
| 162 | + ) & | |
| 163 | + ( | |
| 164 | + dataframe['cci'].gt(params['cci-limit']) | |
| 165 | + ) | |
| 166 | + ) | |
| 167 | + | |
| 168 | + # Triggers | |
| 169 | + if params.get('kama-trigger') == 'cross': | |
| 170 | + conditions.append(qtpylib.crossed_above(dataframe['kama-short'], dataframe['kama-long'])) | |
| 171 | + if params.get('kama-trigger') == 'slope': | |
| 172 | + conditions.append(dataframe['kama-long'] > dataframe['kama-long'].shift(1)) | |
| 173 | + | |
| 174 | + # Check that volume is not 0 | |
| 175 | + conditions.append(dataframe['volume'] > 0) | |
| 176 | + | |
| 177 | + if conditions: | |
| 178 | + dataframe.loc[ | |
| 179 | + reduce(lambda x, y: x & y, conditions), | |
| 180 | + 'buy'] = 1 | |
| 181 | + | |
| 182 | + return dataframe | |
| 183 | + | |
| 184 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 185 | + params = self.sell_params | |
| 186 | + | |
| 187 | + conditions = [] | |
| 188 | + # Guards | |
| 189 | + if params.get('sell-rsi-enabled'): | |
| 190 | + conditions.append( | |
| 191 | + ( | |
| 192 | + qtpylib.crossed_below(dataframe['rsi'], params['sell-rsi-limit']) | | |
| 193 | + qtpylib.crossed_below(dataframe['rsi'].shift(1), params['sell-rsi-limit']) | | |
| 194 | + qtpylib.crossed_below(dataframe['rsi'].shift(2), params['sell-rsi-limit']) | |
| 195 | + ) & | |
| 196 | + ( | |
| 197 | + dataframe['rsi'].lt(params['sell-rsi-limit']) | |
| 198 | + ) | |
| 199 | + ) | |
| 200 | + if params.get('sell-cci-enabled'): | |
| 201 | + conditions.append( | |
| 202 | + ( | |
| 203 | + qtpylib.crossed_below(dataframe['cci'], params['sell-cci-limit']) | | |
| 204 | + qtpylib.crossed_below(dataframe['cci'].shift(1), params['sell-cci-limit']) | | |
| 205 | + qtpylib.crossed_below(dataframe['cci'].shift(2), params['sell-cci-limit']) | |
| 206 | + ) & | |
| 207 | + ( | |
| 208 | + dataframe['cci'].lt(params['sell-cci-limit']) | |
| 209 | + ) | |
| 210 | + ) | |
| 211 | + | |
| 212 | + # Triggers | |
| 213 | + if params.get('sell-kama-trigger') == 'cross': | |
| 214 | + conditions.append(qtpylib.crossed_below(dataframe['kama-short'], dataframe['kama-long'])) | |
| 215 | + if params.get('sell-kama-trigger') == 'slope': | |
| 216 | + conditions.append(dataframe['kama-long'] < dataframe['kama-long'].shift(1)) | |
| 217 | + | |
| 218 | + # Check that the candle had volume | |
| 219 | + conditions.append(dataframe['volume'] > 0) | |
| 220 | + | |
| 221 | + if conditions: | |
| 222 | + dataframe.loc[ | |
| 223 | + reduce(lambda x, y: x & y, conditions), | |
| 224 | + 'sell'] = 1 | |
| 225 | + | |
| 226 | + return dataframe | |
| 227 | + | |
| No newline at the end of the file |
added strategies/old/KamaRsi2.py +209 −0
| @@ -0,0 +1,209 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 3 | +import numpy as np | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | + | |
| 12 | + | |
| 13 | +""" | |
| 14 | +Supertrend Indicator | |
| 15 | +adapted for freqtrade | |
| 16 | +from: https://github.com/freqtrade/freqtrade-strategies/issues/30 | |
| 17 | +ref: https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ | |
| 18 | +ATR: https://github.com/freqtrade/technical/issues/26 | |
| 19 | +""" | |
| 20 | +def supertrend(dataframe, multiplier=3, period=10): | |
| 21 | + | |
| 22 | + df = dataframe.copy() | |
| 23 | + | |
| 24 | + df['TR'] = ta.TRANGE(df) | |
| 25 | + df['ATR'] = df['TR'].ewm(alpha=1 / period).mean() | |
| 26 | + | |
| 27 | + #atr = 'ATR_' + str(period) | |
| 28 | + st = 'ST_' + str(period) + '_' + str(multiplier) | |
| 29 | + stx = 'STX_' + str(period) + '_' + str(multiplier) | |
| 30 | + | |
| 31 | + # Compute basic upper and lower bands | |
| 32 | + df['basic_ub'] = (df['high'] + df['low']) / 2 + multiplier * df['ATR'] | |
| 33 | + df['basic_lb'] = (df['high'] + df['low']) / 2 - multiplier * df['ATR'] | |
| 34 | + | |
| 35 | + # Compute final upper and lower bands | |
| 36 | + df['final_ub'] = 0.00 | |
| 37 | + df['final_lb'] = 0.00 | |
| 38 | + for i in range(period, len(df)): | |
| 39 | + df['final_ub'].iat[i] = df['basic_ub'].iat[i] if df['basic_ub'].iat[i] < df['final_ub'].iat[i - 1] or df['close'].iat[i - 1] > df['final_ub'].iat[i - 1] else df['final_ub'].iat[i - 1] | |
| 40 | + df['final_lb'].iat[i] = df['basic_lb'].iat[i] if df['basic_lb'].iat[i] > df['final_lb'].iat[i - 1] or df['close'].iat[i - 1] < df['final_lb'].iat[i - 1] else df['final_lb'].iat[i - 1] | |
| 41 | + | |
| 42 | + # Set the Supertrend value | |
| 43 | + df[st] = 0.00 | |
| 44 | + for i in range(period, len(df)): | |
| 45 | + df[st].iat[i] = df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[i] <= df['final_ub'].iat[i] else \ | |
| 46 | + df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[i] > df['final_ub'].iat[i] else \ | |
| 47 | + df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] >= df['final_lb'].iat[i] else \ | |
| 48 | + df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] < df['final_lb'].iat[i] else 0.00 | |
| 49 | + | |
| 50 | + # Mark the trend direction up/down | |
| 51 | + df[stx] = np.where((df[st] > 0.00), np.where((df['close'] < df[st]), 'down', 'up'), np.NaN) | |
| 52 | + | |
| 53 | + # Remove basic and final bands from the columns | |
| 54 | + df.drop(['basic_ub', 'basic_lb', 'final_ub', 'final_lb'], inplace=True, axis=1) | |
| 55 | + | |
| 56 | + df.fillna(0, inplace=True) | |
| 57 | + | |
| 58 | + return DataFrame(index=df.index, data={ | |
| 59 | + 'ST' : df[st], | |
| 60 | + 'STX' : df[stx] | |
| 61 | + }) | |
| 62 | + | |
| 63 | +class Kamaflage(IStrategy): | |
| 64 | + | |
| 65 | + """ | |
| 66 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 67 | + """ | |
| 68 | + # Buy hyperspace params: | |
| 69 | + buy_params = { | |
| 70 | + 'rsi-buy-trigger': 10, | |
| 71 | + 'cci-buy-trigger': -100, | |
| 72 | + 'buy-method': 'both', # trend, rsi2, both | |
| 73 | + 'buy-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 74 | + } | |
| 75 | + | |
| 76 | + # Sell hyperspace params: | |
| 77 | + sell_params = { | |
| 78 | + 'rsi-sell-trigger': 90, | |
| 79 | + 'cci-sell-trigger': 100, | |
| 80 | + 'sell-method': 'both', # trend, rsi2, both | |
| 81 | + 'sell-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 82 | + } | |
| 83 | + | |
| 84 | + # ROI table: | |
| 85 | + # ROI is not used in the traditional way in the strategy and is | |
| 86 | + # attempted to be overridden by "ignore_roi_if_buy_signal" on strong upward trends | |
| 87 | + minimal_roi = { | |
| 88 | + "0": 1 | |
| 89 | + } | |
| 90 | + | |
| 91 | + stoploss = -1 | |
| 92 | + | |
| 93 | + """ | |
| 94 | + END HYPEROPT | |
| 95 | + """ | |
| 96 | + | |
| 97 | + timeframe = '5m' | |
| 98 | + | |
| 99 | + use_sell_signal = True | |
| 100 | + sell_profit_only = False | |
| 101 | + sell_profit_offset = 0.01 | |
| 102 | + | |
| 103 | + # this must be true for this strategy to work as intended | |
| 104 | + ignore_roi_if_buy_signal = True | |
| 105 | + | |
| 106 | + process_only_new_candles = False | |
| 107 | + | |
| 108 | + startup_candle_count: int = 200 | |
| 109 | + | |
| 110 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 111 | + | |
| 112 | + dataframe['ohlc4'] = ta.AVGPRICE(dataframe) | |
| 113 | + dataframe['hlc3'] = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3 | |
| 114 | + dataframe['hl2'] = (dataframe['high'] + dataframe['low']) / 2 | |
| 115 | + | |
| 116 | + dataframe['kama-short'] = ta.KAMA(dataframe, timeperiod=5) | |
| 117 | + dataframe['kama-long'] = ta.KAMA(dataframe, timeperiod=200) | |
| 118 | + | |
| 119 | + dataframe['cci'] = ta.CCI(dataframe, timeperiod=5) | |
| 120 | + dataframe['rsi'] = ta.RSI(dataframe['ohlc4'], timeperiod=2) | |
| 121 | + | |
| 122 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 123 | + | |
| 124 | + # st = supertrend(dataframe, multiplier=1, period=10) | |
| 125 | + | |
| 126 | + # dataframe['supertrend'] = st['ST'] | |
| 127 | + # dataframe['supertrend-direction'] = st['STX'] | |
| 128 | + | |
| 129 | + return dataframe | |
| 130 | + | |
| 131 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 132 | + params = self.buy_params | |
| 133 | + | |
| 134 | + trades = False | |
| 135 | + | |
| 136 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 137 | + trades = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 138 | + | |
| 139 | + conditions = [] | |
| 140 | + | |
| 141 | + # if this is a fresh buy | |
| 142 | + if not trades: | |
| 143 | + if params['buy-method'] == 'rsi2' or params['buy-method'] == 'both': | |
| 144 | + conditions.append(dataframe[params['buy-price']] > dataframe['kama-long']) | |
| 145 | + conditions.append(dataframe['close'] < dataframe['kama-short']) | |
| 146 | + conditions.append(dataframe['rsi'] < params['rsi-buy-trigger']) | |
| 147 | + conditions.append(dataframe['cci'] < params['cci-buy-trigger']) | |
| 148 | + | |
| 149 | + if params['buy-method'] == 'trend' or params['buy-method'] == 'both': | |
| 150 | + conditions.append(dataframe[params['buy-price']] > dataframe['sar']) | |
| 151 | + # conditions.append(dataframe[params['buy-price']] > dataframe['supertrend']) | |
| 152 | + | |
| 153 | + # if this is an existing trade we want to extract more ROI from | |
| 154 | + # note: this doesn't work in backtesting and strategy will use normal ROI | |
| 155 | + else: | |
| 156 | + conditions.append(dataframe['ohlc4'] > dataframe['sar']) | |
| 157 | + # conditions.append(dataframe['ohlc4'] > dataframe['supertrend']) | |
| 158 | + | |
| 159 | + conditions.append(dataframe['volume'] > 0) | |
| 160 | + | |
| 161 | + if conditions: | |
| 162 | + dataframe.loc[ | |
| 163 | + reduce(lambda x, y: x & y, conditions), | |
| 164 | + 'buy'] = 1 | |
| 165 | + | |
| 166 | + return dataframe | |
| 167 | + | |
| 168 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 169 | + params = self.sell_params | |
| 170 | + | |
| 171 | + conditions = [] | |
| 172 | + | |
| 173 | + if params['sell-method'] == 'rsi2' or params['sell-method'] == 'both': | |
| 174 | + # conditions.append(dataframe[params['sell-price']] < dataframe['kama-long']) | |
| 175 | + conditions.append(dataframe['close'] > dataframe['kama-short']) | |
| 176 | + conditions.append(dataframe['rsi'] > params['rsi-sell-trigger']) | |
| 177 | + conditions.append(dataframe['cci'] > params['cci-sell-trigger']) | |
| 178 | + if params['sell-method'] == 'trend' or params['sell-method'] == 'both': | |
| 179 | + conditions.append(dataframe[params['sell-price']] < dataframe['sar']) | |
| 180 | + # conditions.append(dataframe[params['sell-price']] < dataframe['supertrend']) | |
| 181 | + | |
| 182 | + conditions.append(dataframe['volume'] > 0) | |
| 183 | + | |
| 184 | + if conditions: | |
| 185 | + dataframe.loc[ | |
| 186 | + reduce(lambda x, y: x & y, conditions), | |
| 187 | + 'sell'] = 1 | |
| 188 | + | |
| 189 | + return dataframe | |
| 190 | + | |
| 191 | + """ | |
| 192 | + Additional buy/sell timeout override if price drifts | |
| 193 | + """ | |
| 194 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 195 | + ob = self.dp.orderbook(pair, 1) | |
| 196 | + current_price = ob['bids'][0][0] | |
| 197 | + # Cancel buy order if price is more than 1% above the order. | |
| 198 | + if current_price > order['price'] * 1.01: | |
| 199 | + return True | |
| 200 | + return False | |
| 201 | + | |
| 202 | + | |
| 203 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 204 | + ob = self.dp.orderbook(pair, 1) | |
| 205 | + current_price = ob['asks'][0][0] | |
| 206 | + # Cancel sell order if price is more than 1% below the order. | |
| 207 | + if current_price < order['price'] * 0.99: | |
| 208 | + return True | |
| 209 | + return False | |
| No newline at the end of the file |
added strategies/old/Kamaflage.py +173 −0
| @@ -0,0 +1,173 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 3 | +import numpy as np | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI, VIDYA | |
| 12 | + | |
| 13 | + | |
| 14 | +class Kamaflage(IStrategy): | |
| 15 | + | |
| 16 | + """ | |
| 17 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 18 | + """ | |
| 19 | + | |
| 20 | + buy_params = { | |
| 21 | + 'macd': 0, | |
| 22 | + 'macdhist': 0, | |
| 23 | + 'rmi': 50 | |
| 24 | + } | |
| 25 | + | |
| 26 | + sell_params = { | |
| 27 | + | |
| 28 | + } | |
| 29 | + | |
| 30 | + minimal_roi = { | |
| 31 | + "0": 0.15, | |
| 32 | + "10": 0.10, | |
| 33 | + "20": 0.05, | |
| 34 | + "30": 0.025, | |
| 35 | + "60": 0.01 | |
| 36 | + } | |
| 37 | + | |
| 38 | + # Stoploss: | |
| 39 | + stoploss = -1 | |
| 40 | + | |
| 41 | + # Trailing stop: | |
| 42 | + trailing_stop = True | |
| 43 | + trailing_stop_positive = 0.01125 | |
| 44 | + trailing_stop_positive_offset = 0.04673 | |
| 45 | + trailing_only_offset_is_reached = True | |
| 46 | + | |
| 47 | + """ | |
| 48 | + END HYPEROPT | |
| 49 | + """ | |
| 50 | + | |
| 51 | + timeframe = '5m' | |
| 52 | + | |
| 53 | + use_sell_signal = True | |
| 54 | + sell_profit_only = False | |
| 55 | + # sell_profit_offset = 0.01 | |
| 56 | + ignore_roi_if_buy_signal = True | |
| 57 | + | |
| 58 | + process_only_new_candles = False | |
| 59 | + | |
| 60 | + startup_candle_count: int = 20 | |
| 61 | + | |
| 62 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 63 | + | |
| 64 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 65 | + dataframe['rmi'] = RMI(dataframe) | |
| 66 | + dataframe['kama-3'] = ta.KAMA(dataframe, timeperiod=3) | |
| 67 | + dataframe['kama-21'] = ta.KAMA(dataframe, timeperiod=21) | |
| 68 | + | |
| 69 | + macd = ta.MACD(dataframe) | |
| 70 | + dataframe['macd'] = macd['macd'] | |
| 71 | + dataframe['macdsignal'] = macd['macdsignal'] | |
| 72 | + dataframe['macdhist'] = macd['macdhist'] | |
| 73 | + | |
| 74 | + dataframe['volume_ma'] = dataframe['volume'].rolling(window=24).mean() | |
| 75 | + | |
| 76 | + | |
| 77 | + return dataframe | |
| 78 | + | |
| 79 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 80 | + params = self.buy_params | |
| 81 | + conditions = [] | |
| 82 | + | |
| 83 | + active_trade = False | |
| 84 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 85 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 86 | + | |
| 87 | + if not active_trade: | |
| 88 | + conditions.append(dataframe['kama-3'] > dataframe['kama-21']) | |
| 89 | + conditions.append(dataframe['macd'] > dataframe['macdsignal']) | |
| 90 | + conditions.append(dataframe['macd'] > params['macd']) | |
| 91 | + conditions.append(dataframe['macdhist'] > params['macdhist']) | |
| 92 | + conditions.append(dataframe['rmi'] > dataframe['rmi'].shift()) | |
| 93 | + conditions.append(dataframe['rmi'] > params['rmi']) | |
| 94 | + conditions.append(dataframe['volume'] < (dataframe['volume_ma'] * 20)) | |
| 95 | + else: | |
| 96 | + conditions.append(dataframe['close'] > dataframe['sar']) | |
| 97 | + conditions.append(dataframe['rmi'] >= 75) | |
| 98 | + | |
| 99 | + conditions.append(dataframe['volume'] > 0) | |
| 100 | + | |
| 101 | + if conditions: | |
| 102 | + dataframe.loc[ | |
| 103 | + reduce(lambda x, y: x & y, conditions), | |
| 104 | + 'buy'] = 1 | |
| 105 | + | |
| 106 | + return dataframe | |
| 107 | + | |
| 108 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 109 | + params = self.sell_params | |
| 110 | + conditions = [] | |
| 111 | + | |
| 112 | + active_trade = False | |
| 113 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 114 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 115 | + | |
| 116 | + if active_trade: | |
| 117 | + ob = self.dp.orderbook(metadata['pair'], 1) | |
| 118 | + current_price = ob['asks'][0][0] | |
| 119 | + current_profit = active_trade[0].calc_profit_ratio(rate=current_price) | |
| 120 | + | |
| 121 | + conditions.append( | |
| 122 | + (dataframe['buy'] == 0) & | |
| 123 | + (dataframe['rmi'] < 30) & | |
| 124 | + (current_profit > -0.03) & | |
| 125 | + (dataframe['volume'].gt(0)) | |
| 126 | + ) | |
| 127 | + | |
| 128 | + if conditions: | |
| 129 | + dataframe.loc[ | |
| 130 | + reduce(lambda x, y: x & y, conditions), | |
| 131 | + 'sell'] = 1 | |
| 132 | + else: | |
| 133 | + dataframe['sell'] = 0 | |
| 134 | + | |
| 135 | + return dataframe | |
| 136 | + | |
| 137 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 138 | + ob = self.dp.orderbook(pair, 1) | |
| 139 | + current_price = ob['bids'][0][0] | |
| 140 | + # Cancel buy order if price is more than 1% above the order. | |
| 141 | + if current_price > order['price'] * 1.01: | |
| 142 | + return True | |
| 143 | + return False | |
| 144 | + | |
| 145 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 146 | + ob = self.dp.orderbook(pair, 1) | |
| 147 | + current_price = ob['asks'][0][0] | |
| 148 | + # Cancel sell order if price is more than 1% below the order. | |
| 149 | + if current_price < order['price'] * 0.99: | |
| 150 | + return True | |
| 151 | + return False | |
| 152 | + | |
| 153 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 154 | + ob = self.dp.orderbook(pair, 1) | |
| 155 | + current_price = ob['asks'][0][0] | |
| 156 | + # Cancel buy order if price is more than 1% above the order. | |
| 157 | + if current_price > rate * 1.01: | |
| 158 | + return False | |
| 159 | + return True | |
| 160 | + | |
| 161 | + """ | |
| 162 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 163 | + _, roi = self.min_roi_reached_entry(0) | |
| 164 | + | |
| 165 | + if roi is None: | |
| 166 | + if Trade.max_rate >= Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 167 | + return False | |
| 168 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate < Trade.open_rate: | |
| 169 | + return False | |
| 170 | + if Trade.max_rate < Trade.rate * 0.8 and Trade.rate > Trade.open_rate: | |
| 171 | + return current_profit > roi | |
| 172 | + return False | |
| 173 | + """ | |
| No newline at the end of the file |
added strategies/old/Lateralus.py +251 −0
| @@ -0,0 +1,251 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from freqtrade.strategy import merge_informative_pair | |
| 6 | +from pandas import DataFrame, Series | |
| 7 | +from functools import reduce | |
| 8 | +from datetime import datetime | |
| 9 | +from freqtrade.persistence import Trade | |
| 10 | +from technical.indicators import RMI | |
| 11 | +from statistics import mean | |
| 12 | + | |
| 13 | +""" | |
| 14 | +TODO: | |
| 15 | + - Better buy signal. | |
| 16 | + - Potentially leverage an external data source? | |
| 17 | +""" | |
| 18 | + | |
| 19 | +class Lateralus(IStrategy): | |
| 20 | + | |
| 21 | + timeframe = '5m' | |
| 22 | + inf_timeframe = '1h' | |
| 23 | + | |
| 24 | + buy_params = { | |
| 25 | + 'bbdelta-close': 0.00865, | |
| 26 | + 'bbdelta-tail': 0.82205, | |
| 27 | + 'close-bblower': 0.0063, | |
| 28 | + 'closedelta-close': 0.00697, | |
| 29 | + 'volume': 16 | |
| 30 | + } | |
| 31 | + | |
| 32 | + # ROI table: | |
| 33 | + minimal_roi = { | |
| 34 | + "0": 0.015 | |
| 35 | + } | |
| 36 | + | |
| 37 | + # Stoploss: | |
| 38 | + stoploss = -0.085 | |
| 39 | + | |
| 40 | + use_sell_signal = True | |
| 41 | + sell_profit_only = False | |
| 42 | + ignore_roi_if_buy_signal = True | |
| 43 | + | |
| 44 | + #startup_candle_count: int = 55 | |
| 45 | + | |
| 46 | + custom_trade_info = {} | |
| 47 | + | |
| 48 | + def informative_pairs(self): | |
| 49 | + pairs = self.dp.current_whitelist() | |
| 50 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 51 | + return informative_pairs | |
| 52 | + | |
| 53 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 54 | + | |
| 55 | + # Misc. calculations regarding existing open positions (reset on every loop iteration) | |
| 56 | + self.custom_trade_info[metadata['pair']] = trade_data = {} | |
| 57 | + trade_data['active_trade'] = trade_data['other_trades'] = False | |
| 58 | + | |
| 59 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 60 | + | |
| 61 | + active_trade = Trade.get_trades([Trade.pair == metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 62 | + other_trades = Trade.get_trades([Trade.pair != metadata['pair'], Trade.is_open.is_(True),]).all() | |
| 63 | + | |
| 64 | + if active_trade: | |
| 65 | + current_rate = self.get_current_price(metadata['pair']) | |
| 66 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 67 | + trade_data['active_trade'] = True | |
| 68 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 69 | + trade_data['peak_profit'] = active_trade[0].calc_profit_ratio(active_trade[0].max_rate) | |
| 70 | + | |
| 71 | + if other_trades: | |
| 72 | + trade_data['other_trades'] = True | |
| 73 | + total_other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair)) for trade in other_trades) | |
| 74 | + trade_data['avg_other_profit'] = mean(total_other_profit) | |
| 75 | + | |
| 76 | + self.custom_trade_info[metadata['pair']] = trade_data | |
| 77 | + | |
| 78 | + # Set Up Bollinger Bands | |
| 79 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=10, stds=2.7) | |
| 80 | + dataframe['lower-bb1'] = bollinger['lower'] | |
| 81 | + dataframe['mid-bb1'] = bollinger['mid'] | |
| 82 | + | |
| 83 | + bollinger2 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=40, stds=1.1) | |
| 84 | + dataframe['lower-bb2'] = bollinger2['lower'] | |
| 85 | + dataframe['mid-bb2'] = bollinger['mid'] | |
| 86 | + | |
| 87 | + dataframe['bb1-delta'] = (dataframe['mid-bb1'] - dataframe['lower-bb1']).abs() | |
| 88 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 89 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 90 | + | |
| 91 | + # Set up other indicators | |
| 92 | + dataframe['volume-mean-slow'] = dataframe['volume'].rolling(window=24).mean() | |
| 93 | + dataframe['rmi-slow'] = RMI(dataframe, length=20, mom=5) | |
| 94 | + dataframe['rmi-fast'] = RMI(dataframe, length=9, mom=3) | |
| 95 | + dataframe['ema-slow'] = ta.EMA(dataframe, timeperiod=55) | |
| 96 | + | |
| 97 | + # Trend Calculations | |
| 98 | + dataframe['max'] = dataframe['high'].rolling(6).max() | |
| 99 | + dataframe['min'] = dataframe['low'].rolling(6).min() | |
| 100 | + dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0) | |
| 101 | + dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0) | |
| 102 | + dataframe['up_trend'] = np.where(dataframe['upper'].rolling(4, min_periods=1).sum() != 0,1,0) | |
| 103 | + dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(4, min_periods=1).sum() != 0,1,0) | |
| 104 | + | |
| 105 | + # Informative Timeframe Indicators | |
| 106 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 107 | + | |
| 108 | + informative['ema-fast'] = ta.EMA(informative, timeperiod=5) | |
| 109 | + informative['ema-slow'] = ta.EMA(informative, timeperiod=21) | |
| 110 | + | |
| 111 | + inf_macd = ta.MACD(informative) | |
| 112 | + informative['macd'] = inf_macd['macd'] | |
| 113 | + informative['macdsignal'] = inf_macd['macdsignal'] | |
| 114 | + informative['macdhist'] = inf_macd['macdhist'] | |
| 115 | + | |
| 116 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 117 | + | |
| 118 | + return dataframe | |
| 119 | + | |
| 120 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 121 | + params = self.buy_params | |
| 122 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 123 | + conditions = [] | |
| 124 | + | |
| 125 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 126 | + # when this buy signal is not present a sell can happen according to ROI table | |
| 127 | + if trade_data['active_trade']: | |
| 128 | + if (trade_data['peak_profit'] > 0): | |
| 129 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * 0.8)) | |
| 130 | + conditions.append(dataframe['rmi-slow'] >= 60) | |
| 131 | + | |
| 132 | + # Normal buy triggers that apply to new trades we want to enter | |
| 133 | + else: | |
| 134 | + conditions.append( | |
| 135 | + ( | |
| 136 | + (dataframe[f"ema-fast_{self.inf_timeframe}"] > dataframe[f"ema-slow_{self.inf_timeframe}"]) & | |
| 137 | + (dataframe[f"macd_{self.inf_timeframe}"] > dataframe[f"macdsignal_{self.inf_timeframe}"]) | |
| 138 | + ) & | |
| 139 | + (( | |
| 140 | + (dataframe['bb1-delta'] > (dataframe['close'] * params['bbdelta-close'])) & | |
| 141 | + (dataframe['closedelta'] > (dataframe['close'] * params['closedelta-close'])) & | |
| 142 | + (dataframe['tail'] < (dataframe['bb1-delta'] * params['bbdelta-tail'])) & | |
| 143 | + (dataframe['close'] < dataframe['lower-bb1'].shift()) & | |
| 144 | + (dataframe['close'] <= dataframe['close'].shift()) | |
| 145 | + ) | | |
| 146 | + ( | |
| 147 | + (dataframe['close'] < dataframe['ema-slow']) & | |
| 148 | + (dataframe['close'] < params['close-bblower'] * dataframe['lower-bb2']) & | |
| 149 | + (dataframe['volume'] < (dataframe['volume-mean-slow'].shift(1) * params['volume'])) | |
| 150 | + )) | |
| 151 | + ) | |
| 152 | + | |
| 153 | + # applies to both new buys and persisting buy signal | |
| 154 | + conditions.append(dataframe['volume'].gt(0)) | |
| 155 | + | |
| 156 | + if conditions: | |
| 157 | + dataframe.loc[ | |
| 158 | + reduce(lambda x, y: x & y, conditions), | |
| 159 | + 'buy'] = 1 | |
| 160 | + | |
| 161 | + return dataframe | |
| 162 | + | |
| 163 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 164 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 165 | + conditions = [] | |
| 166 | + | |
| 167 | + # if we are in an active trade for this pair | |
| 168 | + if trade_data['active_trade']: | |
| 169 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 170 | + conditions.append( | |
| 171 | + (trade_data['current_profit'] < 0) & | |
| 172 | + (trade_data['current_profit'] > self.stoploss) & | |
| 173 | + (dataframe['dn_trend'] == 1) & | |
| 174 | + (qtpylib.crossed_below(dataframe['rmi-fast'], 50)) & | |
| 175 | + (dataframe['volume'].gt(0)) | |
| 176 | + ) | |
| 177 | + | |
| 178 | + # if there are other open trades in addition to this one, consider the average profit | |
| 179 | + # across them all (not including this one), don't sell if entire market is down big and wait for recovery | |
| 180 | + if trade_data['other_trades']: | |
| 181 | + conditions.append(trade_data['avg_other_profit'] >= -0.005) | |
| 182 | + | |
| 183 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 184 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 185 | + # clogging up the charts and not having one leads the bot to crash | |
| 186 | + else: | |
| 187 | + conditions.append(dataframe['volume'].lt(0)) | |
| 188 | + | |
| 189 | + if conditions: | |
| 190 | + dataframe.loc[ | |
| 191 | + reduce(lambda x, y: x & y, conditions), | |
| 192 | + 'sell'] = 1 | |
| 193 | + | |
| 194 | + return dataframe | |
| 195 | + | |
| 196 | + """ | |
| 197 | + Custom methods | |
| 198 | + """ | |
| 199 | + def get_current_price(self, pair: str) -> float: | |
| 200 | + ticker = self.dp.ticker(pair) | |
| 201 | + current_price = ticker['last'] | |
| 202 | + | |
| 203 | + return current_price | |
| 204 | + | |
| 205 | + """ | |
| 206 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 207 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 208 | + """ | |
| 209 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 210 | + ob = self.dp.orderbook(pair, 1) | |
| 211 | + current_price = ob['bids'][0][0] | |
| 212 | + # Cancel buy order if price is more than 1% above the order. | |
| 213 | + if current_price > order['price'] * 1.01: | |
| 214 | + return True | |
| 215 | + return False | |
| 216 | + | |
| 217 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 218 | + ob = self.dp.orderbook(pair, 1) | |
| 219 | + current_price = ob['asks'][0][0] | |
| 220 | + # Cancel sell order if price is more than 1% below the order. | |
| 221 | + if current_price < order['price'] * 0.99: | |
| 222 | + return True | |
| 223 | + return False | |
| 224 | + | |
| 225 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 226 | + ob = self.dp.orderbook(pair, 1) | |
| 227 | + current_price = ob['asks'][0][0] | |
| 228 | + # Cancel buy order if price is more than 1% above the order. | |
| 229 | + if current_price > rate * 1.01: | |
| 230 | + return False | |
| 231 | + return True | |
| 232 | + | |
| 233 | + | |
| 234 | +class Lateralus_Slow(Lateralus): | |
| 235 | + | |
| 236 | + timeframe = '1h' | |
| 237 | + inf_timeframe = '4h' | |
| 238 | + | |
| 239 | + # ROI table: | |
| 240 | + minimal_roi = { | |
| 241 | + "0": 0.15, | |
| 242 | + "10": 0.10, | |
| 243 | + "20": 0.05, | |
| 244 | + "30": 0.025, | |
| 245 | + "60": 0.015, | |
| 246 | + "120": 0.005 | |
| 247 | + } | |
| 248 | + | |
| 249 | + # Stoploss: | |
| 250 | + stoploss = -0.085 | |
| 251 | + |
added strategies/old/Pmax.py +49 −0
| @@ -0,0 +1,49 @@ | ||
| 1 | +import numpy as np # noqa | |
| 2 | +import pandas as pd # noqa | |
| 3 | +from pandas import DataFrame | |
| 4 | +from technical.indicators import PMAX, zema | |
| 5 | +from typing import Dict, List | |
| 6 | +from functools import reduce | |
| 7 | +from freqtrade.strategy.interface import IStrategy | |
| 8 | + | |
| 9 | +# -------------------------------- | |
| 10 | +# Add your lib to import here | |
| 11 | +import talib.abstract as ta | |
| 12 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 13 | + | |
| 14 | + | |
| 15 | +class Pmax(IStrategy): | |
| 16 | + stoploss = -1 | |
| 17 | + timeframe = '5m' | |
| 18 | + | |
| 19 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 20 | + atrperiod = 10 | |
| 21 | + multiplier = 3 | |
| 22 | + matype = 9 | |
| 23 | + malength = 10 | |
| 24 | + source = 2 | |
| 25 | + | |
| 26 | + dataframe['ZLEMA'] = zema(dataframe, period=malength) | |
| 27 | + dataframe = PMAX(dataframe, atrperiod=atrperiod, multiplier=multiplier, malength=malength, matype=matype, source=source) | |
| 28 | + # print(dataframe.keys) | |
| 29 | + return dataframe | |
| 30 | + | |
| 31 | + | |
| 32 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 33 | + dataframe.loc[ | |
| 34 | + ( | |
| 35 | + (qtpylib.crossed_above(dataframe['ZLEMA'], dataframe['pm_40_3_40_9'])) | |
| 36 | + ), | |
| 37 | + 'buy'] = 1 | |
| 38 | + | |
| 39 | + return dataframe | |
| 40 | + | |
| 41 | + | |
| 42 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 43 | + dataframe.loc[ | |
| 44 | + ( | |
| 45 | + (qtpylib.crossed_below(dataframe['ZLEMA'], dataframe['pm_40_3_40_9'])) | |
| 46 | + ), | |
| 47 | + 'sell'] = 1 | |
| 48 | + | |
| 49 | + return dataframe |
added strategies/old/Renko.py +107 −0
| @@ -0,0 +1,107 @@ | ||
| 1 | +import talib.abstract as ta | |
| 2 | +from pandas import DataFrame, Series, DatetimeIndex, merge | |
| 3 | +import pandas as pd | |
| 4 | +import numpy as np | |
| 5 | +#import pdb | |
| 6 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 7 | +from freqtrade.strategy.interface import IStrategy | |
| 8 | +pd.set_option("display.precision", 10) | |
| 9 | + | |
| 10 | +class Renko(IStrategy): | |
| 11 | + | |
| 12 | + minimal_roi = { | |
| 13 | + "0": 100 | |
| 14 | + } | |
| 15 | + | |
| 16 | + stoploss = -100 | |
| 17 | + | |
| 18 | + timeframe = '15m' | |
| 19 | + | |
| 20 | + use_sell_signal = True | |
| 21 | + sell_profit_only = True | |
| 22 | + sell_profit_offset = 0.1 | |
| 23 | + ignore_roi_if_buy_signal = True | |
| 24 | + | |
| 25 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 26 | + | |
| 27 | + dataframe['ATR'] = ta.ATR(dataframe, timeperiod=5) | |
| 28 | + brick_size = np.mean(dataframe['ATR']) | |
| 29 | + columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'ATR'] | |
| 30 | + df = dataframe[columns] | |
| 31 | + cdf = pd.DataFrame( | |
| 32 | + columns=columns, | |
| 33 | + data=[], | |
| 34 | + ) | |
| 35 | + cdf.loc[0] = df.loc[0] | |
| 36 | + close = df.loc[0]['close'] | |
| 37 | + volume = df.loc[0]['volume'] | |
| 38 | + cdf.iloc[0, 1:] = [close - brick_size, close, close - brick_size, close, volume, brick_size] | |
| 39 | + cdf['trend'] = True | |
| 40 | + columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'ATR', 'trend'] | |
| 41 | + | |
| 42 | + for index, row in df.iterrows(): | |
| 43 | + if not np.isnan(row['ATR']): brick_size = row['ATR'] | |
| 44 | + close = row['close'] | |
| 45 | + date = row['date'] | |
| 46 | + volume = row['volume'] | |
| 47 | + row_p1 = cdf.iloc[-1] | |
| 48 | + trend = row_p1['trend'] | |
| 49 | + close_p1 = row_p1['close'] | |
| 50 | + bricks = int(np.nan_to_num((close - close_p1) / brick_size)) | |
| 51 | + data = [] | |
| 52 | + if trend and bricks >= 1: | |
| 53 | + for i in range(bricks): | |
| 54 | + r = [date, close_p1, close_p1 + brick_size, close_p1, close_p1 + brick_size, volume, brick_size, trend] | |
| 55 | + data.append(r) | |
| 56 | + close_p1 += brick_size | |
| 57 | + elif trend and bricks <= -2: | |
| 58 | + trend = not trend | |
| 59 | + bricks += 1 | |
| 60 | + close_p1 -= brick_size | |
| 61 | + for i in range(abs(bricks)): | |
| 62 | + r = [date, close_p1, close_p1, close_p1 - brick_size, close_p1 - brick_size, volume, brick_size, trend] | |
| 63 | + data.append(r) | |
| 64 | + close_p1 -= brick_size | |
| 65 | + elif not trend and bricks <= -1: | |
| 66 | + for i in range(abs(bricks)): | |
| 67 | + r = [date, close_p1, close_p1, close_p1 - brick_size, close_p1 - brick_size, volume, brick_size, trend] | |
| 68 | + data.append(r) | |
| 69 | + close_p1 -= brick_size | |
| 70 | + elif not trend and bricks >= 2: | |
| 71 | + trend = not trend | |
| 72 | + bricks -= 1 | |
| 73 | + close_p1 += brick_size | |
| 74 | + for i in range(abs(bricks)): | |
| 75 | + r = [date, close_p1, close_p1 + brick_size, close_p1, close_p1 + brick_size, volume, brick_size, trend] | |
| 76 | + data.append(r) | |
| 77 | + close_p1 += brick_size | |
| 78 | + else: | |
| 79 | + continue | |
| 80 | + | |
| 81 | + sdf = pd.DataFrame(data=data, columns=columns) | |
| 82 | + cdf = pd.concat([cdf, sdf]) | |
| 83 | + | |
| 84 | + renko_df = cdf.groupby(['date']).last() | |
| 85 | + renko_df = renko_df.reset_index() | |
| 86 | + renko_df['previous-trend'] = renko_df.trend.shift(1) | |
| 87 | + renko_df['previous-trend2'] = renko_df.trend.shift(2) | |
| 88 | + | |
| 89 | + return renko_df | |
| 90 | + | |
| 91 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 92 | + for index, row in dataframe.iterrows(): | |
| 93 | + if row['previous-trend'] == False and row['trend'] == True: | |
| 94 | + last_row = dataframe.loc[dataframe['date'] == row['date']][-1:] | |
| 95 | + dataframe.loc[dataframe.index== last_row.index.values[0], 'buy'] = 1 | |
| 96 | + if row['previous-trend'] == True and row['trend'] == True: | |
| 97 | + last_row = dataframe.loc[dataframe['date'] == row['date']][-1:] | |
| 98 | + dataframe.loc[dataframe.index== last_row.index.values[0], 'buy'] = 1 | |
| 99 | + else: | |
| 100 | + last_row = dataframe.loc[dataframe['date'] == row['date']][-1:] | |
| 101 | + dataframe.loc[dataframe.index== last_row.index.values[0], 'sell'] = 1 | |
| 102 | + | |
| 103 | + return dataframe | |
| 104 | + | |
| 105 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 106 | + | |
| 107 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/RenkoYolo.py +70 −0
| @@ -0,0 +1,70 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from pandas import DataFrame, DatetimeIndex, merge, Series | |
| 6 | + | |
| 7 | + | |
| 8 | +class RenkoYolo(IStrategy): | |
| 9 | + | |
| 10 | + # Buy hyperspace params: | |
| 11 | + buy_params = { | |
| 12 | + | |
| 13 | + } | |
| 14 | + | |
| 15 | + # Sell hyperspace params: | |
| 16 | + sell_params = { | |
| 17 | + | |
| 18 | + } | |
| 19 | + | |
| 20 | + # ROI table: | |
| 21 | + minimal_roi = { | |
| 22 | + "0": 0.03, | |
| 23 | + "7": 0.02, | |
| 24 | + "33": 0.01, | |
| 25 | + "71": 0.005 | |
| 26 | + } | |
| 27 | + | |
| 28 | + # Stoploss: | |
| 29 | + stoploss = -100 | |
| 30 | + | |
| 31 | + # Trailing stop: | |
| 32 | + trailing_stop = False | |
| 33 | + | |
| 34 | + timeframe = '15m' | |
| 35 | + | |
| 36 | + use_sell_signal = True | |
| 37 | + sell_profit_only = True | |
| 38 | + ignore_roi_if_buy_signal = True | |
| 39 | + | |
| 40 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 41 | + | |
| 42 | + dataframe['adx'] = ta.ADX(dataframe, timeperiod=90) #90 | |
| 43 | + aroon = ta.AROON(dataframe, timeperiod=60) #60 | |
| 44 | + | |
| 45 | + dataframe['aroon-down'] = aroon['aroondown'] | |
| 46 | + dataframe['aroon-up'] = aroon['aroonup'] | |
| 47 | + | |
| 48 | + return dataframe | |
| 49 | + | |
| 50 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 51 | + params = self.buy_params | |
| 52 | + | |
| 53 | + dataframe.loc[ | |
| 54 | + ( | |
| 55 | + (dataframe['adx'] > params['adx']) & | |
| 56 | + (dataframe['aroon-up'] > params['aroon-up']) & | |
| 57 | + (dataframe['aroon-down'] < params['aroon-down']) & | |
| 58 | + (dataframe['volume'] > 0) | |
| 59 | + ), | |
| 60 | + 'buy' | |
| 61 | + ] = 1 | |
| 62 | + | |
| 63 | + return dataframe | |
| 64 | + | |
| 65 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 66 | + """ | |
| 67 | + no sell signal | |
| 68 | + """ | |
| 69 | + dataframe['sell'] = 0 | |
| 70 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/Schism-0318.py +474 −0
| @@ -0,0 +1,474 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | +""" | |
| 18 | +TODO: | |
| 19 | + - Continue to hunt for a better all around buy signal. | |
| 20 | + - Existing signal to "buy the dip" seems to work well but would it be nice to have an additional | |
| 21 | + buy signal for strong upward trends without dips? | |
| 22 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 23 | + - Initial 24h range thing seems to be step 1 of this process, anything else we can do? | |
| 24 | + - Fibonacci Retracement for resistance/support levels? | |
| 25 | + - Tweak ROI Ride | |
| 26 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 27 | + - Tweak sell signal | |
| 28 | + - Continue to evaluate good circumstances to sell vs hold | |
| 29 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 30 | +""" | |
| 31 | + | |
| 32 | +class Schism(IStrategy): | |
| 33 | + """ | |
| 34 | + Strategy Configuration Items | |
| 35 | + """ | |
| 36 | + timeframe = '5m' | |
| 37 | + inf_timeframe = '1h' | |
| 38 | + | |
| 39 | + buy_params = { | |
| 40 | + 'inf-pct-adr': 0.81329, | |
| 41 | + 'inf-rsi': 11, | |
| 42 | + 'inf-stake-rmi': 7, | |
| 43 | + 'mp': 65, | |
| 44 | + 'rmi-fast': 32, | |
| 45 | + 'rmi-slow': 22, | |
| 46 | + 'tf-fiat-rsi': 84, | |
| 47 | + 'tf-stake-rsi': 29 | |
| 48 | + } | |
| 49 | + | |
| 50 | + sell_params = {} | |
| 51 | + | |
| 52 | + minimal_roi = { | |
| 53 | + "0": 0.10, | |
| 54 | + "15": 0.05, | |
| 55 | + "30": 0.025, | |
| 56 | + "60": 0.01, | |
| 57 | + "120": 0.005, | |
| 58 | + "1440": 0 | |
| 59 | + } | |
| 60 | + | |
| 61 | + dynamic_roi = { | |
| 62 | + 'dynamic_roi_enabled': False, | |
| 63 | + 'dynamic_roi_type': 'connect' | |
| 64 | + } | |
| 65 | + | |
| 66 | + stoploss = -0.20 | |
| 67 | + | |
| 68 | + # Probably don't change these | |
| 69 | + use_sell_signal = False | |
| 70 | + sell_profit_only = False | |
| 71 | + ignore_roi_if_buy_signal = True | |
| 72 | + | |
| 73 | + startup_candle_count: int = 72 | |
| 74 | + | |
| 75 | + # Custom Dicts for storing trade data and other custom things this strategy does | |
| 76 | + custom_trade_info = {} | |
| 77 | + custom_fiat = "USD" | |
| 78 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 79 | + | |
| 80 | + """ | |
| 81 | + Informative Pair Definitions | |
| 82 | + """ | |
| 83 | + def informative_pairs(self): | |
| 84 | + # add existing pairs from whitelist on the inf_timeframe | |
| 85 | + pairs = self.dp.current_whitelist() | |
| 86 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 87 | + | |
| 88 | + # add additional informative pairs based on certain stakes | |
| 89 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 90 | + for pair in pairs: | |
| 91 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) on base timeframe | |
| 92 | + coin, stake = pair.split('/') | |
| 93 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 94 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 95 | + | |
| 96 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) on base and inf timeframes | |
| 97 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 98 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 99 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 100 | + | |
| 101 | + return informative_pairs | |
| 102 | + | |
| 103 | + """ | |
| 104 | + Indicator Definitions | |
| 105 | + """ | |
| 106 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 107 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 108 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 109 | + | |
| 110 | + # Set up primary indicators | |
| 111 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 112 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 113 | + | |
| 114 | + # Momentum Pinball | |
| 115 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 116 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 117 | + | |
| 118 | + # Trend Calculations | |
| 119 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 120 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 121 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 122 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 123 | + | |
| 124 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 125 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 126 | + coin, stake = metadata['pair'].split('/') | |
| 127 | + fiat = self.custom_fiat | |
| 128 | + coin_fiat = f"{coin}/{fiat}" | |
| 129 | + stake_fiat = f"{stake}/{fiat}" | |
| 130 | + | |
| 131 | + # COIN/FIAT (e.g. XLM/USD) - timeframe | |
| 132 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 133 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 134 | + | |
| 135 | + # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe | |
| 136 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 137 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 138 | + | |
| 139 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 140 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 141 | + | |
| 142 | + # Informative indicators for current pair on inf_timeframe | |
| 143 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 144 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 145 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 146 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 147 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 148 | + | |
| 149 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 150 | + | |
| 151 | + return dataframe | |
| 152 | + | |
| 153 | + """ | |
| 154 | + Buy Trigger Signals | |
| 155 | + """ | |
| 156 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 157 | + params = self.buy_params | |
| 158 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 159 | + conditions = [] | |
| 160 | + | |
| 161 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 162 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 163 | + if trade_data['active_trade']: | |
| 164 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 165 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 166 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 167 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 168 | + | |
| 169 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 170 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 171 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 172 | + | |
| 173 | + # Normal buy triggers that apply to new trades we want to enter | |
| 174 | + else: | |
| 175 | + # Primary buy triggers | |
| 176 | + conditions.append( | |
| 177 | + # "buy the dip" based buy signal using momentum pinball and downward RMI | |
| 178 | + # informative timeframe conditions | |
| 179 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 180 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{self.inf_timeframe}"])) & | |
| 181 | + # default timeframe conditions | |
| 182 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 183 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 184 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 185 | + (dataframe['mp'] <= params['mp']) | |
| 186 | + ) | |
| 187 | + | |
| 188 | + # If the stake is BTC or ETH apply additional conditions | |
| 189 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 190 | + # default timeframe conditions | |
| 191 | + conditions.append( | |
| 192 | + (dataframe[f"{self.config['stake_currency']}_rsi"] <= params['tf-stake-rsi']) | | |
| 193 | + (dataframe[f"{self.custom_fiat}_rsi"] >= params['tf-fiat-rsi']) | |
| 194 | + ) | |
| 195 | + # informative timeframe conditions | |
| 196 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] <= params['inf-stake-rmi']) | |
| 197 | + | |
| 198 | + # Anything below here applies to persisting and new buy signal | |
| 199 | + conditions.append(dataframe['volume'].gt(0)) | |
| 200 | + | |
| 201 | + if conditions: | |
| 202 | + dataframe.loc[ | |
| 203 | + reduce(lambda x, y: x & y, conditions), | |
| 204 | + 'buy'] = 1 | |
| 205 | + | |
| 206 | + return dataframe | |
| 207 | + | |
| 208 | + """ | |
| 209 | + Sell Trigger Signals | |
| 210 | + """ | |
| 211 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 212 | + params = self.sell_params | |
| 213 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 214 | + conditions = [] | |
| 215 | + | |
| 216 | + # In this strategy all sells for profit happen according to ROI | |
| 217 | + # This sell signal is designed only as a "dynamic stoploss" | |
| 218 | + | |
| 219 | + # if we are in an active trade for this pair | |
| 220 | + if trade_data['active_trade']: | |
| 221 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 222 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 223 | + | |
| 224 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 225 | + conditions.append( | |
| 226 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 227 | + (trade_data['current_profit'] > self.stoploss) & | |
| 228 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 229 | + (dataframe['volume'].gt(0)) | |
| 230 | + ) | |
| 231 | + # if the peak profit was positive at some point but never reached ROI, set a higher cross point for exit | |
| 232 | + if trade_data['peak_profit'] > 0: | |
| 233 | + conditions.append(dataframe['rmi-slow'] < 50) | |
| 234 | + # if the trade was always negative, the bounce we expected didn't happen | |
| 235 | + else: | |
| 236 | + conditions.append(dataframe['rmi-slow'] < 10) | |
| 237 | + | |
| 238 | + # if there are other open trades in addition to this one, consider the average profit | |
| 239 | + # across them all and how many free slots we have in our sell decision | |
| 240 | + if trade_data['other_trades']: | |
| 241 | + if trade_data['free_slots'] > 0: | |
| 242 | + # more free slots, the higher this threshold gets | |
| 243 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 244 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 245 | + else: | |
| 246 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 247 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 248 | + | |
| 249 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 250 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 251 | + # clogging up the charts and not having one leads the bot to crash | |
| 252 | + else: | |
| 253 | + conditions.append(dataframe['volume'].lt(0)) | |
| 254 | + | |
| 255 | + if conditions: | |
| 256 | + dataframe.loc[ | |
| 257 | + reduce(lambda x, y: x & y, conditions), | |
| 258 | + 'sell'] = 1 | |
| 259 | + | |
| 260 | + return dataframe | |
| 261 | + | |
| 262 | + """ | |
| 263 | + Super Legit Custom Methods | |
| 264 | + """ | |
| 265 | + # Populate trades_data from the database | |
| 266 | + def populate_trades(self, pair: str) -> dict: | |
| 267 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 268 | + if not pair in self.custom_trade_info: | |
| 269 | + self.custom_trade_info[pair] = {} | |
| 270 | + | |
| 271 | + # init the temp dicts and set the trade stuff to false | |
| 272 | + trade_data = {} | |
| 273 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 274 | + self.custom_trade_info['meta'] = {} | |
| 275 | + | |
| 276 | + # active trade stuff only works in live and dry, not backtest | |
| 277 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 278 | + | |
| 279 | + # find out if we have an open trade for this pair | |
| 280 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 281 | + | |
| 282 | + # if so, get some information | |
| 283 | + if active_trade: | |
| 284 | + # get current price and update the min/max rate | |
| 285 | + current_rate = self.get_current_price(pair, True) | |
| 286 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 287 | + | |
| 288 | + # get how long the trade has been open in minutes and candles | |
| 289 | + present = arrow.utcnow() | |
| 290 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 291 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 292 | + | |
| 293 | + # set up the things we use in the strategy | |
| 294 | + trade_data['active_trade'] = True | |
| 295 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 296 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 297 | + trade_data['open_minutes'] : int = open_minutes | |
| 298 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 299 | + else: | |
| 300 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 301 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 302 | + | |
| 303 | + # if there are open trades not including the current pair, get some information | |
| 304 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 305 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 306 | + | |
| 307 | + if other_trades: | |
| 308 | + trade_data['other_trades'] = True | |
| 309 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 310 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 311 | + # find which of our trades is the biggest loser | |
| 312 | + if trade_data['current_profit'] < min(other_profit): | |
| 313 | + trade_data['biggest_loser'] = True | |
| 314 | + else: | |
| 315 | + trade_data['avg_other_profit'] = 0 | |
| 316 | + | |
| 317 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 318 | + open_trades = len(Trade.get_open_trades()) | |
| 319 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 320 | + | |
| 321 | + return trade_data | |
| 322 | + | |
| 323 | + # Get the current price from the exchange (or cache) | |
| 324 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 325 | + if not refresh: | |
| 326 | + rate = self.custom_current_price_cache.get(pair) | |
| 327 | + # Check if cache has been invalidated | |
| 328 | + if rate: | |
| 329 | + return rate | |
| 330 | + | |
| 331 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 332 | + if ask_strategy.get('use_order_book', False): | |
| 333 | + ob = self.dp.orderbook(pair, 1) | |
| 334 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 335 | + else: | |
| 336 | + ticker = self.dp.ticker(pair) | |
| 337 | + rate = ticker['last'] | |
| 338 | + | |
| 339 | + self.custom_current_price_cache[pair] = rate | |
| 340 | + return rate | |
| 341 | + | |
| 342 | + # linear growth, starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 343 | + # f(t) = X + (rate * t), where rate = (Y - X) / (A - B) | |
| 344 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 345 | + time = max(0, trade_time - start_time) | |
| 346 | + rate = (end - start) / (end_time - start_time) | |
| 347 | + return min(end, start + (rate * trade_time)) | |
| 348 | + | |
| 349 | + """ | |
| 350 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 351 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 352 | + """ | |
| 353 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 354 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 355 | + ob = self.dp.orderbook(pair, 1) | |
| 356 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 357 | + # Cancel buy order if price is more than 1% above the order. | |
| 358 | + if current_price > order['price'] * 1.01: | |
| 359 | + return True | |
| 360 | + return False | |
| 361 | + | |
| 362 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 363 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 364 | + ob = self.dp.orderbook(pair, 1) | |
| 365 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 366 | + # Cancel sell order if price is more than 1% below the order. | |
| 367 | + if current_price < order['price'] * 0.99: | |
| 368 | + return True | |
| 369 | + return False | |
| 370 | + | |
| 371 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 372 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 373 | + ob = self.dp.orderbook(pair, 1) | |
| 374 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 375 | + # Cancel buy order if price is more than 1% above the order. | |
| 376 | + if current_price > rate * 1.01: | |
| 377 | + return False | |
| 378 | + return True | |
| 379 | + | |
| 380 | + """ | |
| 381 | + Override for default Freqtrade ROI table functionality | |
| 382 | + """ | |
| 383 | + def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 384 | + dynamic_roi = self.dynamic_roi | |
| 385 | + minimal_roi = self.minimal_roi | |
| 386 | + | |
| 387 | + # if the dynamic_roi dict is defined and enabled, use it, otherwise fallback to default functionality | |
| 388 | + if dynamic_roi and dynamic_roi['dynamic_roi_enabled']: | |
| 389 | + # linear decay: f(t) = start - (rate * t) | |
| 390 | + if dynamic_roi['dynamic_roi_type'] == 'linear': | |
| 391 | + start, end = dynamic_roi['dynamic_roi_start'], dynamic_roi['dynamic_roi_end'] | |
| 392 | + rate = (start - end) / dynamic_roi['dynamic_roi_time'] | |
| 393 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 394 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 395 | + elif dynamic_roi['dynamic_roi_type'] == 'exponential': | |
| 396 | + start, end = dynamic_roi['dynamic_roi_start'], dynamic_roi['dynamic_roi_end'] | |
| 397 | + min_roi = max(end, start * np.exp(-dynamic_roi['dynamic_roi_rate']*trade_dur)) | |
| 398 | + elif dynamic_roi['dynamic_roi_type'] == 'connect': | |
| 399 | + # connect the points in the defined table with lines | |
| 400 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 401 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 402 | + if not past_roi: | |
| 403 | + return None, None | |
| 404 | + current_entry = max(past_roi) | |
| 405 | + if not next_roi: | |
| 406 | + return current_entry, minimal_roi[current_entry] | |
| 407 | + # use the slope-intercept formula between the two points in the roi table we are between | |
| 408 | + else: | |
| 409 | + next_entry = min(next_roi) | |
| 410 | + # y = mx + b | |
| 411 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 412 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 413 | + m = (y1-y2)/(x1-x2) | |
| 414 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 415 | + min_roi = (m * trade_dur) + b | |
| 416 | + else: | |
| 417 | + min_roi = 0 | |
| 418 | + | |
| 419 | + return trade_dur, min_roi | |
| 420 | + # Default ROI table functionality | |
| 421 | + else: | |
| 422 | + # Get highest entry in ROI dict where key <= trade-duration | |
| 423 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 424 | + if not roi_list: | |
| 425 | + return None, None | |
| 426 | + roi_entry = max(roi_list) | |
| 427 | + return roi_entry, minimal_roi[roi_entry] | |
| 428 | + | |
| 429 | +""" | |
| 430 | +Sub-strategy overrides | |
| 431 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 432 | +""" | |
| 433 | +# Sub-strategy with parameters specific to BTC stake | |
| 434 | +class Schism_BTC(Schism): | |
| 435 | + | |
| 436 | + timeframe = '5m' | |
| 437 | + inf_timeframe = '1h' | |
| 438 | + | |
| 439 | + buy_params = { | |
| 440 | + 'inf-pct-adr': 0.91556, | |
| 441 | + 'inf-rsi': 14, | |
| 442 | + 'inf-stake-rmi': 51, | |
| 443 | + 'mp': 66, | |
| 444 | + 'rmi-fast': 34, | |
| 445 | + 'rmi-slow': 19, | |
| 446 | + 'tf-fiat-rsi': 38, | |
| 447 | + 'tf-stake-rsi': 60 | |
| 448 | + } | |
| 449 | + | |
| 450 | + use_sell_signal = False | |
| 451 | + | |
| 452 | +# Sub-strategy with parameters specific to ETH stake | |
| 453 | +class Schism_ETH(Schism): | |
| 454 | + | |
| 455 | + timeframe = '5m' | |
| 456 | + inf_timeframe = '1h' | |
| 457 | + | |
| 458 | + buy_params = { | |
| 459 | + 'inf-pct-adr': 0.81628, | |
| 460 | + 'inf-rsi': 13, | |
| 461 | + 'inf-stake-rmi': 69, | |
| 462 | + 'mp': 40, | |
| 463 | + 'rmi-fast': 42, | |
| 464 | + 'rmi-slow': 17, | |
| 465 | + 'tf-fiat-rsi': 15, | |
| 466 | + 'tf-stake-rsi': 92 | |
| 467 | + } | |
| 468 | + | |
| 469 | + trailing_stop = True | |
| 470 | + trailing_stop_positive = 0.014 | |
| 471 | + trailing_stop_positive_offset = 0.022 | |
| 472 | + trailing_only_offset_is_reached = False | |
| 473 | + | |
| 474 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Schism-Badstreak.py +471 −0
| @@ -0,0 +1,471 @@ | ||
| 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 | |
| 8 | +from freqtrade.persistence import Trade | |
| 9 | +from technical.indicators import RMI | |
| 10 | +from technical.util import resample_to_interval, resampled_merge | |
| 11 | + | |
| 12 | +from typing import Dict, List, Optional, Tuple | |
| 13 | +from pandas import DataFrame, Series | |
| 14 | +from functools import reduce | |
| 15 | +from datetime import datetime | |
| 16 | +from statistics import mean | |
| 17 | +from cachetools import TTLCache | |
| 18 | +from collections import namedtuple | |
| 19 | + | |
| 20 | +""" | |
| 21 | +TODO: | |
| 22 | + - Continue to hunt for a better all around buy signal. | |
| 23 | + - Existing signal to "buy the dip" seems to work well but would it be nice to have an additional | |
| 24 | + buy signal for strong upward trends without dips? | |
| 25 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 26 | + - Initial 24h range thing seems to be step 1 of this process, anything else we can do? | |
| 27 | + - Fibonacci Retracement for resistance/support levels? | |
| 28 | + - Tweak ROI Ride | |
| 29 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 30 | + - Tweak sell signal | |
| 31 | + - Continue to evaluate good circumstances to sell vs hold | |
| 32 | + | |
| 33 | +Loosely based on: | |
| 34 | +https://github.com/nicolay-zlobin/jesse-indicators/blob/main/strategies/BadStreak/__init__.py | |
| 35 | +""" | |
| 36 | + | |
| 37 | +class Schism(IStrategy): | |
| 38 | + """ | |
| 39 | + Strategy Configuration Items | |
| 40 | + """ | |
| 41 | + timeframe = '5m' | |
| 42 | + | |
| 43 | + buy_params = { | |
| 44 | + 'mp': 65 | |
| 45 | + } | |
| 46 | + | |
| 47 | + sell_params = {} | |
| 48 | + | |
| 49 | + minimal_roi = { | |
| 50 | + "0": 0.02, | |
| 51 | + "60": 0.01, | |
| 52 | + "1440": 0 | |
| 53 | + } | |
| 54 | + | |
| 55 | + use_custom_stoploss = True | |
| 56 | + stoploss = -0.20 | |
| 57 | + | |
| 58 | + use_sell_signal = False | |
| 59 | + sell_profit_only = False | |
| 60 | + ignore_roi_if_buy_signal = True | |
| 61 | + | |
| 62 | + startup_candle_count: int = 72 | |
| 63 | + | |
| 64 | + # Custom Variables | |
| 65 | + custom_trade_info = {} | |
| 66 | + custom_fiat = "USD" | |
| 67 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 68 | + | |
| 69 | + # at what % profit to start trailing | |
| 70 | + custom_stoploss_trail_start = 0.01 | |
| 71 | + # how far behind it should trail (positive here means 1% below) | |
| 72 | + custom_stoploss_trail_dist = 0.01 | |
| 73 | + | |
| 74 | + """ | |
| 75 | + Indicator Definitions | |
| 76 | + """ | |
| 77 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 78 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 79 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 80 | + | |
| 81 | + # Momentum Pinball | |
| 82 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=1) | |
| 83 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=3) | |
| 84 | + | |
| 85 | + # MA Streak | |
| 86 | + dataframe['mac'] = cta.macross(dataframe, 21, 55) | |
| 87 | + dataframe['streak'] = cta.mastreak(dataframe, period=4) | |
| 88 | + | |
| 89 | + lookup_idxs = dataframe.index.values - (abs(dataframe['streak'].values) + 1) | |
| 90 | + valid_lookups = lookup_idxs >= 0 | |
| 91 | + dataframe['sbc'] = np.nan | |
| 92 | + dataframe.loc[valid_lookups, 'sbc'] = dataframe['close'].to_numpy()[lookup_idxs[valid_lookups].astype(int)] | |
| 93 | + | |
| 94 | + dataframe['streak-roc'] = 100 * (dataframe['close'] - dataframe['sbc']) / dataframe['sbc'] | |
| 95 | + | |
| 96 | + # Percent Change Channel | |
| 97 | + upper, mid, lower = cta.pcc(dataframe, period=20, mult=2) | |
| 98 | + dataframe['pcc-lowerband'] = lower | |
| 99 | + dataframe['pcc-upperband'] = upper | |
| 100 | + | |
| 101 | + # RMI Trend Strength | |
| 102 | + dataframe['rmi'] = RMI(dataframe, length=21, mom=5) | |
| 103 | + | |
| 104 | + # RMI Trend Calculations | |
| 105 | + dataframe['rmi-up'] = np.where(dataframe['rmi'] >= dataframe['rmi'].shift(),1,0) | |
| 106 | + dataframe['rmi-dn'] = np.where(dataframe['rmi'] <= dataframe['rmi'].shift(),1,0) | |
| 107 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 108 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 109 | + | |
| 110 | + return dataframe | |
| 111 | + | |
| 112 | + """ | |
| 113 | + Buy Trigger Signals | |
| 114 | + """ | |
| 115 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + params = self.buy_params | |
| 117 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 118 | + conditions = [] | |
| 119 | + | |
| 120 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 121 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 122 | + if trade_data['active_trade']: | |
| 123 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 124 | + profit_factor = (1 - (dataframe['rmi'].iloc[-1] / 400)) | |
| 125 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 126 | + rmi_grow = linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 127 | + | |
| 128 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 129 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 130 | + conditions.append(dataframe['rmi'] >= rmi_grow) | |
| 131 | + | |
| 132 | + # Normal buy triggers that apply to new trades we want to enter | |
| 133 | + else: | |
| 134 | + # Primary buy triggers | |
| 135 | + conditions.append( | |
| 136 | + (dataframe['mp'] < params['mp']) & | |
| 137 | + (dataframe['streak-roc'] > dataframe['pcc-lowerband']) & | |
| 138 | + (dataframe['mac'] == 1) | |
| 139 | + ) | |
| 140 | + | |
| 141 | + # Anything below here applies to persisting and new buy signal | |
| 142 | + conditions.append(dataframe['volume'].gt(0)) | |
| 143 | + | |
| 144 | + if conditions: | |
| 145 | + dataframe.loc[ | |
| 146 | + reduce(lambda x, y: x & y, conditions), | |
| 147 | + 'buy'] = 1 | |
| 148 | + | |
| 149 | + return dataframe | |
| 150 | + | |
| 151 | + """ | |
| 152 | + Sell Trigger Signals | |
| 153 | + """ | |
| 154 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 155 | + params = self.sell_params | |
| 156 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 157 | + conditions = [] | |
| 158 | + | |
| 159 | + # In this strategy all sells for profit happen according to ROI | |
| 160 | + # This sell signal is designed only as a "dynamic stoploss" | |
| 161 | + | |
| 162 | + # if we are in an active trade for this pair | |
| 163 | + if trade_data['active_trade']: | |
| 164 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 165 | + loss_cutoff = linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 166 | + | |
| 167 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 168 | + conditions.append( | |
| 169 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 170 | + (trade_data['current_profit'] > self.stoploss) & | |
| 171 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 172 | + (dataframe['volume'].gt(0)) | |
| 173 | + ) | |
| 174 | + # if the peak profit was positive at some point but never reached ROI, set a higher cross point for exit | |
| 175 | + if trade_data['peak_profit'] > 0: | |
| 176 | + conditions.append(qtpylib.crossed_below(dataframe['rmi'], 50)) | |
| 177 | + # if the trade was always negative, the bounce we expected didn't happen | |
| 178 | + else: | |
| 179 | + conditions.append(qtpylib.crossed_below(dataframe['rmi'], 10)) | |
| 180 | + | |
| 181 | + # if there are other open trades in addition to this one, consider the average profit | |
| 182 | + # across them all and how many free slots we have in our sell decision | |
| 183 | + if trade_data['other_trades']: | |
| 184 | + if trade_data['free_slots'] > 0: | |
| 185 | + # more free slots, the higher this threshold gets | |
| 186 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 187 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 188 | + else: | |
| 189 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 190 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 191 | + | |
| 192 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 193 | + # so we pass an impossible condiiton here | |
| 194 | + else: | |
| 195 | + conditions.append(dataframe['volume'].lt(0)) | |
| 196 | + | |
| 197 | + if conditions: | |
| 198 | + dataframe.loc[ | |
| 199 | + reduce(lambda x, y: x & y, conditions), | |
| 200 | + 'sell'] = 1 | |
| 201 | + | |
| 202 | + return dataframe | |
| 203 | + | |
| 204 | + """ | |
| 205 | + Custom Methods for Live Trade Data and Realtime Price | |
| 206 | + """ | |
| 207 | + # Populate trades_data from the database | |
| 208 | + def populate_trades(self, pair: str) -> dict: | |
| 209 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 210 | + if not pair in self.custom_trade_info: | |
| 211 | + self.custom_trade_info[pair] = {} | |
| 212 | + | |
| 213 | + # init the temp dicts and set the trade stuff to false | |
| 214 | + trade_data = {} | |
| 215 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 216 | + self.custom_trade_info['meta'] = {} | |
| 217 | + | |
| 218 | + # active trade stuff only works in live and dry, not backtest | |
| 219 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 220 | + | |
| 221 | + # find out if we have an open trade for this pair | |
| 222 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 223 | + | |
| 224 | + # if so, get some information | |
| 225 | + if active_trade: | |
| 226 | + # get current price and update the min/max rate | |
| 227 | + current_rate = self.get_current_price(pair, True) | |
| 228 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 229 | + | |
| 230 | + # get how long the trade has been open in minutes and candles | |
| 231 | + present = arrow.utcnow() | |
| 232 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 233 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 234 | + | |
| 235 | + # set up the things we use in the strategy | |
| 236 | + trade_data['active_trade'] = True | |
| 237 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 238 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 239 | + trade_data['open_minutes'] : int = open_minutes | |
| 240 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 241 | + else: | |
| 242 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 243 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 244 | + | |
| 245 | + # if there are open trades not including the current pair, get some information | |
| 246 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 247 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 248 | + | |
| 249 | + if other_trades: | |
| 250 | + trade_data['other_trades'] = True | |
| 251 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 252 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 253 | + # find which of our trades is the biggest loser | |
| 254 | + if trade_data['current_profit'] < min(other_profit): | |
| 255 | + trade_data['biggest_loser'] = True | |
| 256 | + else: | |
| 257 | + trade_data['avg_other_profit'] = 0 | |
| 258 | + | |
| 259 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 260 | + open_trades = len(Trade.get_open_trades()) | |
| 261 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 262 | + | |
| 263 | + return trade_data | |
| 264 | + | |
| 265 | + # Get the current price from the exchange (or cache) | |
| 266 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 267 | + if not refresh: | |
| 268 | + rate = self.custom_current_price_cache.get(pair) | |
| 269 | + # Check if cache has been invalidated | |
| 270 | + if rate: | |
| 271 | + return rate | |
| 272 | + | |
| 273 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 274 | + if ask_strategy.get('use_order_book', False): | |
| 275 | + ob = self.dp.orderbook(pair, 1) | |
| 276 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 277 | + else: | |
| 278 | + ticker = self.dp.ticker(pair) | |
| 279 | + rate = ticker['last'] | |
| 280 | + | |
| 281 | + self.custom_current_price_cache[pair] = rate | |
| 282 | + return rate | |
| 283 | + | |
| 284 | + """ | |
| 285 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 286 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 287 | + """ | |
| 288 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 289 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 290 | + ob = self.dp.orderbook(pair, 1) | |
| 291 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 292 | + # Cancel buy order if price is more than 1% above the order. | |
| 293 | + if current_price > order['price'] * 1.01: | |
| 294 | + return True | |
| 295 | + return False | |
| 296 | + | |
| 297 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 298 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 299 | + ob = self.dp.orderbook(pair, 1) | |
| 300 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 301 | + # Cancel sell order if price is more than 1% below the order. | |
| 302 | + if current_price < order['price'] * 0.99: | |
| 303 | + return True | |
| 304 | + return False | |
| 305 | + | |
| 306 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 307 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 308 | + ob = self.dp.orderbook(pair, 1) | |
| 309 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 310 | + # Cancel buy order if price is more than 1% above the order. | |
| 311 | + if current_price > rate * 1.01: | |
| 312 | + return False | |
| 313 | + return True | |
| 314 | + | |
| 315 | + """ | |
| 316 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 317 | + https://www.freqtrade.io/en/latest/strategy-advanced/#custom-stoploss | |
| 318 | + """ | |
| 319 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 320 | + | |
| 321 | + if current_profit < self.custom_stoploss_trail_start: | |
| 322 | + return -1 # return a value bigger than the inital stoploss to keep using the inital stoploss | |
| 323 | + | |
| 324 | + # After reaching the desired offset, allow the stoploss to trail the defined value | |
| 325 | + desired_stoploss = current_profit - (current_profit * self.custom_stoploss_trail_dist) | |
| 326 | + | |
| 327 | + # Use a minimum of 0.5% | |
| 328 | + return max(desired_stoploss, 0.005) | |
| 329 | + | |
| 330 | +""" | |
| 331 | +Sub-strategy overrides | |
| 332 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 333 | +""" | |
| 334 | +# Sub-strategy with parameters specific to BTC stake | |
| 335 | +class Schism_BTC(Schism): | |
| 336 | + | |
| 337 | + timeframe = '5m' | |
| 338 | + inf_timeframe = '1h' | |
| 339 | + | |
| 340 | + buy_params = { | |
| 341 | + 'mp': 66, | |
| 342 | + 'tf-fiat-rsi': 38, | |
| 343 | + 'tf-stake-rsi': 60, | |
| 344 | + 'inf-rsi': 14, | |
| 345 | + 'inf-stake-rmi': 51 | |
| 346 | + } | |
| 347 | + | |
| 348 | + use_sell_signal = False | |
| 349 | + | |
| 350 | +# Sub-strategy with parameters specific to ETH stake | |
| 351 | +class Schism_ETH(Schism): | |
| 352 | + | |
| 353 | + timeframe = '5m' | |
| 354 | + inf_timeframe = '1h' | |
| 355 | + | |
| 356 | + buy_params = { | |
| 357 | + 'mp': 40, | |
| 358 | + 'tf-fiat-rsi': 15, | |
| 359 | + 'tf-stake-rsi': 92, | |
| 360 | + 'inf-rsi': 13, | |
| 361 | + 'inf-stake-rmi': 69, | |
| 362 | + } | |
| 363 | + | |
| 364 | + trailing_stop = True | |
| 365 | + trailing_stop_positive = 0.014 | |
| 366 | + trailing_stop_positive_offset = 0.022 | |
| 367 | + trailing_only_offset_is_reached = False | |
| 368 | + | |
| 369 | + use_sell_signal = False | |
| 370 | + | |
| 371 | + | |
| 372 | +""" | |
| 373 | +Custom Indicators | |
| 374 | +""" | |
| 375 | + | |
| 376 | +""" | |
| 377 | +linear growth, starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 378 | +f(t) = X + (rate * t), where rate = (Y - X) / (A - B) | |
| 379 | +""" | |
| 380 | +def linear_growth(start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 381 | + time = max(0, trade_time - start_time) | |
| 382 | + rate = (end - start) / (end_time - start_time) | |
| 383 | + return min(end, start + (rate * trade_time)) | |
| 384 | + | |
| 385 | +""" | |
| 386 | +Moving Average Cross | |
| 387 | +Port of: https://www.tradingview.com/script/PcWAuplI-Moving-Average-Cross/ | |
| 388 | +""" | |
| 389 | +def ci_mac(dataframe: DataFrame, fast: int = 20, slow: int = 50) -> Series: | |
| 390 | + | |
| 391 | + dataframe = dataframe.copy() | |
| 392 | + | |
| 393 | + # Fast MAs | |
| 394 | + upper_fast = ta.EMA(dataframe['high'], timeperiod=fast) | |
| 395 | + lower_fast = ta.EMA(dataframe['low'], timeperiod=fast) | |
| 396 | + | |
| 397 | + # Slow MAs | |
| 398 | + upper_slow = ta.EMA(dataframe['high'], timeperiod=slow) | |
| 399 | + lower_slow = ta.EMA(dataframe['low'], timeperiod=slow) | |
| 400 | + | |
| 401 | + # Crosses | |
| 402 | + crosses_lf_us = qtpylib.crossed_above(lower_fast, upper_slow) | qtpylib.crossed_below(lower_fast, upper_slow) | |
| 403 | + crosses_uf_ls = qtpylib.crossed_above(upper_fast, lower_slow) | qtpylib.crossed_below(upper_fast, lower_slow) | |
| 404 | + | |
| 405 | + dir_1 = np.where(crosses_lf_us, 1, np.nan) | |
| 406 | + dir_2 = np.where(crosses_uf_ls, -1, np.nan) | |
| 407 | + | |
| 408 | + dir = np.where(dir_1 == 1, dir_1, np.nan) | |
| 409 | + dir = np.where(dir_2 == -1, dir_2, dir_1) | |
| 410 | + | |
| 411 | + res = Series(dir).fillna(method='ffill').to_numpy() | |
| 412 | + | |
| 413 | + return res | |
| 414 | + | |
| 415 | +""" | |
| 416 | +MA Streak | |
| 417 | +Port of: https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/ | |
| 418 | +""" | |
| 419 | +def ci_mastreak(dataframe: DataFrame, period: int = 4, source_type='close') -> Series: | |
| 420 | + | |
| 421 | + dataframe = dataframe.copy() | |
| 422 | + | |
| 423 | + avgval = zlema(dataframe[source_type], period) | |
| 424 | + | |
| 425 | + arr = np.diff(avgval) | |
| 426 | + pos = np.clip(arr, 0, 1).astype(bool).cumsum() | |
| 427 | + neg = np.clip(arr, -1, 0).astype(bool).cumsum() | |
| 428 | + streak = np.where(arr >= 0, pos - np.maximum.accumulate(np.where(arr <= 0, pos, 0)), | |
| 429 | + -neg + np.maximum.accumulate(np.where(arr >= 0, neg, 0))) | |
| 430 | + | |
| 431 | + res = np.concatenate((np.full((dataframe.shape[0] - streak.shape[0]), np.nan), streak)) | |
| 432 | + | |
| 433 | + return res | |
| 434 | + | |
| 435 | +""" | |
| 436 | +Percent Change Channel | |
| 437 | +PCC is like KC unless it uses percentage changes in price to set channel distance. | |
| 438 | +https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/ | |
| 439 | +""" | |
| 440 | +def ci_pcc(dataframe: DataFrame, period: int = 20, mult: int = 2): | |
| 441 | + | |
| 442 | + PercentChangeChannel = namedtuple('PercentChangeChannel', ['upperband', 'middleband', 'lowerband']) | |
| 443 | + | |
| 444 | + dataframe = dataframe.copy() | |
| 445 | + | |
| 446 | + close = dataframe['close'] | |
| 447 | + previous_close = close.shift() | |
| 448 | + low = dataframe['low'] | |
| 449 | + high = dataframe['high'] | |
| 450 | + | |
| 451 | + close_change = (close - previous_close) / previous_close * 100 | |
| 452 | + high_change = (high - close) / close * 100 | |
| 453 | + low_change = (low - close) / close * 100 | |
| 454 | + | |
| 455 | + mid = zlema(close_change, period) | |
| 456 | + rangema = zlema(high_change - low_change, period) | |
| 457 | + | |
| 458 | + upper = mid + rangema * mult | |
| 459 | + lower = mid - rangema * mult | |
| 460 | + | |
| 461 | + return PercentChangeChannel(upper, rangema, lower) | |
| 462 | + | |
| 463 | +""" | |
| 464 | +Zero Lag EMA | |
| 465 | +""" | |
| 466 | +def zlema(series: Series, period): | |
| 467 | + ema1 = ta.EMA(series, period) | |
| 468 | + ema2 = ta.EMA(ema1, period) | |
| 469 | + d = ema1 - ema2 | |
| 470 | + zlema = ema1 + d | |
| 471 | + return zlema | |
| No newline at the end of the file |
added strategies/old/Schism-Badstreak2.py +525 −0
| @@ -0,0 +1,525 @@ | ||
| 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 | |
| 8 | +from freqtrade.persistence import Trade | |
| 9 | +from technical.indicators import RMI | |
| 10 | +from technical.util import resample_to_interval, resampled_merge | |
| 11 | + | |
| 12 | +from typing import Dict, List, Optional, Tuple | |
| 13 | +from pandas import DataFrame, Series | |
| 14 | +from functools import reduce | |
| 15 | +from datetime import datetime | |
| 16 | +from statistics import mean | |
| 17 | +from cachetools import TTLCache | |
| 18 | +from collections import namedtuple | |
| 19 | + | |
| 20 | +""" | |
| 21 | +Loosely based on: | |
| 22 | +https://github.com/nicolay-zlobin/jesse-indicators/blob/main/strategies/BadStreak/__init__.py | |
| 23 | +""" | |
| 24 | + | |
| 25 | +class Schism(IStrategy): | |
| 26 | + """ | |
| 27 | + Strategy Configuration Items | |
| 28 | + """ | |
| 29 | + timeframe = '15m' | |
| 30 | + inf_timeframe = '4h' | |
| 31 | + | |
| 32 | + buy_params = { | |
| 33 | + 'inf-rsi-1': 51, | |
| 34 | + 'inf-rsi-2': 52, | |
| 35 | + 'mp': 42, | |
| 36 | + 'rmi-above': 17, | |
| 37 | + 'rmi-below': 60, | |
| 38 | + 'xinf-stake-rmi': 59, | |
| 39 | + 'xtf-fiat-rsi': 48, | |
| 40 | + 'xtf-stake-rsi': 66 | |
| 41 | + } | |
| 42 | + | |
| 43 | + sell_params = {} | |
| 44 | + | |
| 45 | + minimal_roi = { | |
| 46 | + "0": 0.05, | |
| 47 | + "60": 0.025, | |
| 48 | + "180": 0.01, | |
| 49 | + "1440": 0 | |
| 50 | + } | |
| 51 | + | |
| 52 | + stoploss = -0.30 | |
| 53 | + | |
| 54 | + use_sell_signal = False | |
| 55 | + sell_profit_only = False | |
| 56 | + ignore_roi_if_buy_signal = True | |
| 57 | + | |
| 58 | + startup_candle_count: int = 72 | |
| 59 | + | |
| 60 | + # Custom Variables | |
| 61 | + custom_trade_info = {} | |
| 62 | + custom_fiat = "USD" | |
| 63 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 64 | + | |
| 65 | + """ | |
| 66 | + Informative Pair Definitions | |
| 67 | + """ | |
| 68 | + def informative_pairs(self): | |
| 69 | + # add existing pairs from whitelist on the inf_timeframe | |
| 70 | + pairs = self.dp.current_whitelist() | |
| 71 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 72 | + | |
| 73 | + # add additional informative pairs based on certain stakes | |
| 74 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 75 | + for pair in pairs: | |
| 76 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) on base timeframe | |
| 77 | + coin, stake = pair.split('/') | |
| 78 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 79 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 80 | + | |
| 81 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) on base and inf timeframes | |
| 82 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 83 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 84 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 85 | + | |
| 86 | + return informative_pairs | |
| 87 | + | |
| 88 | + """ | |
| 89 | + Indicator Definitions | |
| 90 | + """ | |
| 91 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 92 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 93 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 94 | + | |
| 95 | + # Momentum Pinball | |
| 96 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=1) | |
| 97 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=3) | |
| 98 | + | |
| 99 | + # MA Streak | |
| 100 | + dataframe['mac'] = ci_mac(dataframe, 20, 50) | |
| 101 | + dataframe['streak'] = ci_mastreak(dataframe, period=4) | |
| 102 | + | |
| 103 | + streak = abs(int(dataframe['streak'].iloc[-1])) | |
| 104 | + streak_back_close = dataframe['close'].shift(streak + 1) | |
| 105 | + | |
| 106 | + dataframe['streak-roc'] = 100 * (dataframe['close'] - streak_back_close) / streak_back_close | |
| 107 | + | |
| 108 | + # Percent Change Channel | |
| 109 | + pcc = ci_pcc(dataframe, period=20, mult=2) | |
| 110 | + dataframe['pcc-lowerband'] = pcc.lowerband | |
| 111 | + dataframe['pcc-upperband'] = pcc.upperband | |
| 112 | + | |
| 113 | + # RMI Trend Strength | |
| 114 | + dataframe['rmi'] = RMI(dataframe, length=21, mom=5) | |
| 115 | + | |
| 116 | + # RMI Trend Calculations | |
| 117 | + dataframe['rmi-up'] = np.where(dataframe['rmi'] >= dataframe['rmi'].shift(),1,0) | |
| 118 | + dataframe['rmi-dn'] = np.where(dataframe['rmi'] <= dataframe['rmi'].shift(),1,0) | |
| 119 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 120 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 121 | + | |
| 122 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 123 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 124 | + coin, stake = metadata['pair'].split('/') | |
| 125 | + fiat = self.custom_fiat | |
| 126 | + coin_fiat = f"{coin}/{fiat}" | |
| 127 | + stake_fiat = f"{stake}/{fiat}" | |
| 128 | + | |
| 129 | + # COIN/FIAT (e.g. XLM/USD) - timeframe | |
| 130 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 131 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 132 | + | |
| 133 | + # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe | |
| 134 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 135 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 136 | + | |
| 137 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 138 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 139 | + | |
| 140 | + # Informative indicators for current pair on inf_timeframe | |
| 141 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 142 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 143 | + | |
| 144 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 145 | + | |
| 146 | + return dataframe | |
| 147 | + | |
| 148 | + """ | |
| 149 | + Buy Trigger Signals | |
| 150 | + """ | |
| 151 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 152 | + params = self.buy_params | |
| 153 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 154 | + conditions = [] | |
| 155 | + | |
| 156 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 157 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 158 | + if trade_data['active_trade']: | |
| 159 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 160 | + profit_factor = (1 - (dataframe['rmi'].iloc[-1] / 400)) | |
| 161 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 162 | + rmi_grow = linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 163 | + | |
| 164 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 165 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 166 | + conditions.append(dataframe['rmi'] >= rmi_grow) | |
| 167 | + | |
| 168 | + # Normal buy triggers that apply to new trades we want to enter | |
| 169 | + else: | |
| 170 | + # Primary buy triggers | |
| 171 | + conditions.append( | |
| 172 | + ( | |
| 173 | + # core "buy the dip" badstreak | |
| 174 | + (dataframe[f"rsi_{self.inf_timeframe}"] < params['inf-rsi-1']) & | |
| 175 | + (dataframe['mp'] < params['mp']) & | |
| 176 | + (dataframe['streak-roc'] > dataframe['pcc-lowerband']) & | |
| 177 | + (dataframe['mac'] == 1) | |
| 178 | + ) | | |
| 179 | + ( | |
| 180 | + # additional set of conditions to buy in strong upward trends | |
| 181 | + (dataframe[f"rsi_{self.inf_timeframe}"] < params['inf-rsi-2']) & | |
| 182 | + (dataframe['rmi-up-trend'] == 1) & | |
| 183 | + (dataframe['rmi'] < params['rmi-below']) & | |
| 184 | + (dataframe['rmi'] > params['rmi-above']) | |
| 185 | + ) | |
| 186 | + ) | |
| 187 | + | |
| 188 | + # If the stake is BTC or ETH apply additional conditions | |
| 189 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 190 | + # default timeframe conditions | |
| 191 | + conditions.append( | |
| 192 | + (dataframe[f"{self.config['stake_currency']}_rsi"] > params['xtf-stake-rsi']) | | |
| 193 | + (dataframe[f"{self.custom_fiat}_rsi"] < params['xtf-fiat-rsi']) | |
| 194 | + ) | |
| 195 | + # informative timeframe conditions | |
| 196 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 197 | + | |
| 198 | + # Anything below here applies to persisting and new buy signal | |
| 199 | + conditions.append(dataframe['volume'].gt(0)) | |
| 200 | + | |
| 201 | + if conditions: | |
| 202 | + dataframe.loc[ | |
| 203 | + reduce(lambda x, y: x & y, conditions), | |
| 204 | + 'buy'] = 1 | |
| 205 | + | |
| 206 | + return dataframe | |
| 207 | + | |
| 208 | + """ | |
| 209 | + Sell Trigger Signals | |
| 210 | + """ | |
| 211 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 212 | + params = self.sell_params | |
| 213 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 214 | + conditions = [] | |
| 215 | + | |
| 216 | + # In this strategy all sells for profit happen according to ROI | |
| 217 | + # This sell signal is designed only as a "dynamic stoploss" | |
| 218 | + | |
| 219 | + # if we are in an active trade for this pair | |
| 220 | + if trade_data['active_trade']: | |
| 221 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 222 | + loss_cutoff = linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 223 | + | |
| 224 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 225 | + conditions.append( | |
| 226 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 227 | + (trade_data['current_profit'] > self.stoploss) & | |
| 228 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 229 | + (dataframe['volume'].gt(0)) | |
| 230 | + ) | |
| 231 | + # if the peak profit was positive at some point but never reached ROI, set a higher cross point for exit | |
| 232 | + if trade_data['peak_profit'] > 0: | |
| 233 | + conditions.append(qtpylib.crossed_below(dataframe['rmi'], 50)) | |
| 234 | + # if the trade was always negative, the bounce we expected didn't happen | |
| 235 | + else: | |
| 236 | + conditions.append(qtpylib.crossed_below(dataframe['rmi'], 10)) | |
| 237 | + | |
| 238 | + # if there are other open trades in addition to this one, consider the average profit | |
| 239 | + # across them all and how many free slots we have in our sell decision | |
| 240 | + if trade_data['other_trades']: | |
| 241 | + if trade_data['free_slots'] > 0: | |
| 242 | + # more free slots, the higher this threshold gets | |
| 243 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 244 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 245 | + else: | |
| 246 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 247 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 248 | + | |
| 249 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 250 | + # so we pass an impossible condiiton here | |
| 251 | + else: | |
| 252 | + conditions.append(dataframe['volume'].lt(0)) | |
| 253 | + | |
| 254 | + if conditions: | |
| 255 | + dataframe.loc[ | |
| 256 | + reduce(lambda x, y: x & y, conditions), | |
| 257 | + 'sell'] = 1 | |
| 258 | + | |
| 259 | + return dataframe | |
| 260 | + | |
| 261 | + """ | |
| 262 | + Custom Methods for Live Trade Data and Realtime Price | |
| 263 | + """ | |
| 264 | + # Populate trades_data from the database | |
| 265 | + def populate_trades(self, pair: str) -> dict: | |
| 266 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 267 | + if not pair in self.custom_trade_info: | |
| 268 | + self.custom_trade_info[pair] = {} | |
| 269 | + | |
| 270 | + # init the temp dicts and set the trade stuff to false | |
| 271 | + trade_data = {} | |
| 272 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 273 | + self.custom_trade_info['meta'] = {} | |
| 274 | + | |
| 275 | + # active trade stuff only works in live and dry, not backtest | |
| 276 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 277 | + | |
| 278 | + # find out if we have an open trade for this pair | |
| 279 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 280 | + | |
| 281 | + # if so, get some information | |
| 282 | + if active_trade: | |
| 283 | + # get current price and update the min/max rate | |
| 284 | + current_rate = self.get_current_price(pair, True) | |
| 285 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 286 | + | |
| 287 | + # get how long the trade has been open in minutes and candles | |
| 288 | + present = arrow.utcnow() | |
| 289 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 290 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 291 | + | |
| 292 | + # set up the things we use in the strategy | |
| 293 | + trade_data['active_trade'] = True | |
| 294 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 295 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 296 | + trade_data['open_minutes'] : int = open_minutes | |
| 297 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 298 | + else: | |
| 299 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 300 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 301 | + | |
| 302 | + # if there are open trades not including the current pair, get some information | |
| 303 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 304 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 305 | + | |
| 306 | + if other_trades: | |
| 307 | + trade_data['other_trades'] = True | |
| 308 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 309 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 310 | + # find which of our trades is the biggest loser | |
| 311 | + if trade_data['current_profit'] < min(other_profit): | |
| 312 | + trade_data['biggest_loser'] = True | |
| 313 | + else: | |
| 314 | + trade_data['avg_other_profit'] = 0 | |
| 315 | + | |
| 316 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 317 | + open_trades = len(Trade.get_open_trades()) | |
| 318 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 319 | + | |
| 320 | + return trade_data | |
| 321 | + | |
| 322 | + # Get the current price from the exchange (or cache) | |
| 323 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 324 | + if not refresh: | |
| 325 | + rate = self.custom_current_price_cache.get(pair) | |
| 326 | + # Check if cache has been invalidated | |
| 327 | + if rate: | |
| 328 | + return rate | |
| 329 | + | |
| 330 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 331 | + if ask_strategy.get('use_order_book', False): | |
| 332 | + ob = self.dp.orderbook(pair, 1) | |
| 333 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 334 | + else: | |
| 335 | + ticker = self.dp.ticker(pair) | |
| 336 | + rate = ticker['last'] | |
| 337 | + | |
| 338 | + self.custom_current_price_cache[pair] = rate | |
| 339 | + return rate | |
| 340 | + | |
| 341 | + """ | |
| 342 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 343 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 344 | + """ | |
| 345 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 346 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 347 | + ob = self.dp.orderbook(pair, 1) | |
| 348 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 349 | + # Cancel buy order if price is more than 1% above the order. | |
| 350 | + if current_price > order['price'] * 1.01: | |
| 351 | + return True | |
| 352 | + return False | |
| 353 | + | |
| 354 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 355 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 356 | + ob = self.dp.orderbook(pair, 1) | |
| 357 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 358 | + # Cancel sell order if price is more than 1% below the order. | |
| 359 | + if current_price < order['price'] * 0.99: | |
| 360 | + return True | |
| 361 | + return False | |
| 362 | + | |
| 363 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 364 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 365 | + ob = self.dp.orderbook(pair, 1) | |
| 366 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 367 | + # Cancel buy order if price is more than 1% above the order. | |
| 368 | + if current_price > rate * 1.01: | |
| 369 | + return False | |
| 370 | + return True | |
| 371 | + | |
| 372 | +""" | |
| 373 | +Sub-strategy overrides | |
| 374 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 375 | +""" | |
| 376 | +# Sub-strategy with parameters specific to BTC stake | |
| 377 | +class Schism_BTC(Schism): | |
| 378 | + | |
| 379 | + timeframe = '1h' | |
| 380 | + inf_timeframe = '4h' | |
| 381 | + | |
| 382 | + buy_params = { | |
| 383 | + 'inf-rsi': 14, | |
| 384 | + 'inf-stake-rmi': 51, | |
| 385 | + 'mp': 66, | |
| 386 | + 'rmi-fast': 34, | |
| 387 | + 'rmi-slow': 19, | |
| 388 | + 'tf-fiat-rsi': 38, | |
| 389 | + 'tf-stake-rsi': 60 | |
| 390 | + } | |
| 391 | + | |
| 392 | + minimal_roi = { | |
| 393 | + "0": 0.05, | |
| 394 | + "360": 0.025, | |
| 395 | + "1440": 0.01, | |
| 396 | + "4320": 0 | |
| 397 | + } | |
| 398 | + | |
| 399 | + use_sell_signal = False | |
| 400 | + | |
| 401 | +# Sub-strategy with parameters specific to ETH stake | |
| 402 | +class Schism_ETH(Schism): | |
| 403 | + | |
| 404 | + timeframe = '1h' | |
| 405 | + inf_timeframe = '4h' | |
| 406 | + | |
| 407 | + buy_params = { | |
| 408 | + 'inf-rsi': 13, | |
| 409 | + 'inf-stake-rmi': 69, | |
| 410 | + 'mp': 40, | |
| 411 | + 'rmi-fast': 42, | |
| 412 | + 'rmi-slow': 17, | |
| 413 | + 'tf-fiat-rsi': 15, | |
| 414 | + 'tf-stake-rsi': 92 | |
| 415 | + } | |
| 416 | + | |
| 417 | + minimal_roi = { | |
| 418 | + "0": 0.05, | |
| 419 | + "360": 0.025, | |
| 420 | + "1440": 0.01, | |
| 421 | + "4320": 0 | |
| 422 | + } | |
| 423 | + | |
| 424 | + use_sell_signal = False | |
| 425 | + | |
| 426 | +""" | |
| 427 | +Custom Indicators | |
| 428 | +""" | |
| 429 | + | |
| 430 | +""" | |
| 431 | +linear growth, starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 432 | +f(t) = X + (rate * t), where rate = (Y - X) / (A - B) | |
| 433 | +""" | |
| 434 | +def linear_growth(start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 435 | + time = max(0, trade_time - start_time) | |
| 436 | + rate = (end - start) / (end_time - start_time) | |
| 437 | + return min(end, start + (rate * trade_time)) | |
| 438 | + | |
| 439 | +""" | |
| 440 | +Moving Average Cross | |
| 441 | +Port of: https://www.tradingview.com/script/PcWAuplI-Moving-Average-Cross/ | |
| 442 | +""" | |
| 443 | +def ci_mac(dataframe: DataFrame, fast: int = 20, slow: int = 50) -> Series: | |
| 444 | + | |
| 445 | + dataframe = dataframe.copy() | |
| 446 | + | |
| 447 | + # Fast MAs | |
| 448 | + upper_fast = ta.EMA(dataframe['high'], timeperiod=fast) | |
| 449 | + lower_fast = ta.EMA(dataframe['low'], timeperiod=fast) | |
| 450 | + | |
| 451 | + # Slow MAs | |
| 452 | + upper_slow = ta.EMA(dataframe['high'], timeperiod=slow) | |
| 453 | + lower_slow = ta.EMA(dataframe['low'], timeperiod=slow) | |
| 454 | + | |
| 455 | + # Crosses | |
| 456 | + crosses_lf_us = qtpylib.crossed_above(lower_fast, upper_slow) | qtpylib.crossed_below(lower_fast, upper_slow) | |
| 457 | + crosses_uf_ls = qtpylib.crossed_above(upper_fast, lower_slow) | qtpylib.crossed_below(upper_fast, lower_slow) | |
| 458 | + | |
| 459 | + dir_1 = np.where(crosses_lf_us, 1, np.nan) | |
| 460 | + dir_2 = np.where(crosses_uf_ls, -1, np.nan) | |
| 461 | + | |
| 462 | + dir = np.where(dir_1 == 1, dir_1, np.nan) | |
| 463 | + dir = np.where(dir_2 == -1, dir_2, dir_1) | |
| 464 | + | |
| 465 | + res = Series(dir).fillna(method='ffill').to_numpy() | |
| 466 | + | |
| 467 | + return res | |
| 468 | + | |
| 469 | +""" | |
| 470 | +MA Streak | |
| 471 | +Port of: https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/ | |
| 472 | +""" | |
| 473 | +def ci_mastreak(dataframe: DataFrame, period: int = 4, source_type='close') -> Series: | |
| 474 | + | |
| 475 | + dataframe = dataframe.copy() | |
| 476 | + | |
| 477 | + avgval = zlema(dataframe[source_type], period) | |
| 478 | + | |
| 479 | + arr = np.diff(avgval) | |
| 480 | + pos = np.clip(arr, 0, 1).astype(bool).cumsum() | |
| 481 | + neg = np.clip(arr, -1, 0).astype(bool).cumsum() | |
| 482 | + streak = np.where(arr >= 0, pos - np.maximum.accumulate(np.where(arr <= 0, pos, 0)), | |
| 483 | + -neg + np.maximum.accumulate(np.where(arr >= 0, neg, 0))) | |
| 484 | + | |
| 485 | + res = np.concatenate((np.full((dataframe.shape[0] - streak.shape[0]), np.nan), streak)) | |
| 486 | + | |
| 487 | + return res | |
| 488 | + | |
| 489 | +""" | |
| 490 | +Percent Change Channel | |
| 491 | +PCC is like KC unless it uses percentage changes in price to set channel distance. | |
| 492 | +https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/ | |
| 493 | +""" | |
| 494 | +def ci_pcc(dataframe: DataFrame, period: int = 20, mult: int = 2): | |
| 495 | + | |
| 496 | + PercentChangeChannel = namedtuple('PercentChangeChannel', ['upperband', 'middleband', 'lowerband']) | |
| 497 | + | |
| 498 | + dataframe = dataframe.copy() | |
| 499 | + | |
| 500 | + close = dataframe['close'] | |
| 501 | + previous_close = close.shift() | |
| 502 | + low = dataframe['low'] | |
| 503 | + high = dataframe['high'] | |
| 504 | + | |
| 505 | + close_change = (close - previous_close) / previous_close * 100 | |
| 506 | + high_change = (high - close) / close * 100 | |
| 507 | + low_change = (low - close) / close * 100 | |
| 508 | + | |
| 509 | + mid = zlema(close_change, period) | |
| 510 | + rangema = zlema(high_change - low_change, period) | |
| 511 | + | |
| 512 | + upper = mid + rangema * mult | |
| 513 | + lower = mid - rangema * mult | |
| 514 | + | |
| 515 | + return PercentChangeChannel(upper, rangema, lower) | |
| 516 | + | |
| 517 | +""" | |
| 518 | +Zero Lag EMA | |
| 519 | +""" | |
| 520 | +def zlema(series: Series, period): | |
| 521 | + ema1 = ta.EMA(series, period) | |
| 522 | + ema2 = ta.EMA(ema1, period) | |
| 523 | + d = ema1 - ema2 | |
| 524 | + zlema = ema1 + d | |
| 525 | + return zlema | |
| No newline at the end of the file |
added strategies/old/Schism-v1.3.py +468 −0
| @@ -0,0 +1,468 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | +""" | |
| 18 | +TODO: | |
| 19 | + | |
| 20 | +""" | |
| 21 | + | |
| 22 | +class Schism3(IStrategy): | |
| 23 | + """ | |
| 24 | + Strategy Configuration Items | |
| 25 | + """ | |
| 26 | + timeframe = '5m' | |
| 27 | + inf_timeframe = '1h' | |
| 28 | + | |
| 29 | + # Global Buy/Sell Params | |
| 30 | + buy_params = { | |
| 31 | + 'bounce-lookback': 8, | |
| 32 | + 'bounce-price': 'min', | |
| 33 | + 'down-inf-rsi': 37, | |
| 34 | + 'down-mp': 60, | |
| 35 | + 'down-rmi-fast': 28, | |
| 36 | + 'down-rmi-slow': 35, | |
| 37 | + 'up-inf-rsi': 59, | |
| 38 | + 'xinf-stake-rmi': 70, | |
| 39 | + 'xtf-fiat-rsi': 15, | |
| 40 | + 'xtf-stake-rsi': 60 | |
| 41 | + } | |
| 42 | + | |
| 43 | + sell_params = { | |
| 44 | + 'rmi-high': 50, | |
| 45 | + 'rmi-low': 10 | |
| 46 | + } | |
| 47 | + | |
| 48 | + # Pair Specific Buy/Sell Params | |
| 49 | + buy_params_FOO = {} | |
| 50 | + sell_params_FOO = {} | |
| 51 | + | |
| 52 | + | |
| 53 | + minimal_roi = { | |
| 54 | + "0": 0.05, | |
| 55 | + "10": 0.025, | |
| 56 | + "20": 0.015, | |
| 57 | + "30": 0.01, | |
| 58 | + "720": 0.005, | |
| 59 | + "1440": 0 | |
| 60 | + } | |
| 61 | + | |
| 62 | + stoploss = -0.30 | |
| 63 | + | |
| 64 | + use_sell_signal = False | |
| 65 | + sell_profit_only = False | |
| 66 | + ignore_roi_if_buy_signal = True | |
| 67 | + | |
| 68 | + startup_candle_count: int = 72 | |
| 69 | + | |
| 70 | + # Startegy Specific Variable Storage | |
| 71 | + custom_trade_info = {} | |
| 72 | + custom_fiat = "USD" | |
| 73 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 74 | + | |
| 75 | + """ | |
| 76 | + Informative Pair Definitions | |
| 77 | + """ | |
| 78 | + def informative_pairs(self): | |
| 79 | + # add existing pairs from whitelist on the inf_timeframe | |
| 80 | + pairs = self.dp.current_whitelist() | |
| 81 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 82 | + | |
| 83 | + # add additional informative pairs based on certain stakes | |
| 84 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 85 | + for pair in pairs: | |
| 86 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) on base timeframe | |
| 87 | + coin, stake = pair.split('/') | |
| 88 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 89 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 90 | + | |
| 91 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) on base and inf timeframes | |
| 92 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 93 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 94 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 95 | + | |
| 96 | + return informative_pairs | |
| 97 | + | |
| 98 | + | |
| 99 | + """ | |
| 100 | + Indicator Definitions | |
| 101 | + """ | |
| 102 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 103 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 104 | + | |
| 105 | + # Relative Momentum Index | |
| 106 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 107 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 108 | + | |
| 109 | + # Momentum Pinball | |
| 110 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 111 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 112 | + | |
| 113 | + # Trend Calculations | |
| 114 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 115 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 116 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 117 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 118 | + | |
| 119 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 120 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 121 | + coin, stake = metadata['pair'].split('/') | |
| 122 | + fiat = self.custom_fiat | |
| 123 | + coin_fiat = f"{coin}/{fiat}" | |
| 124 | + stake_fiat = f"{stake}/{fiat}" | |
| 125 | + | |
| 126 | + # COIN/FIAT (e.g. XLM/USD) - timeframe | |
| 127 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 128 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 129 | + | |
| 130 | + # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe | |
| 131 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 132 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 133 | + | |
| 134 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 135 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 136 | + | |
| 137 | + # Informative indicators for current pair on inf_timeframe | |
| 138 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 139 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 140 | + | |
| 141 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 142 | + | |
| 143 | + return dataframe | |
| 144 | + | |
| 145 | + """ | |
| 146 | + Buy Trigger Signals | |
| 147 | + """ | |
| 148 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 149 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 150 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 151 | + conditions = [] | |
| 152 | + | |
| 153 | + # Set up a pre-buy condition that we sort of "cache" | |
| 154 | + dataframe['bounce-pending'] = np.where( | |
| 155 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['down-inf-rsi']) & | |
| 156 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 157 | + (dataframe['rmi-slow'] >= params['down-rmi-slow']) & | |
| 158 | + (dataframe['rmi-fast'] <= params['down-rmi-fast']) & | |
| 159 | + (dataframe['mp'] <= params['down-mp']), | |
| 160 | + 1,0 | |
| 161 | + ) | |
| 162 | + | |
| 163 | + # Capture the price where we got the signal that a bounce would happen | |
| 164 | + dataframe['bounce-price'] = np.where( | |
| 165 | + dataframe['bounce-pending'] == 1, | |
| 166 | + dataframe['close'], | |
| 167 | + getattr(dataframe['close'].rolling(params['bounce-lookback'], min_periods=1), params['bounce-price'])() | |
| 168 | + ) | |
| 169 | + | |
| 170 | + # Count how many times our pre-bounce happned in the last "lookback" candles | |
| 171 | + dataframe['bounce-range'] = np.where(dataframe['bounce-pending'].rolling(params['bounce-lookback'], min_periods=1).sum() >= 1,1,0) | |
| 172 | + | |
| 173 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 174 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 175 | + if trade_data['active_trade']: | |
| 176 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 177 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 178 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 179 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 180 | + | |
| 181 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 182 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 183 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 184 | + | |
| 185 | + # Normal buy triggers that apply to new trades we want to enter | |
| 186 | + else: | |
| 187 | + conditions.append( | |
| 188 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['up-inf-rsi']) & | |
| 189 | + (dataframe['bounce-range'] == 1) & | |
| 190 | + (dataframe['rmi-up-trend'] == 1) & | |
| 191 | + (dataframe['close'] >= dataframe['bounce-price']) | |
| 192 | + ) | |
| 193 | + | |
| 194 | + # If the stake is BTC or ETH apply additional conditions | |
| 195 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 196 | + # default timeframe conditions | |
| 197 | + conditions.append( | |
| 198 | + (dataframe[f"{self.config['stake_currency']}_rsi"] < params['xtf-stake-rsi']) | | |
| 199 | + (dataframe[f"{self.custom_fiat}_rsi"] > params['xtf-fiat-rsi']) | |
| 200 | + ) | |
| 201 | + # informative timeframe conditions | |
| 202 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 203 | + | |
| 204 | + # Anything below here applies to persisting and new buy signal | |
| 205 | + conditions.append(dataframe['volume'].gt(0)) | |
| 206 | + | |
| 207 | + if conditions: | |
| 208 | + dataframe.loc[ | |
| 209 | + reduce(lambda x, y: x & y, conditions), | |
| 210 | + 'buy'] = 1 | |
| 211 | + | |
| 212 | + return dataframe | |
| 213 | + | |
| 214 | + """ | |
| 215 | + Sell Trigger Signals: | |
| 216 | + In this strategy all sells for profit happen according to ROI | |
| 217 | + This sell signal is designed only as a "dynamic stoploss" | |
| 218 | + """ | |
| 219 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 220 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 221 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 222 | + conditions = [] | |
| 223 | + | |
| 224 | + # add additional conditions based on time and profit | |
| 225 | + if trade_data['active_trade']: | |
| 226 | + # give some wiggle room for the trade to go negative a little bit before selling | |
| 227 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 228 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 229 | + | |
| 230 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 231 | + conditions.append( | |
| 232 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 233 | + (trade_data['current_profit'] > self.stoploss) & | |
| 234 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 235 | + (dataframe['volume'].gt(0)) | |
| 236 | + ) | |
| 237 | + | |
| 238 | + # if the peak profit was positive at some point but never reached ROI, set a higher cross point for exit | |
| 239 | + if trade_data['peak_profit'] > 0: | |
| 240 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-high'])) | |
| 241 | + # if the trade was always negative, the bounce we expected didn't happen | |
| 242 | + else: | |
| 243 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-low'])) | |
| 244 | + | |
| 245 | + # if we have other trades, consider their profit and the # of free slots in the sell | |
| 246 | + if trade_data['other_trades']: | |
| 247 | + if trade_data['free_slots'] > 0: | |
| 248 | + """ | |
| 249 | + Less free slots, more willing to sell | |
| 250 | + 1 / free_slots * x = | |
| 251 | + 1 slot = 1/1 * -0.04 = -0.04 -> only allow sells if avg_other_proift above -0.04 | |
| 252 | + 4 slot = 1/4 * -0.04 = -0.01 -> only allow sells is avg_other_profit above -0.01 | |
| 253 | + """ | |
| 254 | + max_market_down = -0.04 | |
| 255 | + hold_pct = (1/trade_data['free_slots']) * max_market_down | |
| 256 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 257 | + else: | |
| 258 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 259 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 260 | + | |
| 261 | + # Impossible condition to satisfy the bot when it looks here and theres no active trade | |
| 262 | + else: | |
| 263 | + conditions.append(dataframe['volume'].lt(0)) | |
| 264 | + | |
| 265 | + if conditions: | |
| 266 | + dataframe.loc[ | |
| 267 | + reduce(lambda x, y: x & y, conditions), | |
| 268 | + 'sell'] = 1 | |
| 269 | + | |
| 270 | + return dataframe | |
| 271 | + | |
| 272 | + """ | |
| 273 | + Custom Methods | |
| 274 | + """ | |
| 275 | + # Populate trades_data from the database | |
| 276 | + def populate_trades(self, pair: str) -> dict: | |
| 277 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 278 | + if not pair in self.custom_trade_info: | |
| 279 | + self.custom_trade_info[pair] = {} | |
| 280 | + | |
| 281 | + # init the temp dicts and set the trade stuff to false | |
| 282 | + trade_data = {} | |
| 283 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 284 | + self.custom_trade_info['meta'] = {} | |
| 285 | + | |
| 286 | + # active trade stuff only works in live and dry, not backtest | |
| 287 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 288 | + | |
| 289 | + # find out if we have an open trade for this pair | |
| 290 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 291 | + | |
| 292 | + # if so, get some information | |
| 293 | + if active_trade: | |
| 294 | + # get current price and update the min/max rate | |
| 295 | + current_rate = self.get_current_price(pair, True) | |
| 296 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 297 | + | |
| 298 | + # get how long the trade has been open in minutes and candles | |
| 299 | + present = arrow.utcnow() | |
| 300 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 301 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 302 | + | |
| 303 | + # set up the things we use in the strategy | |
| 304 | + trade_data['active_trade'] = True | |
| 305 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 306 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 307 | + trade_data['open_minutes'] : int = open_minutes | |
| 308 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 309 | + else: | |
| 310 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 311 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 312 | + | |
| 313 | + # if there are open trades not including the current pair, get some information | |
| 314 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 315 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 316 | + | |
| 317 | + if other_trades: | |
| 318 | + trade_data['other_trades'] = True | |
| 319 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 320 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 321 | + # find which of our trades is the biggest loser | |
| 322 | + if trade_data['current_profit'] < min(other_profit): | |
| 323 | + trade_data['biggest_loser'] = True | |
| 324 | + else: | |
| 325 | + trade_data['avg_other_profit'] = 0 | |
| 326 | + | |
| 327 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 328 | + open_trades = len(Trade.get_open_trades()) | |
| 329 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 330 | + | |
| 331 | + return trade_data | |
| 332 | + | |
| 333 | + # Get the current price from the exchange (or cache) | |
| 334 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 335 | + if not refresh: | |
| 336 | + rate = self.custom_current_price_cache.get(pair) | |
| 337 | + # Check if cache has been invalidated | |
| 338 | + if rate: | |
| 339 | + return rate | |
| 340 | + | |
| 341 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 342 | + if ask_strategy.get('use_order_book', False): | |
| 343 | + ob = self.dp.orderbook(pair, 1) | |
| 344 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 345 | + else: | |
| 346 | + ticker = self.dp.ticker(pair) | |
| 347 | + rate = ticker['last'] | |
| 348 | + | |
| 349 | + self.custom_current_price_cache[pair] = rate | |
| 350 | + return rate | |
| 351 | + | |
| 352 | + """ | |
| 353 | + Simple linear growth function: | |
| 354 | + Starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 355 | + f(t) = X + (rate * t), where rate = (Y - X) / (B - A) | |
| 356 | + """ | |
| 357 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 358 | + time = max(0, trade_time - start_time) | |
| 359 | + rate = (end - start) / (end_time - start_time) | |
| 360 | + return min(end, start + (rate * time)) | |
| 361 | + | |
| 362 | + """ | |
| 363 | + Allow for buy/sell override parameters per pair. Testing, might remove. | |
| 364 | + TODO: | |
| 365 | + If good: make this more robust so you never have to edit this method. | |
| 366 | + Consider: per-pair ROI if it seems worthwhile? | |
| 367 | + """ | |
| 368 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 369 | + buy_params = self.buy_params | |
| 370 | + sell_params = self.sell_params | |
| 371 | + | |
| 372 | + ### Stake: USD | |
| 373 | + if pair in ('ABC/XYZ', 'DEF/XYZ'): | |
| 374 | + buy_params = self.buy_params_GROUP1 | |
| 375 | + sell_params = self.sell_params_GROUP1 | |
| 376 | + elif pair in ('QRD/WTF'): | |
| 377 | + buy_params = self.buy_params_QRD | |
| 378 | + sell_params = self.sell_params_QRD | |
| 379 | + | |
| 380 | + if side == 'sell': | |
| 381 | + return sell_params | |
| 382 | + | |
| 383 | + return buy_params | |
| 384 | + | |
| 385 | + """ | |
| 386 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 387 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 388 | + """ | |
| 389 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 390 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 391 | + ob = self.dp.orderbook(pair, 1) | |
| 392 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 393 | + # Cancel buy order if price is more than 1% above the order. | |
| 394 | + if current_price > order['price'] * 1.01: | |
| 395 | + return True | |
| 396 | + return False | |
| 397 | + | |
| 398 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 399 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 400 | + ob = self.dp.orderbook(pair, 1) | |
| 401 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 402 | + # Cancel sell order if price is more than 1% below the order. | |
| 403 | + if current_price < order['price'] * 0.99: | |
| 404 | + return True | |
| 405 | + return False | |
| 406 | + | |
| 407 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 408 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 409 | + ob = self.dp.orderbook(pair, 1) | |
| 410 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 411 | + # Cancel buy order if price is more than 1% above the order. | |
| 412 | + if current_price > rate * 1.01: | |
| 413 | + return False | |
| 414 | + return True | |
| 415 | + | |
| 416 | +""" | |
| 417 | +Sub-strategy overrides | |
| 418 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 419 | +""" | |
| 420 | +# Sub-strategy with parameters specific to BTC stake | |
| 421 | +class Schism3_BTC(Schism3): | |
| 422 | + | |
| 423 | + timeframe = '1h' | |
| 424 | + inf_timeframe = '4h' | |
| 425 | + | |
| 426 | + buy_params = { | |
| 427 | + 'inf-rsi': 64, | |
| 428 | + 'mp': 55, | |
| 429 | + 'rmi-fast': 31, | |
| 430 | + 'rmi-slow': 16, | |
| 431 | + 'xinf-stake-rmi': 67, | |
| 432 | + 'xtf-fiat-rsi': 17, | |
| 433 | + 'xtf-stake-rsi': 57 | |
| 434 | + } | |
| 435 | + | |
| 436 | + minimal_roi = { | |
| 437 | + "0": 0.05, | |
| 438 | + "240": 0.025, | |
| 439 | + "1440": 0.01, | |
| 440 | + "4320": 0 | |
| 441 | + } | |
| 442 | + | |
| 443 | + use_sell_signal = False | |
| 444 | + | |
| 445 | +# Sub-strategy with parameters specific to ETH stake | |
| 446 | +class Schism3_ETH(Schism3): | |
| 447 | + | |
| 448 | + timeframe = '1h' | |
| 449 | + inf_timeframe = '4h' | |
| 450 | + | |
| 451 | + buy_params = { | |
| 452 | + 'inf-rsi': 13, | |
| 453 | + 'inf-stake-rmi': 69, | |
| 454 | + 'mp': 40, | |
| 455 | + 'rmi-fast': 42, | |
| 456 | + 'rmi-slow': 17, | |
| 457 | + 'tf-fiat-rsi': 15, | |
| 458 | + 'tf-stake-rsi': 92 | |
| 459 | + } | |
| 460 | + | |
| 461 | + minimal_roi = { | |
| 462 | + "0": 0.05, | |
| 463 | + "240": 0.025, | |
| 464 | + "1440": 0.01, | |
| 465 | + "4320": 0 | |
| 466 | + } | |
| 467 | + | |
| 468 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Schism-v1.4.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 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | +""" | |
| 18 | +TODO: | |
| 19 | + | |
| 20 | +""" | |
| 21 | + | |
| 22 | +class Schism4(IStrategy): | |
| 23 | + """ | |
| 24 | + Strategy Configuration Items | |
| 25 | + """ | |
| 26 | + timeframe = '5m' | |
| 27 | + inf_timeframe = '1h' | |
| 28 | + | |
| 29 | + # Global Buy/Sell Params | |
| 30 | + buy_params = { | |
| 31 | + 'inf-rsi': 58, | |
| 32 | + 'mp': 26, | |
| 33 | + 'rmi-fast': 11, | |
| 34 | + 'rmi-slow': 55, | |
| 35 | + 'xinf-stake-rmi': 25, | |
| 36 | + 'xtf-fiat-rsi': 64, | |
| 37 | + 'xtf-stake-rsi': 90 | |
| 38 | + } | |
| 39 | + | |
| 40 | + sell_params = { | |
| 41 | + 'rmi-high': 50, | |
| 42 | + 'rmi-low': 10 | |
| 43 | + } | |
| 44 | + | |
| 45 | + # Pair Specific Buy/Sell Params | |
| 46 | + buy_params_FOO = {} | |
| 47 | + sell_params_FOO = {} | |
| 48 | + | |
| 49 | + minimal_roi = { | |
| 50 | + "0": 0.05, | |
| 51 | + "10": 0.025, | |
| 52 | + "20": 0.015, | |
| 53 | + "30": 0.01, | |
| 54 | + "720": 0.005, | |
| 55 | + "1440": 0 | |
| 56 | + } | |
| 57 | + | |
| 58 | + stoploss = -0.30 | |
| 59 | + | |
| 60 | + use_sell_signal = False | |
| 61 | + sell_profit_only = False | |
| 62 | + ignore_roi_if_buy_signal = True | |
| 63 | + | |
| 64 | + startup_candle_count: int = 72 | |
| 65 | + | |
| 66 | + # Startegy Specific Variable Storage | |
| 67 | + custom_trade_info = {} | |
| 68 | + custom_fiat = "USD" | |
| 69 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 70 | + | |
| 71 | + """ | |
| 72 | + Informative Pair Definitions | |
| 73 | + """ | |
| 74 | + def informative_pairs(self): | |
| 75 | + # add existing pairs from whitelist on the inf_timeframe | |
| 76 | + pairs = self.dp.current_whitelist() | |
| 77 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 78 | + | |
| 79 | + # add additional informative pairs based on certain stakes | |
| 80 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 81 | + for pair in pairs: | |
| 82 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) on base timeframe | |
| 83 | + coin, stake = pair.split('/') | |
| 84 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 85 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 86 | + | |
| 87 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) on base and inf timeframes | |
| 88 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 89 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 90 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 91 | + | |
| 92 | + return informative_pairs | |
| 93 | + | |
| 94 | + """ | |
| 95 | + Indicator Definitions | |
| 96 | + """ | |
| 97 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 98 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 99 | + | |
| 100 | + # Relative Momentum Index | |
| 101 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 102 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 103 | + | |
| 104 | + # Momentum Pinball | |
| 105 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 106 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 107 | + | |
| 108 | + # Trend Calculations | |
| 109 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 110 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 111 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 112 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 113 | + | |
| 114 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 115 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 116 | + coin, stake = metadata['pair'].split('/') | |
| 117 | + fiat = self.custom_fiat | |
| 118 | + coin_fiat = f"{coin}/{fiat}" | |
| 119 | + stake_fiat = f"{stake}/{fiat}" | |
| 120 | + | |
| 121 | + # COIN/FIAT (e.g. XLM/USD) - timeframe | |
| 122 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 123 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 124 | + | |
| 125 | + # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe | |
| 126 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 127 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 128 | + | |
| 129 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 130 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 131 | + | |
| 132 | + # Informative indicators for current pair on inf_timeframe | |
| 133 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 134 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 135 | + | |
| 136 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 137 | + | |
| 138 | + return dataframe | |
| 139 | + | |
| 140 | + """ | |
| 141 | + Buy Trigger Signals | |
| 142 | + """ | |
| 143 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 144 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 145 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 146 | + conditions = [] | |
| 147 | + | |
| 148 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 149 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 150 | + if trade_data['active_trade']: | |
| 151 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 152 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 153 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 154 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 155 | + | |
| 156 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 157 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 158 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 159 | + | |
| 160 | + # Normal buy triggers that apply to new trades we want to enter | |
| 161 | + else: | |
| 162 | + conditions.append( | |
| 163 | + (dataframe[f"rsi_{self.inf_timeframe}"] <= params['inf-rsi']) & | |
| 164 | + (dataframe['rmi-up-trend'] == 1) & | |
| 165 | + (dataframe['rmi-slow'] <= params['rmi-slow']) & | |
| 166 | + (dataframe['rmi-fast'] >= params['rmi-fast']) & | |
| 167 | + (dataframe['mp'] >= params['mp']) | |
| 168 | + ) | |
| 169 | + | |
| 170 | + # If the stake is BTC or ETH apply additional conditions | |
| 171 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 172 | + # default timeframe conditions | |
| 173 | + conditions.append( | |
| 174 | + (dataframe[f"{self.config['stake_currency']}_rsi"] < params['xtf-stake-rsi']) | | |
| 175 | + (dataframe[f"{self.custom_fiat}_rsi"] > params['xtf-fiat-rsi']) | |
| 176 | + ) | |
| 177 | + # informative timeframe conditions | |
| 178 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 179 | + | |
| 180 | + # Anything below here applies to persisting and new buy signal | |
| 181 | + conditions.append(dataframe['volume'].gt(0)) | |
| 182 | + | |
| 183 | + if conditions: | |
| 184 | + dataframe.loc[ | |
| 185 | + reduce(lambda x, y: x & y, conditions), | |
| 186 | + 'buy'] = 1 | |
| 187 | + | |
| 188 | + return dataframe | |
| 189 | + | |
| 190 | + """ | |
| 191 | + Sell Trigger Signals: | |
| 192 | + In this strategy all sells for profit happen according to ROI | |
| 193 | + This sell signal is designed only as a "dynamic stoploss" | |
| 194 | + """ | |
| 195 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 196 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 197 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 198 | + conditions = [] | |
| 199 | + | |
| 200 | + # add additional conditions based on time and profit | |
| 201 | + if trade_data['active_trade']: | |
| 202 | + # give some wiggle room for the trade to go negative a little bit before selling | |
| 203 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 204 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 205 | + | |
| 206 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 207 | + conditions.append( | |
| 208 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 209 | + (trade_data['current_profit'] > self.stoploss) & | |
| 210 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 211 | + (dataframe['volume'].gt(0)) | |
| 212 | + ) | |
| 213 | + | |
| 214 | + # if the peak profit was positive at some point but never reached ROI, set a higher cross point for exit | |
| 215 | + if trade_data['peak_profit'] > 0: | |
| 216 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-high'])) | |
| 217 | + # if the trade was always negative, the bounce we expected didn't happen | |
| 218 | + else: | |
| 219 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-low'])) | |
| 220 | + | |
| 221 | + # if we have other trades, consider their profit and the # of free slots in the sell | |
| 222 | + if trade_data['other_trades']: | |
| 223 | + if trade_data['free_slots'] > 0: | |
| 224 | + """ | |
| 225 | + Less free slots, more willing to sell | |
| 226 | + 1 / free_slots * x = | |
| 227 | + 1 slot = 1/1 * -0.04 = -0.04 -> only allow sells if avg_other_proift above -0.04 | |
| 228 | + 4 slot = 1/4 * -0.04 = -0.01 -> only allow sells is avg_other_profit above -0.01 | |
| 229 | + """ | |
| 230 | + max_market_down = -0.04 | |
| 231 | + hold_pct = (1/trade_data['free_slots']) * max_market_down | |
| 232 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 233 | + else: | |
| 234 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 235 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 236 | + | |
| 237 | + # Impossible condition to satisfy the bot when it looks here and theres no active trade | |
| 238 | + else: | |
| 239 | + conditions.append(dataframe['volume'].lt(0)) | |
| 240 | + | |
| 241 | + if conditions: | |
| 242 | + dataframe.loc[ | |
| 243 | + reduce(lambda x, y: x & y, conditions), | |
| 244 | + 'sell'] = 1 | |
| 245 | + | |
| 246 | + return dataframe | |
| 247 | + | |
| 248 | + """ | |
| 249 | + Custom Methods | |
| 250 | + """ | |
| 251 | + # Populate trades_data from the database | |
| 252 | + def populate_trades(self, pair: str) -> dict: | |
| 253 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 254 | + if not pair in self.custom_trade_info: | |
| 255 | + self.custom_trade_info[pair] = {} | |
| 256 | + | |
| 257 | + # init the temp dicts and set the trade stuff to false | |
| 258 | + trade_data = {} | |
| 259 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 260 | + self.custom_trade_info['meta'] = {} | |
| 261 | + | |
| 262 | + # active trade stuff only works in live and dry, not backtest | |
| 263 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 264 | + | |
| 265 | + # find out if we have an open trade for this pair | |
| 266 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 267 | + | |
| 268 | + # if so, get some information | |
| 269 | + if active_trade: | |
| 270 | + # get current price and update the min/max rate | |
| 271 | + current_rate = self.get_current_price(pair, True) | |
| 272 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 273 | + | |
| 274 | + # get how long the trade has been open in minutes and candles | |
| 275 | + present = arrow.utcnow() | |
| 276 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 277 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 278 | + | |
| 279 | + # set up the things we use in the strategy | |
| 280 | + trade_data['active_trade'] = True | |
| 281 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 282 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 283 | + trade_data['open_minutes'] : int = open_minutes | |
| 284 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 285 | + else: | |
| 286 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 287 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 288 | + | |
| 289 | + # if there are open trades not including the current pair, get some information | |
| 290 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 291 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 292 | + | |
| 293 | + if other_trades: | |
| 294 | + trade_data['other_trades'] = True | |
| 295 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 296 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 297 | + # find which of our trades is the biggest loser | |
| 298 | + if trade_data['current_profit'] < min(other_profit): | |
| 299 | + trade_data['biggest_loser'] = True | |
| 300 | + else: | |
| 301 | + trade_data['avg_other_profit'] = 0 | |
| 302 | + | |
| 303 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 304 | + open_trades = len(Trade.get_open_trades()) | |
| 305 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 306 | + | |
| 307 | + return trade_data | |
| 308 | + | |
| 309 | + # Get the current price from the exchange (or cache) | |
| 310 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 311 | + if not refresh: | |
| 312 | + rate = self.custom_current_price_cache.get(pair) | |
| 313 | + # Check if cache has been invalidated | |
| 314 | + if rate: | |
| 315 | + return rate | |
| 316 | + | |
| 317 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 318 | + if ask_strategy.get('use_order_book', False): | |
| 319 | + ob = self.dp.orderbook(pair, 1) | |
| 320 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 321 | + else: | |
| 322 | + ticker = self.dp.ticker(pair) | |
| 323 | + rate = ticker['last'] | |
| 324 | + | |
| 325 | + self.custom_current_price_cache[pair] = rate | |
| 326 | + return rate | |
| 327 | + | |
| 328 | + """ | |
| 329 | + Simple linear growth function: | |
| 330 | + Starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 331 | + f(t) = X + (rate * t), where rate = (Y - X) / (B - A) | |
| 332 | + """ | |
| 333 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 334 | + time = max(0, trade_time - start_time) | |
| 335 | + rate = (end - start) / (end_time - start_time) | |
| 336 | + return min(end, start + (rate * time)) | |
| 337 | + | |
| 338 | + """ | |
| 339 | + Allow for buy/sell override parameters per pair. Testing, might remove. | |
| 340 | + TODO: | |
| 341 | + If good: make this more robust so you never have to edit this method. | |
| 342 | + Consider: per-pair ROI if it seems worthwhile? | |
| 343 | + """ | |
| 344 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 345 | + buy_params = self.buy_params | |
| 346 | + sell_params = self.sell_params | |
| 347 | + | |
| 348 | + ### Stake: USD | |
| 349 | + if pair in ('ABC/XYZ', 'DEF/XYZ'): | |
| 350 | + buy_params = self.buy_params_GROUP1 | |
| 351 | + sell_params = self.sell_params_GROUP1 | |
| 352 | + elif pair in ('QRD/WTF'): | |
| 353 | + buy_params = self.buy_params_QRD | |
| 354 | + sell_params = self.sell_params_QRD | |
| 355 | + | |
| 356 | + if side == 'sell': | |
| 357 | + return sell_params | |
| 358 | + | |
| 359 | + return buy_params | |
| 360 | + | |
| 361 | + """ | |
| 362 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 363 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 364 | + """ | |
| 365 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 366 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 367 | + ob = self.dp.orderbook(pair, 1) | |
| 368 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 369 | + # Cancel buy order if price is more than 1% above the order. | |
| 370 | + if current_price > order['price'] * 1.01: | |
| 371 | + return True | |
| 372 | + return False | |
| 373 | + | |
| 374 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 375 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 376 | + ob = self.dp.orderbook(pair, 1) | |
| 377 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 378 | + # Cancel sell order if price is more than 1% below the order. | |
| 379 | + if current_price < order['price'] * 0.99: | |
| 380 | + return True | |
| 381 | + return False | |
| 382 | + | |
| 383 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 384 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 385 | + ob = self.dp.orderbook(pair, 1) | |
| 386 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 387 | + # Cancel buy order if price is more than 1% above the order. | |
| 388 | + if current_price > rate * 1.01: | |
| 389 | + return False | |
| 390 | + return True | |
| 391 | + | |
| 392 | +""" | |
| 393 | +Sub-strategy overrides | |
| 394 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 395 | +""" | |
| 396 | +# Sub-strategy with parameters specific to BTC stake | |
| 397 | +class Schism4_BTC(Schism4): | |
| 398 | + | |
| 399 | + timeframe = '1h' | |
| 400 | + inf_timeframe = '4h' | |
| 401 | + | |
| 402 | + buy_params = { | |
| 403 | + 'inf-rsi': 64, | |
| 404 | + 'mp': 55, | |
| 405 | + 'rmi-fast': 31, | |
| 406 | + 'rmi-slow': 16, | |
| 407 | + 'xinf-stake-rmi': 67, | |
| 408 | + 'xtf-fiat-rsi': 17, | |
| 409 | + 'xtf-stake-rsi': 57 | |
| 410 | + } | |
| 411 | + | |
| 412 | + minimal_roi = { | |
| 413 | + "0": 0.05, | |
| 414 | + "240": 0.025, | |
| 415 | + "1440": 0.01, | |
| 416 | + "4320": 0 | |
| 417 | + } | |
| 418 | + | |
| 419 | + use_sell_signal = False | |
| 420 | + | |
| 421 | +# Sub-strategy with parameters specific to ETH stake | |
| 422 | +class Schism4_ETH(Schism4): | |
| 423 | + | |
| 424 | + timeframe = '1h' | |
| 425 | + inf_timeframe = '4h' | |
| 426 | + | |
| 427 | + buy_params = { | |
| 428 | + 'inf-rsi': 13, | |
| 429 | + 'inf-stake-rmi': 69, | |
| 430 | + 'mp': 40, | |
| 431 | + 'rmi-fast': 42, | |
| 432 | + 'rmi-slow': 17, | |
| 433 | + 'tf-fiat-rsi': 15, | |
| 434 | + 'tf-stake-rsi': 92 | |
| 435 | + } | |
| 436 | + | |
| 437 | + minimal_roi = { | |
| 438 | + "0": 0.05, | |
| 439 | + "240": 0.025, | |
| 440 | + "1440": 0.01, | |
| 441 | + "4320": 0 | |
| 442 | + } | |
| 443 | + | |
| 444 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Schism-v1.5.py +310 −0
| @@ -0,0 +1,310 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime, timedelta | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | +class Schism5(IStrategy): | |
| 18 | + """ | |
| 19 | + Strategy Configuration Items | |
| 20 | + """ | |
| 21 | + timeframe = '5m' | |
| 22 | + inf_timeframe = '1h' | |
| 23 | + | |
| 24 | + buy_params = { | |
| 25 | + 'bear-buy-rsi': 49, | |
| 26 | + 'bull-buy-rsi': 39 | |
| 27 | + } | |
| 28 | + | |
| 29 | + sell_params = { | |
| 30 | + 'bear-sell-rsi': 86, | |
| 31 | + 'bull-sell-rsi': 86 | |
| 32 | + } | |
| 33 | + | |
| 34 | + minimal_roi = { | |
| 35 | + "0": 0.14025, | |
| 36 | + "34": 0.08031, | |
| 37 | + "86": 0.03995, | |
| 38 | + "203": 0 | |
| 39 | + } | |
| 40 | + | |
| 41 | + stoploss = -0.30 | |
| 42 | + use_custom_stoploss = True | |
| 43 | + custom_stop_ramp_minutes = 110 | |
| 44 | + custom_stop_trailing = 0.001 | |
| 45 | + | |
| 46 | + use_sell_signal = True | |
| 47 | + sell_profit_only = True | |
| 48 | + ignore_roi_if_buy_signal = True | |
| 49 | + | |
| 50 | + startup_candle_count: int = 72 | |
| 51 | + | |
| 52 | + custom_trade_info = {} | |
| 53 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 54 | + | |
| 55 | + """ | |
| 56 | + Informative Pair Definitions | |
| 57 | + """ | |
| 58 | + def informative_pairs(self): | |
| 59 | + # add existing pairs from whitelist on the inf_timeframe | |
| 60 | + pairs = self.dp.current_whitelist() | |
| 61 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 62 | + | |
| 63 | + return informative_pairs | |
| 64 | + | |
| 65 | + """ | |
| 66 | + Indicator Definitions | |
| 67 | + """ | |
| 68 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 69 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 70 | + | |
| 71 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 72 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 73 | + | |
| 74 | + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) | |
| 75 | + | |
| 76 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 77 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 78 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 79 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 80 | + | |
| 81 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 82 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 83 | + | |
| 84 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 85 | + | |
| 86 | + dataframe['bull'] = dataframe[f"rsi_{self.inf_timeframe}"].gt(60).astype('int') * 20 | |
| 87 | + | |
| 88 | + return dataframe | |
| 89 | + | |
| 90 | + """ | |
| 91 | + Buy Trigger Signals | |
| 92 | + """ | |
| 93 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 94 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 95 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 96 | + conditions = [] | |
| 97 | + | |
| 98 | + if trade_data['active_trade']: | |
| 99 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 100 | + rmi_grow = self.linear_growth(30, 70, 0, 240, trade_data['open_minutes']) | |
| 101 | + | |
| 102 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 103 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 104 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 105 | + | |
| 106 | + else: | |
| 107 | + | |
| 108 | + conditions.append( | |
| 109 | + ((dataframe['bull'] > 0) & qtpylib.crossed_below(dataframe['rsi'], params['bull-buy-rsi'])) | | |
| 110 | + (~(dataframe['bull'] > 0) & qtpylib.crossed_below(dataframe['rsi'], params['bear-buy-rsi'])) | |
| 111 | + ) | |
| 112 | + | |
| 113 | + conditions.append(dataframe['volume'].gt(0)) | |
| 114 | + | |
| 115 | + if conditions: | |
| 116 | + dataframe.loc[ | |
| 117 | + reduce(lambda x, y: x & y, conditions), | |
| 118 | + 'buy'] = 1 | |
| 119 | + | |
| 120 | + return dataframe | |
| 121 | + | |
| 122 | + """ | |
| 123 | + Sell Trigger Signals | |
| 124 | + """ | |
| 125 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 126 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 127 | + conditions = [] | |
| 128 | + | |
| 129 | + conditions.append( | |
| 130 | + ((dataframe['bull'] > 0) & (dataframe['rsi'] > params['bull-sell-rsi'])) | | |
| 131 | + (~(dataframe['bull'] > 0) & (dataframe['rsi'] > params['bear-sell-rsi'])) | |
| 132 | + ) | |
| 133 | + | |
| 134 | + conditions.append(dataframe['volume'].gt(0)) | |
| 135 | + | |
| 136 | + if conditions: | |
| 137 | + dataframe.loc[ | |
| 138 | + reduce(lambda x, y: x & y, conditions), | |
| 139 | + 'sell'] = 1 | |
| 140 | + | |
| 141 | + return dataframe | |
| 142 | + | |
| 143 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 144 | + | |
| 145 | + since_open = current_time - trade.open_date | |
| 146 | + | |
| 147 | + sl_pct = 1 - (max(min(since_open / timedelta(minutes=self.custom_stop_ramp_minutes), 1), 0))**3 | |
| 148 | + sl_ramp = self.stoploss * sl_pct | |
| 149 | + | |
| 150 | + return min(0, sl_ramp) - self.custom_stop_trailing | |
| 151 | + | |
| 152 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 153 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 154 | + ob = self.dp.orderbook(pair, 1) | |
| 155 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 156 | + if current_price > order['price'] * 1.01: | |
| 157 | + return True | |
| 158 | + return False | |
| 159 | + | |
| 160 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 161 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 162 | + ob = self.dp.orderbook(pair, 1) | |
| 163 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 164 | + if current_price < order['price'] * 0.99: | |
| 165 | + return True | |
| 166 | + return False | |
| 167 | + | |
| 168 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 169 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 170 | + ob = self.dp.orderbook(pair, 1) | |
| 171 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 172 | + if current_price > rate * 1.01: | |
| 173 | + return False | |
| 174 | + return True | |
| 175 | + | |
| 176 | + """ | |
| 177 | + Custom Methods | |
| 178 | + """ | |
| 179 | + def populate_trades(self, pair: str) -> dict: | |
| 180 | + if not pair in self.custom_trade_info: | |
| 181 | + self.custom_trade_info[pair] = {} | |
| 182 | + | |
| 183 | + trade_data = {} | |
| 184 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 185 | + self.custom_trade_info['meta'] = {} | |
| 186 | + | |
| 187 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 188 | + | |
| 189 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 190 | + | |
| 191 | + if active_trade: | |
| 192 | + current_rate = self.get_current_price(pair, True) | |
| 193 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 194 | + | |
| 195 | + present = arrow.utcnow() | |
| 196 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 197 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 198 | + | |
| 199 | + trade_data['active_trade'] = True | |
| 200 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 201 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 202 | + trade_data['open_minutes'] : int = open_minutes | |
| 203 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 204 | + else: | |
| 205 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 206 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 207 | + | |
| 208 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 209 | + | |
| 210 | + if other_trades: | |
| 211 | + trade_data['other_trades'] = True | |
| 212 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 213 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 214 | + if trade_data['current_profit'] < min(other_profit): | |
| 215 | + trade_data['biggest_loser'] = True | |
| 216 | + else: | |
| 217 | + trade_data['avg_other_profit'] = 0 | |
| 218 | + | |
| 219 | + open_trades = len(Trade.get_open_trades()) | |
| 220 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 221 | + | |
| 222 | + return trade_data | |
| 223 | + | |
| 224 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 225 | + if not refresh: | |
| 226 | + rate = self.custom_current_price_cache.get(pair) | |
| 227 | + if rate: | |
| 228 | + return rate | |
| 229 | + | |
| 230 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 231 | + if ask_strategy.get('use_order_book', False): | |
| 232 | + ob = self.dp.orderbook(pair, 1) | |
| 233 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 234 | + else: | |
| 235 | + ticker = self.dp.ticker(pair) | |
| 236 | + rate = ticker['last'] | |
| 237 | + | |
| 238 | + self.custom_current_price_cache[pair] = rate | |
| 239 | + return rate | |
| 240 | + | |
| 241 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 242 | + time = max(0, trade_time - start_time) | |
| 243 | + rate = (end - start) / (end_time - start_time) | |
| 244 | + return min(end, start + (rate * time)) | |
| 245 | + | |
| 246 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 247 | + buy_params = self.buy_params | |
| 248 | + sell_params = self.sell_params | |
| 249 | + | |
| 250 | + ### Stake: USD | |
| 251 | + if pair in ('ABC/XYZ', 'DEF/XYZ'): | |
| 252 | + buy_params = self.buy_params_GROUP1 | |
| 253 | + sell_params = self.sell_params_GROUP1 | |
| 254 | + elif pair in ('QRD/WTF'): | |
| 255 | + buy_params = self.buy_params_QRD | |
| 256 | + sell_params = self.sell_params_QRD | |
| 257 | + | |
| 258 | + if side == 'sell': | |
| 259 | + return sell_params | |
| 260 | + | |
| 261 | + return buy_params | |
| 262 | + | |
| 263 | + | |
| 264 | +class Schism5_BTC(Schism5): | |
| 265 | + | |
| 266 | + timeframe = '1h' | |
| 267 | + inf_timeframe = '4h' | |
| 268 | + | |
| 269 | + buy_params = { | |
| 270 | + 'inf-rsi': 64, | |
| 271 | + 'mp': 55, | |
| 272 | + 'rmi-fast': 31, | |
| 273 | + 'rmi-slow': 16, | |
| 274 | + 'xinf-stake-rmi': 67, | |
| 275 | + 'xtf-fiat-rsi': 17, | |
| 276 | + 'xtf-stake-rsi': 57 | |
| 277 | + } | |
| 278 | + | |
| 279 | + minimal_roi = { | |
| 280 | + "0": 0.05, | |
| 281 | + "240": 0.025, | |
| 282 | + "1440": 0.01, | |
| 283 | + "4320": 0 | |
| 284 | + } | |
| 285 | + | |
| 286 | + use_sell_signal = False | |
| 287 | + | |
| 288 | +class Schism5_ETH(Schism5): | |
| 289 | + | |
| 290 | + timeframe = '1h' | |
| 291 | + inf_timeframe = '4h' | |
| 292 | + | |
| 293 | + buy_params = { | |
| 294 | + 'inf-rsi': 13, | |
| 295 | + 'inf-stake-rmi': 69, | |
| 296 | + 'mp': 40, | |
| 297 | + 'rmi-fast': 42, | |
| 298 | + 'rmi-slow': 17, | |
| 299 | + 'tf-fiat-rsi': 15, | |
| 300 | + 'tf-stake-rsi': 92 | |
| 301 | + } | |
| 302 | + | |
| 303 | + minimal_roi = { | |
| 304 | + "0": 0.05, | |
| 305 | + "240": 0.025, | |
| 306 | + "1440": 0.01, | |
| 307 | + "4320": 0 | |
| 308 | + } | |
| 309 | + | |
| 310 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Schism-v1.6.py +608 −0
| @@ -0,0 +1,608 @@ | ||
| 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 | |
| 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 technical.indicators import RMI, PMAX | |
| 14 | +from statistics import mean | |
| 15 | +from cachetools import TTLCache | |
| 16 | + | |
| 17 | +import pandas as pd | |
| 18 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 19 | + | |
| 20 | +""" | |
| 21 | +TODO: | |
| 22 | + - Continue to hunt for a better all around buy signal. | |
| 23 | + - Existing signal to "buy the dip" seems to work well but would it be nice to have an additional | |
| 24 | + buy signal for strong upward trends without dips? | |
| 25 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 26 | + - Fibonacci Retracement for resistance/support levels? | |
| 27 | + - TD Sequential? | |
| 28 | + - Tweak ROI Trend Ride | |
| 29 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 30 | + - Maybe further exploit the ROI table itself using trade data? | |
| 31 | + - Tweak sell signal | |
| 32 | + - Continue to evaluate good circumstances to bail and sell vs hold | |
| 33 | + - Optimize Custom Stop Loss | |
| 34 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 35 | + - Per-pair automatic/dynamic ROI based on ADR/ATR or something similar? | |
| 36 | + | |
| 37 | +NOTES: | |
| 38 | + - It is recommended to configure protections as you will use in live and run hyperopt/backtest with | |
| 39 | + --enable-protections as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 40 | + to test. | |
| 41 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 42 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 43 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 44 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 45 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 46 | + ROI based sells will be higher than the backtest shows. | |
| 47 | +""" | |
| 48 | + | |
| 49 | +class Schism6(IStrategy): | |
| 50 | + | |
| 51 | + timeframe = '5m' | |
| 52 | + inf_timeframe = '1h' | |
| 53 | + | |
| 54 | + buy_params = { | |
| 55 | + 'inf-guard': 'upper', | |
| 56 | + 'inf-pct-adr-bot': 0.08848, | |
| 57 | + 'inf-pct-adr-top': 0.82507, | |
| 58 | + 'base-mp': 68, | |
| 59 | + 'base-rmi-fast': 47, | |
| 60 | + 'base-rmi-slow': 16, | |
| 61 | + 'xtra-inf-stake-rmi': 54, | |
| 62 | + 'xtra-base-fiat-rsi': 69, | |
| 63 | + 'xtra-base-stake-rsi': 61 | |
| 64 | + } | |
| 65 | + | |
| 66 | + sell_params = { | |
| 67 | + 'sell-rmi-drop': 0.50 | |
| 68 | + } | |
| 69 | + | |
| 70 | + minimal_roi = { | |
| 71 | + "0": 0.05, | |
| 72 | + "30": 0.025, | |
| 73 | + "120": 0.01, | |
| 74 | + "360": 0.01, | |
| 75 | + "1440": 0 | |
| 76 | + } | |
| 77 | + | |
| 78 | + dynamic_roi = { | |
| 79 | + 'dynamic_roi_enabled': True, | |
| 80 | + 'dynamic_roi_type': 'connect' | |
| 81 | + } | |
| 82 | + | |
| 83 | + stoploss = -0.30 | |
| 84 | + use_custom_stoploss = True | |
| 85 | + | |
| 86 | + custom_stop = { | |
| 87 | + 'decay-time': 1080, # minutes to reach end | |
| 88 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 89 | + 'decay-start': -0.30, # should be the same as initial stoploss | |
| 90 | + 'decay-end': -0.03, # ending value | |
| 91 | + } | |
| 92 | + | |
| 93 | + # Recommended | |
| 94 | + use_sell_signal = True | |
| 95 | + sell_profit_only = False | |
| 96 | + ignore_roi_if_buy_signal = True | |
| 97 | + | |
| 98 | + startup_candle_count: int = 72 | |
| 99 | + | |
| 100 | + # Strategy Specific Variable Storage | |
| 101 | + custom_trade_info = {} | |
| 102 | + custom_fiat = "USD" | |
| 103 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 104 | + | |
| 105 | + """ | |
| 106 | + Informative Pair Definitions | |
| 107 | + """ | |
| 108 | + def informative_pairs(self): | |
| 109 | + pairs = self.dp.current_whitelist() | |
| 110 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 111 | + | |
| 112 | + # add extra informative pairs if the stake is BTC or ETH | |
| 113 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 114 | + for pair in pairs: | |
| 115 | + coin, stake = pair.split('/') | |
| 116 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 117 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 118 | + | |
| 119 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 120 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 121 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 122 | + | |
| 123 | + return informative_pairs | |
| 124 | + | |
| 125 | + """ | |
| 126 | + Indicator Definitions | |
| 127 | + """ | |
| 128 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 129 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 130 | + | |
| 131 | + # Base timeframe indicators | |
| 132 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 133 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 134 | + | |
| 135 | + # Momentum Pinball: | |
| 136 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 137 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 138 | + | |
| 139 | + # RMI Trends and Peaks | |
| 140 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 141 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 142 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 143 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 144 | + dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max() | |
| 145 | + | |
| 146 | + # See: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L1059 | |
| 147 | + # matype = vidya, src = hl2 | |
| 148 | + dataframe = PMAX(dataframe, period=10, multiplier=3, length=10, MAtype=5, src=2) | |
| 149 | + | |
| 150 | + # Other stake specific informative indicators | |
| 151 | + # TODO: Re-evaluate the value of these informative indicators | |
| 152 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 153 | + coin, stake = metadata['pair'].split('/') | |
| 154 | + fiat = self.custom_fiat | |
| 155 | + coin_fiat = f"{coin}/{fiat}" | |
| 156 | + stake_fiat = f"{stake}/{fiat}" | |
| 157 | + | |
| 158 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 159 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 160 | + | |
| 161 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 162 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 163 | + | |
| 164 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 165 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 166 | + | |
| 167 | + # Base pair informative timeframe indicators | |
| 168 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 169 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 170 | + | |
| 171 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 172 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 173 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 174 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 175 | + | |
| 176 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 177 | + | |
| 178 | + dataframe.to_csv('user_data/foo.csv') | |
| 179 | + | |
| 180 | + return dataframe | |
| 181 | + | |
| 182 | + """ | |
| 183 | + Buy Signal | |
| 184 | + """ | |
| 185 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 186 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 187 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 188 | + conditions = [] | |
| 189 | + | |
| 190 | + """ | |
| 191 | + The primary "secret sauce" of Schism is to take advantage of the ignore_roi_if_buy_signal setting. | |
| 192 | + Ideally, the ROI table is very tight and aggressive allowing for quick exits on ROI without reliance | |
| 193 | + on a sell signal. However, if certain criteria are met for an open trade, we stimulate a sticking buy | |
| 194 | + signal on purpose to prevent the bot from selling to the ROI in the midst of an upward trend. | |
| 195 | + | |
| 196 | + This is not currently able to be backtested or hyperopted so all settings here must be tested and validated | |
| 197 | + in dry-run or live. It is safe to assume that when backtesting, all sells for reason roi will have likely been | |
| 198 | + for higher profits in live trading than in backtest. | |
| 199 | + """ | |
| 200 | + | |
| 201 | + # If active trade, look at trend to persist a buy signal for ignore_roi_if_buy_signal | |
| 202 | + if trade_data['active_trade']: | |
| 203 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 204 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 205 | + | |
| 206 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 207 | + # TODO: Experiment with replacing or augmenting this with PMAX | |
| 208 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 209 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 210 | + | |
| 211 | + # Standard signals for entering new trades | |
| 212 | + else: | |
| 213 | + | |
| 214 | + # Guards on informative timeframe | |
| 215 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 216 | + conditions.append( | |
| 217 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 218 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 219 | + ) | |
| 220 | + | |
| 221 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 222 | + conditions.append( | |
| 223 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 224 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 225 | + ) | |
| 226 | + | |
| 227 | + # Primary buy signal | |
| 228 | + conditions.append( | |
| 229 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 230 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 231 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 232 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 233 | + (dataframe['mp'] <= params['base-mp']) | |
| 234 | + ) | |
| 235 | + | |
| 236 | + # Extra conditions for BTC/ETH stakes on additional informative pairs | |
| 237 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 238 | + conditions.append( | |
| 239 | + (dataframe[f"{self.config['stake_currency']}_rsi"] < params['xtra-base-stake-rsi']) | | |
| 240 | + (dataframe[f"{self.custom_fiat}_rsi"] > params['xtra-base-fiat-rsi']) | |
| 241 | + ) | |
| 242 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 243 | + | |
| 244 | + # Applies to active or new trades | |
| 245 | + conditions.append(dataframe['volume'].gt(0)) | |
| 246 | + | |
| 247 | + if conditions: | |
| 248 | + dataframe.loc[ | |
| 249 | + reduce(lambda x, y: x & y, conditions), | |
| 250 | + 'buy'] = 1 | |
| 251 | + | |
| 252 | + return dataframe | |
| 253 | + | |
| 254 | + """ | |
| 255 | + Sell Signal | |
| 256 | + """ | |
| 257 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 258 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 259 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 260 | + conditions = [] | |
| 261 | + | |
| 262 | + """ | |
| 263 | + Previous Schism sell implementation has been *partially* replaced by custom_stoploss. | |
| 264 | + Doing it there makes it able to be backtested more realistically but some of the functionality | |
| 265 | + such as the ability to use other trades or the # of slots in our decision need to remain here. | |
| 266 | + | |
| 267 | + The current sell is meant to be a pre-stoploss bailout but most sells at a loss | |
| 268 | + should happen due to the stoploss in live/dry. | |
| 269 | + | |
| 270 | + ** Only part of this signal functions in backtest/hyperopt. Can only be optimized in live/dry. | |
| 271 | + ** Results in backtest/hyperopts will sell far more readily than in live due to the profit guards. | |
| 272 | + """ | |
| 273 | + | |
| 274 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 275 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 276 | + if trade_data['active_trade']: | |
| 277 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 278 | + # a trade to go into the negative a little bit before we react to sell. | |
| 279 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 240, trade_data['open_minutes']) | |
| 280 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 281 | + | |
| 282 | + # Primary sell trigger | |
| 283 | + # TODO: Experiment with replacing or augmenting this with PMAX | |
| 284 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * 0.50) | |
| 285 | + conditions.append( | |
| 286 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 287 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 288 | + (dataframe['volume'].gt(0)) | |
| 289 | + ) | |
| 290 | + | |
| 291 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 292 | + if trade_data['other_trades']: | |
| 293 | + if trade_data['free_slots'] > 0: | |
| 294 | + # If the average of all our other trades is below a certain threshold based | |
| 295 | + # on free slots available, hold and wait for market recovery. | |
| 296 | + max_market_down = -0.04 | |
| 297 | + hold_pct = (1/trade_data['free_slots']) * max_market_down | |
| 298 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 299 | + else: | |
| 300 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 301 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 302 | + else: | |
| 303 | + # This is an impossible condition but needs to be here for some reason? | |
| 304 | + conditions.append(dataframe['volume'].lt(0)) | |
| 305 | + | |
| 306 | + """ | |
| 307 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 308 | + | |
| 309 | + conditions.append( | |
| 310 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 311 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 312 | + (dataframe['volume'].gt(0)) | |
| 313 | + ) | |
| 314 | + """ | |
| 315 | + | |
| 316 | + if conditions: | |
| 317 | + dataframe.loc[ | |
| 318 | + reduce(lambda x, y: x & y, conditions), | |
| 319 | + 'sell'] = 1 | |
| 320 | + | |
| 321 | + return dataframe | |
| 322 | + | |
| 323 | + """ | |
| 324 | + Custom Stoploss | |
| 325 | + """ | |
| 326 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 327 | + start = self.custom_stop['decay-start'] | |
| 328 | + end = self.custom_stop['decay-end'] | |
| 329 | + time = self.custom_stop['decay-time'] | |
| 330 | + delay = self.custom_stop['decay-delay'] | |
| 331 | + | |
| 332 | + open_minutes: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 333 | + | |
| 334 | + decay_stoploss = self.linear_growth(start, end, delay, time, open_minutes) | |
| 335 | + | |
| 336 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 337 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 338 | + profit_diff = current_profit - min_profit | |
| 339 | + | |
| 340 | + # if trade is positive, immediately move the stoploss up to 1% behind it | |
| 341 | + if current_profit > 0: | |
| 342 | + return current_profit - 0.01 | |
| 343 | + | |
| 344 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 345 | + if current_profit > min_profit: | |
| 346 | + if profit_diff > 0.015: | |
| 347 | + return min_profit | |
| 348 | + return -1 | |
| 349 | + | |
| 350 | + # otherwise return the time decaying stoploss | |
| 351 | + return decay_stoploss | |
| 352 | + | |
| 353 | + """ | |
| 354 | + Trade Timeout Overrides | |
| 355 | + """ | |
| 356 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 357 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 358 | + ob = self.dp.orderbook(pair, 1) | |
| 359 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 360 | + if current_price > order['price'] * 1.01: | |
| 361 | + return True | |
| 362 | + return False | |
| 363 | + | |
| 364 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 365 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 366 | + ob = self.dp.orderbook(pair, 1) | |
| 367 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 368 | + if current_price < order['price'] * 0.99: | |
| 369 | + return True | |
| 370 | + return False | |
| 371 | + | |
| 372 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 373 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 374 | + ob = self.dp.orderbook(pair, 1) | |
| 375 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 376 | + if current_price > rate * 1.01: | |
| 377 | + return False | |
| 378 | + return True | |
| 379 | + | |
| 380 | + """ | |
| 381 | + Freqtrade ROI Override for dynamic ROI functionality | |
| 382 | + """ | |
| 383 | + def min_roi_reached_dynamic(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 384 | + | |
| 385 | + dynamic_roi = self.dynamic_roi | |
| 386 | + minimal_roi = self.minimal_roi | |
| 387 | + | |
| 388 | + if not dynamic_roi: | |
| 389 | + return None, None | |
| 390 | + | |
| 391 | + if 'dynamic_roi_type' in dynamic_roi and dynamic_roi['dynamic_roi_type'] \ | |
| 392 | + in ['linear', 'exponential', 'connect']: | |
| 393 | + roi_type = dynamic_roi['dynamic_roi_type'] | |
| 394 | + # linear decay: f(t) = start - (rate * t) | |
| 395 | + if roi_type == 'linear': | |
| 396 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 397 | + 'dynamic_roi_time' in dynamic_roi: | |
| 398 | + start = dynamic_roi['dynamic_roi_start'] | |
| 399 | + end = dynamic_roi['dynamic_roi_end'] | |
| 400 | + time = dynamic_roi['dynamic_roi_time'] | |
| 401 | + rate = (start - end) / time | |
| 402 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 403 | + else: | |
| 404 | + return None, None | |
| 405 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 406 | + elif roi_type == 'exponential': | |
| 407 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 408 | + 'dynamic_roi_rate' in dynamic_roi: | |
| 409 | + start = dynamic_roi['dynamic_roi_start'] | |
| 410 | + end = dynamic_roi['dynamic_roi_end'] | |
| 411 | + rate = dynamic_roi['dynamic_roi_rate'] | |
| 412 | + min_roi = max(end, start * np.exp(-rate*trade_dur)) | |
| 413 | + else: | |
| 414 | + return None, None | |
| 415 | + # "connect the dots" between the points on the minima_roi table | |
| 416 | + elif roi_type == 'connect': | |
| 417 | + if not minimal_roi: | |
| 418 | + return None, None | |
| 419 | + # figure out where we are in the defined roi table | |
| 420 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 421 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 422 | + # if we are past the final point in the table, use that key/vaule pair | |
| 423 | + if not past_roi: | |
| 424 | + return None, None | |
| 425 | + current_entry = max(past_roi) | |
| 426 | + if not next_roi: | |
| 427 | + return current_entry, minimal_roi[current_entry] | |
| 428 | + next_entry = min(next_roi) | |
| 429 | + # use the slope-intercept formula between the two points | |
| 430 | + # y = mx + b | |
| 431 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 432 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 433 | + m = (y1-y2)/(x1-x2) | |
| 434 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 435 | + min_roi = (m * trade_dur) + b | |
| 436 | + else: | |
| 437 | + return None, None | |
| 438 | + | |
| 439 | + return trade_dur, min_roi | |
| 440 | + | |
| 441 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 442 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 443 | + | |
| 444 | + if self.dynamic_roi and 'dynamic_roi_enabled' in self.dynamic_roi \ | |
| 445 | + and self.dynamic_roi['dynamic_roi_enabled']: | |
| 446 | + _, roi = self.min_roi_reached_dynamic(trade_dur) | |
| 447 | + else: | |
| 448 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 449 | + if roi is None: | |
| 450 | + return False | |
| 451 | + else: | |
| 452 | + return current_profit > roi | |
| 453 | + | |
| 454 | + """ | |
| 455 | + Schism Custom Methods | |
| 456 | + """ | |
| 457 | + def populate_trades(self, pair: str) -> dict: | |
| 458 | + """ | |
| 459 | + Query the database and populate the custom_trade_info dict. | |
| 460 | + """ | |
| 461 | + if not pair in self.custom_trade_info: | |
| 462 | + self.custom_trade_info[pair] = {} | |
| 463 | + | |
| 464 | + trade_data = {} | |
| 465 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 466 | + | |
| 467 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 468 | + | |
| 469 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 470 | + | |
| 471 | + if active_trade: | |
| 472 | + current_rate = self.get_current_price(pair, True) | |
| 473 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 474 | + | |
| 475 | + present = arrow.utcnow() | |
| 476 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 477 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 478 | + | |
| 479 | + trade_data['active_trade'] = True | |
| 480 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 481 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 482 | + trade_data['open_minutes'] : int = open_minutes | |
| 483 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 484 | + else: | |
| 485 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 486 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 487 | + | |
| 488 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 489 | + | |
| 490 | + if other_trades: | |
| 491 | + trade_data['other_trades'] = True | |
| 492 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 493 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 494 | + if trade_data['current_profit'] < min(other_profit): | |
| 495 | + trade_data['biggest_loser'] = True | |
| 496 | + else: | |
| 497 | + trade_data['avg_other_profit'] = 0 | |
| 498 | + | |
| 499 | + open_trades = len(Trade.get_open_trades()) | |
| 500 | + # this was lazy. | |
| 501 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 502 | + | |
| 503 | + return trade_data | |
| 504 | + | |
| 505 | + | |
| 506 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 507 | + """ | |
| 508 | + Query the exchange for current price information, used in profit calculations. | |
| 509 | + Implements a cache to prevent excessive api calls. | |
| 510 | + """ | |
| 511 | + if not refresh: | |
| 512 | + rate = self.custom_current_price_cache.get(pair) | |
| 513 | + if rate: | |
| 514 | + return rate | |
| 515 | + | |
| 516 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 517 | + if ask_strategy.get('use_order_book', False): | |
| 518 | + ob = self.dp.orderbook(pair, 1) | |
| 519 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 520 | + else: | |
| 521 | + ticker = self.dp.ticker(pair) | |
| 522 | + rate = ticker['last'] | |
| 523 | + | |
| 524 | + self.custom_current_price_cache[pair] = rate | |
| 525 | + return rate | |
| 526 | + | |
| 527 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 528 | + """ | |
| 529 | + Simple linear growth function. Grows from start to end after end_time minutes (starts after start_time minutes) | |
| 530 | + """ | |
| 531 | + time = max(0, trade_time - start_time) | |
| 532 | + rate = (end - start) / (end_time - start_time) | |
| 533 | + return min(end, start + (rate * time)) | |
| 534 | + | |
| 535 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 536 | + """ | |
| 537 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 538 | + TODO: | |
| 539 | + - Make this function more robust so that one does not need to ever edit it. | |
| 540 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 541 | + """ | |
| 542 | + buy_params = self.buy_params | |
| 543 | + sell_params = self.sell_params | |
| 544 | + | |
| 545 | + ### Stake: USD | |
| 546 | + if pair in ('ABC/XYZ', 'DEF/XYZ'): | |
| 547 | + buy_params = self.buy_params_GROUP1 | |
| 548 | + sell_params = self.sell_params_GROUP1 | |
| 549 | + elif pair in ('QRD/WTF'): | |
| 550 | + buy_params = self.buy_params_QRD | |
| 551 | + sell_params = self.sell_params_QRD | |
| 552 | + | |
| 553 | + if side == 'sell': | |
| 554 | + return sell_params | |
| 555 | + | |
| 556 | + return buy_params | |
| 557 | + | |
| 558 | +# Sub-strategy with parameters specific to BTC stake | |
| 559 | +class Schism6_BTC(Schism6): | |
| 560 | + | |
| 561 | + timeframe = '1h' | |
| 562 | + inf_timeframe = '4h' | |
| 563 | + | |
| 564 | + buy_params = { | |
| 565 | + 'inf-rsi': 64, | |
| 566 | + 'mp': 55, | |
| 567 | + 'rmi-fast': 31, | |
| 568 | + 'rmi-slow': 16, | |
| 569 | + 'xinf-stake-rmi': 67, | |
| 570 | + 'xtf-fiat-rsi': 17, | |
| 571 | + 'xtf-stake-rsi': 57 | |
| 572 | + } | |
| 573 | + | |
| 574 | + minimal_roi = { | |
| 575 | + "0": 0.05, | |
| 576 | + "240": 0.025, | |
| 577 | + "1440": 0.01, | |
| 578 | + "4320": 0 | |
| 579 | + } | |
| 580 | + | |
| 581 | + stoploss = -0.30 | |
| 582 | + use_custom_stoploss = False | |
| 583 | + | |
| 584 | +# Sub-strategy with parameters specific to ETH stake | |
| 585 | +class Schism6_ETH(Schism6): | |
| 586 | + | |
| 587 | + timeframe = '1h' | |
| 588 | + inf_timeframe = '4h' | |
| 589 | + | |
| 590 | + buy_params = { | |
| 591 | + 'inf-rsi': 13, | |
| 592 | + 'inf-stake-rmi': 69, | |
| 593 | + 'mp': 40, | |
| 594 | + 'rmi-fast': 42, | |
| 595 | + 'rmi-slow': 17, | |
| 596 | + 'tf-fiat-rsi': 15, | |
| 597 | + 'tf-stake-rsi': 92 | |
| 598 | + } | |
| 599 | + | |
| 600 | + minimal_roi = { | |
| 601 | + "0": 0.05, | |
| 602 | + "240": 0.025, | |
| 603 | + "1440": 0.01, | |
| 604 | + "4320": 0 | |
| 605 | + } | |
| 606 | + | |
| 607 | + stoploss = -0.30 | |
| 608 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Schism-v1.py +341 −0
| @@ -0,0 +1,341 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI, VIDYA | |
| 12 | +from statistics import mean | |
| 13 | +from cachetools import TTLCache | |
| 14 | + | |
| 15 | + | |
| 16 | +""" | |
| 17 | +TODO: | |
| 18 | + - Better buy signal. | |
| 19 | + - Potentially leverage an external data source? | |
| 20 | + - Make stop-loss bailout a bit more intelligent (based on free slots, time passed, etc.) | |
| 21 | + - We're getting stuck in too many losing trades and it creates a domino effect. | |
| 22 | +""" | |
| 23 | + | |
| 24 | +class Schism(IStrategy): | |
| 25 | + | |
| 26 | + timeframe = '5m' | |
| 27 | + inf_timeframe = '1h' | |
| 28 | + | |
| 29 | + buy_params = {} | |
| 30 | + sell_params = {} | |
| 31 | + | |
| 32 | + # ROI table: | |
| 33 | + minimal_roi = { | |
| 34 | + "0": 0.05, | |
| 35 | + "10": 0.025, | |
| 36 | + "20": 0.015, | |
| 37 | + "30": 0.01 | |
| 38 | + } | |
| 39 | + | |
| 40 | + # Stoploss: | |
| 41 | + stoploss = -0.50 | |
| 42 | + | |
| 43 | + # Probably don't change these | |
| 44 | + use_sell_signal = True | |
| 45 | + sell_profit_only = False | |
| 46 | + ignore_roi_if_buy_signal = True | |
| 47 | + | |
| 48 | + startup_candle_count: int = 21 | |
| 49 | + | |
| 50 | + # Custom stored data, these are required. | |
| 51 | + custom_trade_info = {} | |
| 52 | + custom_fiat = "USD" | |
| 53 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 54 | + | |
| 55 | + def informative_pairs(self): | |
| 56 | + pairs = self.dp.current_whitelist() | |
| 57 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 58 | + | |
| 59 | + # add additional informative pairs based on certain stakes | |
| 60 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 61 | + for pair in pairs: | |
| 62 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) | |
| 63 | + coin, stake = pair.split('/') | |
| 64 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 65 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 66 | + | |
| 67 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) | |
| 68 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 69 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 70 | + | |
| 71 | + return informative_pairs | |
| 72 | + | |
| 73 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 74 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 75 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 76 | + | |
| 77 | + # Set up primary indicators | |
| 78 | + dataframe['rmi-slow'] = RMI(dataframe, length=20, mom=5) | |
| 79 | + dataframe['rmi-fast'] = RMI(dataframe, length=9, mom=3) | |
| 80 | + dataframe['vidya'] = VIDYA(dataframe) | |
| 81 | + | |
| 82 | + macd = ta.MACD(dataframe, fastperiod=12, slowperiod=26, signalperiod=9) | |
| 83 | + dataframe['macd'] = macd['macd'] | |
| 84 | + dataframe['macdsignal'] = macd['macdsignal'] | |
| 85 | + dataframe['macdhist'] = macd['macdhist'] | |
| 86 | + | |
| 87 | + dataframe['kama-fast'] = ta.KAMA(dataframe, timeperiod=5) | |
| 88 | + dataframe['kama-slow'] = ta.KAMA(dataframe, timeperiod=13) | |
| 89 | + | |
| 90 | + # Trend Calculations | |
| 91 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 92 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 93 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 94 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 95 | + | |
| 96 | + dataframe['vdy-up'] = np.where(dataframe['vidya'] >= dataframe['vidya'].shift(),1,0) | |
| 97 | + dataframe['vdy-dn'] = np.where(dataframe['vidya'] <= dataframe['vidya'].shift(),1,0) | |
| 98 | + dataframe['vdy-up-trend'] = np.where(dataframe['vdy-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 99 | + dataframe['vdy-dn-trend'] = np.where(dataframe['vdy-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 100 | + | |
| 101 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 102 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 103 | + coin, stake = metadata['pair'].split('/') | |
| 104 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 105 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 106 | + | |
| 107 | + coin_fiat_inf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 108 | + stake_fiat_inf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 109 | + | |
| 110 | + dataframe[f"{self.custom_fiat}_rmi-slow"] = RMI(coin_fiat_inf, length=20, mom=5) | |
| 111 | + dataframe[f"{self.config['stake_currency']}_rmi-slow"] = RMI(stake_fiat_inf, length=20, mom=5) | |
| 112 | + | |
| 113 | + # Informative for current pair on inf_timeframe | |
| 114 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 115 | + | |
| 116 | + inf_macd = ta.MACD(informative, fastperiod=12, slowperiod=26, signalperiod=9) | |
| 117 | + informative['macd'] = inf_macd['macd'] | |
| 118 | + informative['macdsignal'] = inf_macd['macdsignal'] | |
| 119 | + informative['macdhist'] = inf_macd['macdhist'] | |
| 120 | + | |
| 121 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 122 | + | |
| 123 | + return dataframe | |
| 124 | + | |
| 125 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 126 | + params = self.buy_params | |
| 127 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 128 | + conditions = [] | |
| 129 | + | |
| 130 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 131 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 132 | + if trade_data['active_trade']: | |
| 133 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * (dataframe['rmi-slow'] / 105))) | |
| 134 | + conditions.append(dataframe['rmi-slow'] >= 50) | |
| 135 | + | |
| 136 | + # Normal buy triggers that apply to new trades we want to enter | |
| 137 | + else: | |
| 138 | + # If the stake is BTC or ETH apply an additional condition | |
| 139 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 140 | + conditions.append( | |
| 141 | + (dataframe[f"{self.config['stake_currency']}_rmi-slow"] < 50) | | |
| 142 | + (dataframe[f"{self.custom_fiat}_rmi-slow"] > 40) | |
| 143 | + ) | |
| 144 | + | |
| 145 | + conditions.append( | |
| 146 | + # informative timeframe conditions | |
| 147 | + (dataframe[f"macd_{self.inf_timeframe}"] > dataframe[f"macdsignal_{self.inf_timeframe}"]) & | |
| 148 | + | |
| 149 | + # default timeframe conditions | |
| 150 | + (dataframe['rmi-up-trend'] == 1) & | |
| 151 | + (dataframe['vdy-up-trend'] == 1) & | |
| 152 | + (dataframe['macd'] > dataframe['macdsignal']) & | |
| 153 | + (dataframe['open'] > dataframe['kama-fast']) & | |
| 154 | + (dataframe['close'] > dataframe['kama-slow']) | |
| 155 | + ) | |
| 156 | + | |
| 157 | + # applies to both new buys and persisting buy signal | |
| 158 | + conditions.append(dataframe['volume'].gt(0)) | |
| 159 | + | |
| 160 | + if conditions: | |
| 161 | + dataframe.loc[ | |
| 162 | + reduce(lambda x, y: x & y, conditions), | |
| 163 | + 'buy'] = 1 | |
| 164 | + | |
| 165 | + return dataframe | |
| 166 | + | |
| 167 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 168 | + params = self.sell_params | |
| 169 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 170 | + conditions = [] | |
| 171 | + | |
| 172 | + # In this strategy all sells for profit happen according to ROI | |
| 173 | + # This sell signal is designed as a "dynamic stoploss" | |
| 174 | + | |
| 175 | + # if we are in an active trade for this pair | |
| 176 | + if trade_data['active_trade']: | |
| 177 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 178 | + conditions.append( | |
| 179 | + (trade_data['current_profit'] < 0) & | |
| 180 | + (trade_data['current_profit'] > self.stoploss) & | |
| 181 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 182 | + (qtpylib.crossed_below(dataframe['rmi-fast'], 50)) & | |
| 183 | + (dataframe['volume'].gt(0)) | |
| 184 | + ) | |
| 185 | + | |
| 186 | + # if there are other open trades in addition to this one, consider the average profit | |
| 187 | + # across them all (not including this one), don't sell if entire market is down big and wait for recovery | |
| 188 | + if trade_data['other_trades']: | |
| 189 | + if trade_data['free_slots'] == 0: | |
| 190 | + conditions.append(trade_data['avg_other_profit'] >= -0.03) | |
| 191 | + else: | |
| 192 | + conditions.append(trade_data['avg_other_profit'] >= -0.01) | |
| 193 | + | |
| 194 | + # the bot comes through this loop even when there isn't an open trade to sell | |
| 195 | + # so we pass an impossible condiiton here because we don't want a sell signal | |
| 196 | + # clogging up the charts and not having one leads the bot to crash | |
| 197 | + else: | |
| 198 | + conditions.append(dataframe['volume'].lt(0)) | |
| 199 | + | |
| 200 | + if conditions: | |
| 201 | + dataframe.loc[ | |
| 202 | + reduce(lambda x, y: x & y, conditions), | |
| 203 | + 'sell'] = 1 | |
| 204 | + | |
| 205 | + return dataframe | |
| 206 | + | |
| 207 | + """ | |
| 208 | + Super Legit Custom Methods | |
| 209 | + """ | |
| 210 | + # Populate trades_data from the database | |
| 211 | + def populate_trades(self, pair: str) -> dict: | |
| 212 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 213 | + if not pair in self.custom_trade_info: | |
| 214 | + self.custom_trade_info[pair] = {} | |
| 215 | + | |
| 216 | + # init the temp dicts and set the trade stuff to false | |
| 217 | + trade_data = {} | |
| 218 | + trade_data['active_trade'] = trade_data['other_trades'] = False | |
| 219 | + | |
| 220 | + # active trade stuff only really works in live and dry, not backtest | |
| 221 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 222 | + | |
| 223 | + # find out if we have an open trade for this pair | |
| 224 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 225 | + | |
| 226 | + # if so, get some information | |
| 227 | + if active_trade: | |
| 228 | + # get current price and update the min/max rate | |
| 229 | + current_rate = self.get_current_price(pair, True) | |
| 230 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 231 | + | |
| 232 | + # get how long the trade has been open in minutes and candles | |
| 233 | + present = arrow.utcnow() | |
| 234 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 235 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 236 | + | |
| 237 | + # set up the things we use in the strategy | |
| 238 | + trade_data['active_trade'] = True | |
| 239 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 240 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 241 | + trade_data['open_minutes'] : int = open_minutes | |
| 242 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 243 | + else: | |
| 244 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 245 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 246 | + | |
| 247 | + # if there are open trades not including the current pair, get some information | |
| 248 | + # future reference, for all open trades: open_trades = Trade.get_open_trades() | |
| 249 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 250 | + | |
| 251 | + if other_trades: | |
| 252 | + trade_data['other_trades'] = True | |
| 253 | + total_other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 254 | + trade_data['avg_other_profit'] = mean(total_other_profit) | |
| 255 | + else: | |
| 256 | + trade_data['avg_other_profit'] = 0 | |
| 257 | + | |
| 258 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 259 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - (len(active_trade) + len(other_trades))) | |
| 260 | + | |
| 261 | + return trade_data | |
| 262 | + | |
| 263 | + # Get the current price from the exchange (or cache) | |
| 264 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 265 | + if not refresh: | |
| 266 | + rate = self.custom_current_price_cache.get(pair) | |
| 267 | + # Check if cache has been invalidated | |
| 268 | + if rate: | |
| 269 | + return rate | |
| 270 | + | |
| 271 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 272 | + if ask_strategy.get('use_order_book', False): | |
| 273 | + ob = self.dp.orderbook(pair, 1) | |
| 274 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 275 | + else: | |
| 276 | + ticker = self.dp.ticker(pair) | |
| 277 | + rate = ticker['last'] | |
| 278 | + | |
| 279 | + self.custom_current_price_cache[pair] = rate | |
| 280 | + return rate | |
| 281 | + | |
| 282 | + | |
| 283 | + """ | |
| 284 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 285 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 286 | + """ | |
| 287 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 288 | + ob = self.dp.orderbook(pair, 1) | |
| 289 | + current_price = ob['bids'][0][0] | |
| 290 | + # Cancel buy order if price is more than 1% above the order. | |
| 291 | + if current_price > order['price'] * 1.01: | |
| 292 | + return True | |
| 293 | + return False | |
| 294 | + | |
| 295 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 296 | + ob = self.dp.orderbook(pair, 1) | |
| 297 | + current_price = ob['asks'][0][0] | |
| 298 | + # Cancel sell order if price is more than 1% below the order. | |
| 299 | + if current_price < order['price'] * 0.99: | |
| 300 | + return True | |
| 301 | + return False | |
| 302 | + | |
| 303 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 304 | + ob = self.dp.orderbook(pair, 1) | |
| 305 | + current_price = ob['asks'][0][0] | |
| 306 | + # Cancel buy order if price is more than 1% above the order. | |
| 307 | + if current_price > rate * 1.01: | |
| 308 | + return False | |
| 309 | + return True | |
| 310 | + | |
| 311 | + | |
| 312 | +""" | |
| 313 | +Sub-strategy overrides | |
| 314 | +""" | |
| 315 | +# Sub-strategy with parameters specific to BTC stake | |
| 316 | +class Schism_BTC(Schism): | |
| 317 | + | |
| 318 | + timeframe = '5m' | |
| 319 | + inf_timeframe = '1h' | |
| 320 | + | |
| 321 | + # ROI table: | |
| 322 | + minimal_roi = { | |
| 323 | + "0": 0.05, | |
| 324 | + "10": 0.025, | |
| 325 | + "20": 0.015, | |
| 326 | + "30": 0.01 | |
| 327 | + } | |
| 328 | + | |
| 329 | +# Sub-strategy with parameters specific to ETH stake | |
| 330 | +class Schism_ETH(Schism): | |
| 331 | + | |
| 332 | + timeframe = '5m' | |
| 333 | + inf_timeframe = '1h' | |
| 334 | + | |
| 335 | + # ROI table: | |
| 336 | + minimal_roi = { | |
| 337 | + "0": 0.05, | |
| 338 | + "10": 0.025, | |
| 339 | + "20": 0.015, | |
| 340 | + "30": 0.01 | |
| 341 | + } |
added strategies/old/Schism-v2.py +486 −0
| @@ -0,0 +1,486 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | +""" | |
| 18 | +Solipsis - By @werkkrew and @JimmyNixx | |
| 19 | +This strategy is an evolution of our previous framework "Schism" which we are happy to share by request. | |
| 20 | + | |
| 21 | +FEATURES: | |
| 22 | + - Sticking buy signal for extending ROI | |
| 23 | + - Idea is to use a completely different buy signal for active trades to force the "ignore_roi_if_buy_signal = True" setting to stop a sell to ROI | |
| 24 | + during a strong upward trend. | |
| 25 | + - This is not compatible with backtest or hyperopt and can only be tested in dry-run or live. | |
| 26 | + - Dynamic Sell | |
| 27 | + - Emulates a pre-stoploss bailout when market conditions meet specific criteria, including looking at profit factors, other trade status, etc. | |
| 28 | + - Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 29 | + - If your stake is BTC or ETH, use COIN/FIAT and BTC/FIAT as informatives. | |
| 30 | + - Full access to current trade and other trade data within buy and sell methods to use in decisions, this is not compatible with backtesting. | |
| 31 | + - 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. | |
| 32 | + - Stub Child strategies for stake specific settings and different settings for different instances. | |
| 33 | + | |
| 34 | +TODO: | |
| 35 | + - Continue to hunt for a better all around buy signal. | |
| 36 | + - Tweak ROI Ride | |
| 37 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 38 | + - Tweak sell signal | |
| 39 | + - Continue to evaluate good circumstances to sell vs hold | |
| 40 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 41 | + - Per-pair automatic ROI based on ADR or something similar? | |
| 42 | +""" | |
| 43 | + | |
| 44 | +class Schism2(IStrategy): | |
| 45 | + """ | |
| 46 | + Strategy Configuration Items | |
| 47 | + """ | |
| 48 | + timeframe = '5m' | |
| 49 | + inf_timeframe = '1h' | |
| 50 | + | |
| 51 | + buy_params = { | |
| 52 | + 'inf-pct-adr': 0.83534, | |
| 53 | + 'inf-rsi': 57, | |
| 54 | + 'mp': 64, | |
| 55 | + 'rmi-fast': 49, | |
| 56 | + 'rmi-slow': 24, | |
| 57 | + 'xinf-stake-rmi': 45, | |
| 58 | + 'xtf-fiat-rsi': 28, | |
| 59 | + 'xtf-stake-rsi': 90 | |
| 60 | + } | |
| 61 | + | |
| 62 | + sell_params = {} | |
| 63 | + | |
| 64 | + minimal_roi = { | |
| 65 | + "0": 0.05, | |
| 66 | + "10": 0.025, | |
| 67 | + "20": 0.015, | |
| 68 | + "30": 0.01, | |
| 69 | + "720": 0.005, | |
| 70 | + "1440": 0 | |
| 71 | + } | |
| 72 | + | |
| 73 | + custom_pair_params = [] | |
| 74 | + | |
| 75 | + stoploss = -0.30 | |
| 76 | + | |
| 77 | + # Recommended | |
| 78 | + use_sell_signal = True | |
| 79 | + sell_profit_only = False | |
| 80 | + ignore_roi_if_buy_signal = True | |
| 81 | + | |
| 82 | + startup_candle_count: int = 72 | |
| 83 | + | |
| 84 | + # Startegy Specific Variable Storage | |
| 85 | + custom_trade_info = {} | |
| 86 | + custom_fiat = "USD" | |
| 87 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 88 | + | |
| 89 | + """ | |
| 90 | + Informative Pair Definitions | |
| 91 | + """ | |
| 92 | + def informative_pairs(self): | |
| 93 | + # add existing pairs from whitelist on the inf_timeframe | |
| 94 | + pairs = self.dp.current_whitelist() | |
| 95 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 96 | + | |
| 97 | + # add additional informative pairs based on certain stakes | |
| 98 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 99 | + for pair in pairs: | |
| 100 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) on base timeframe | |
| 101 | + coin, stake = pair.split('/') | |
| 102 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 103 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 104 | + | |
| 105 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) on base and inf timeframes | |
| 106 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 107 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 108 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 109 | + | |
| 110 | + return informative_pairs | |
| 111 | + | |
| 112 | + """ | |
| 113 | + Indicator Definitions | |
| 114 | + """ | |
| 115 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 117 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 118 | + | |
| 119 | + # Set up primary indicators | |
| 120 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 121 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 122 | + | |
| 123 | + # Momentum Pinball | |
| 124 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 125 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 126 | + | |
| 127 | + # Trend Calculations | |
| 128 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 129 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 130 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 131 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 132 | + | |
| 133 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 134 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 135 | + coin, stake = metadata['pair'].split('/') | |
| 136 | + fiat = self.custom_fiat | |
| 137 | + coin_fiat = f"{coin}/{fiat}" | |
| 138 | + stake_fiat = f"{stake}/{fiat}" | |
| 139 | + | |
| 140 | + # COIN/FIAT (e.g. XLM/USD) - timeframe | |
| 141 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 142 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 143 | + | |
| 144 | + # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe | |
| 145 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 146 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 147 | + | |
| 148 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 149 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 150 | + | |
| 151 | + # Informative indicators for current pair on inf_timeframe | |
| 152 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 153 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 154 | + | |
| 155 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 156 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 157 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 158 | + | |
| 159 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 160 | + | |
| 161 | + return dataframe | |
| 162 | + | |
| 163 | + """ | |
| 164 | + Buy Trigger Signals | |
| 165 | + """ | |
| 166 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 167 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 168 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 169 | + conditions = [] | |
| 170 | + | |
| 171 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 172 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 173 | + if trade_data['active_trade']: | |
| 174 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 175 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 176 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 177 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 178 | + | |
| 179 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 180 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 181 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 182 | + | |
| 183 | + # Normal buy triggers that apply to new trades we want to enter | |
| 184 | + else: | |
| 185 | + # Primary buy triggers | |
| 186 | + conditions.append( | |
| 187 | + # "buy the dip" based buy signal using momentum pinball and downward RMI | |
| 188 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{self.inf_timeframe}"])) & | |
| 189 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 190 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 191 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 192 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 193 | + (dataframe['mp'] <= params['mp']) | |
| 194 | + ) | |
| 195 | + | |
| 196 | + # If the stake is BTC or ETH apply additional conditions | |
| 197 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 198 | + # default timeframe conditions | |
| 199 | + conditions.append( | |
| 200 | + (dataframe[f"{self.config['stake_currency']}_rsi"] < params['xtf-stake-rsi']) | | |
| 201 | + (dataframe[f"{self.custom_fiat}_rsi"] > params['xtf-fiat-rsi']) | |
| 202 | + ) | |
| 203 | + # informative timeframe conditions | |
| 204 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 205 | + | |
| 206 | + # Anything below here applies to persisting and new buy signal | |
| 207 | + conditions.append(dataframe['volume'].gt(0)) | |
| 208 | + | |
| 209 | + if conditions: | |
| 210 | + dataframe.loc[ | |
| 211 | + reduce(lambda x, y: x & y, conditions), | |
| 212 | + 'buy'] = 1 | |
| 213 | + | |
| 214 | + return dataframe | |
| 215 | + | |
| 216 | + """ | |
| 217 | + Sell Trigger Signals | |
| 218 | + """ | |
| 219 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 220 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 221 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 222 | + conditions = [] | |
| 223 | + | |
| 224 | + # In this strategy all sells for profit happen according to ROI | |
| 225 | + # This sell signal is designed only as a "dynamic stoploss" | |
| 226 | + | |
| 227 | + # if we are in an active trade for this pair | |
| 228 | + if trade_data['active_trade']: | |
| 229 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 230 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 231 | + | |
| 232 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 233 | + conditions.append( | |
| 234 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 235 | + (trade_data['current_profit'] > self.stoploss) & | |
| 236 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 237 | + (dataframe['volume'].gt(0)) | |
| 238 | + ) | |
| 239 | + | |
| 240 | + # if the peak profit was positive at some point but never reached ROI, set a higher cross point for exit | |
| 241 | + if trade_data['peak_profit'] > 0: | |
| 242 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 50)) | |
| 243 | + # if the trade was always negative, the bounce we expected didn't happen | |
| 244 | + else: | |
| 245 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 10)) | |
| 246 | + | |
| 247 | + # if there are other open trades in addition to this one, consider the average profit | |
| 248 | + # across them all and how many free slots we have in our sell decision | |
| 249 | + if trade_data['other_trades']: | |
| 250 | + if trade_data['free_slots'] > 0: | |
| 251 | + """ | |
| 252 | + Less free slots, more willing to sell | |
| 253 | + 1 / free_slots * x = | |
| 254 | + 1 slot = 1/1 * -0.04 = -0.04 -> only allow sells if avg_other_proift above -0.04 | |
| 255 | + 4 slot = 1/4 * -0.04 = -0.01 -> only allow sells is avg_other_profit above -0.01 | |
| 256 | + """ | |
| 257 | + max_market_down = -0.04 | |
| 258 | + hold_pct = (1/trade_data['free_slots']) * max_market_down | |
| 259 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 260 | + else: | |
| 261 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 262 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 263 | + | |
| 264 | + # Impossible condition to satisfy the bot when it looks here and theres no active trade | |
| 265 | + else: | |
| 266 | + conditions.append(dataframe['volume'].lt(0)) | |
| 267 | + | |
| 268 | + if conditions: | |
| 269 | + dataframe.loc[ | |
| 270 | + reduce(lambda x, y: x & y, conditions), | |
| 271 | + 'sell'] = 1 | |
| 272 | + | |
| 273 | + return dataframe | |
| 274 | + | |
| 275 | + """ | |
| 276 | + Super Legit Custom Methods | |
| 277 | + """ | |
| 278 | + # Populate trades_data from the database | |
| 279 | + def populate_trades(self, pair: str) -> dict: | |
| 280 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 281 | + if not pair in self.custom_trade_info: | |
| 282 | + self.custom_trade_info[pair] = {} | |
| 283 | + | |
| 284 | + # init the temp dicts and set the trade stuff to false | |
| 285 | + trade_data = {} | |
| 286 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 287 | + | |
| 288 | + # active trade stuff only works in live and dry, not backtest | |
| 289 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 290 | + | |
| 291 | + # find out if we have an open trade for this pair | |
| 292 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 293 | + | |
| 294 | + # if so, get some information | |
| 295 | + if active_trade: | |
| 296 | + # get current price and update the min/max rate | |
| 297 | + current_rate = self.get_current_price(pair, True) | |
| 298 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 299 | + | |
| 300 | + # get how long the trade has been open in minutes and candles | |
| 301 | + present = arrow.utcnow() | |
| 302 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 303 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 304 | + | |
| 305 | + # set up the things we use in the strategy | |
| 306 | + trade_data['active_trade'] = True | |
| 307 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 308 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 309 | + trade_data['open_minutes'] : int = open_minutes | |
| 310 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 311 | + else: | |
| 312 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 313 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 314 | + | |
| 315 | + # if there are open trades not including the current pair, get some information | |
| 316 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 317 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 318 | + | |
| 319 | + if other_trades: | |
| 320 | + trade_data['other_trades'] = True | |
| 321 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 322 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 323 | + # find which of our trades is the biggest loser | |
| 324 | + if trade_data['current_profit'] < min(other_profit): | |
| 325 | + trade_data['biggest_loser'] = True | |
| 326 | + else: | |
| 327 | + trade_data['avg_other_profit'] = 0 | |
| 328 | + | |
| 329 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 330 | + open_trades = len(Trade.get_open_trades()) | |
| 331 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 332 | + | |
| 333 | + return trade_data | |
| 334 | + | |
| 335 | + # Get the current price from the exchange (or cache) | |
| 336 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 337 | + if not refresh: | |
| 338 | + rate = self.custom_current_price_cache.get(pair) | |
| 339 | + # Check if cache has been invalidated | |
| 340 | + if rate: | |
| 341 | + return rate | |
| 342 | + | |
| 343 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 344 | + if ask_strategy.get('use_order_book', False): | |
| 345 | + ob = self.dp.orderbook(pair, 1) | |
| 346 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 347 | + else: | |
| 348 | + ticker = self.dp.ticker(pair) | |
| 349 | + rate = ticker['last'] | |
| 350 | + | |
| 351 | + self.custom_current_price_cache[pair] = rate | |
| 352 | + return rate | |
| 353 | + | |
| 354 | + # linear growth, starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 355 | + # f(t) = X + (rate * t), where rate = (Y - X) / (A - B) | |
| 356 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 357 | + time = max(0, trade_time - start_time) | |
| 358 | + rate = (end - start) / (end_time - start_time) | |
| 359 | + return min(end, start + (rate * time)) | |
| 360 | + | |
| 361 | + """ | |
| 362 | + Allow for buy/sell override parameters per pair. Testing, might remove. | |
| 363 | + """ | |
| 364 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 365 | + buy_params = self.buy_params | |
| 366 | + sell_params = self.sell_params | |
| 367 | + minimal_roi = self.minimal_roi | |
| 368 | + | |
| 369 | + if self.custom_pair_params: | |
| 370 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 371 | + if custom_params['buy_params']: | |
| 372 | + buy_params = custom_params['buy_params'] | |
| 373 | + if custom_params['sell_params']: | |
| 374 | + sell_params = custom_params['sell_params'] | |
| 375 | + if custom_params['minimal_roi']: | |
| 376 | + custom_stop = custom_params['minimal_roi'] | |
| 377 | + | |
| 378 | + if params == 'buy': | |
| 379 | + return buy_params | |
| 380 | + if params == 'sell': | |
| 381 | + return sell_params | |
| 382 | + if params == 'minimal_roi': | |
| 383 | + return minimal_roi | |
| 384 | + | |
| 385 | + """ | |
| 386 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 387 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 388 | + """ | |
| 389 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 390 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 391 | + ob = self.dp.orderbook(pair, 1) | |
| 392 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 393 | + # Cancel buy order if price is more than 1% above the order. | |
| 394 | + if current_price > order['price'] * 1.01: | |
| 395 | + return True | |
| 396 | + return False | |
| 397 | + | |
| 398 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 399 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 400 | + ob = self.dp.orderbook(pair, 1) | |
| 401 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 402 | + # Cancel sell order if price is more than 1% below the order. | |
| 403 | + if current_price < order['price'] * 0.99: | |
| 404 | + return True | |
| 405 | + return False | |
| 406 | + | |
| 407 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 408 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 409 | + ob = self.dp.orderbook(pair, 1) | |
| 410 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 411 | + # Cancel buy order if price is more than 1% above the order. | |
| 412 | + if current_price > rate * 1.01: | |
| 413 | + return False | |
| 414 | + return True | |
| 415 | + | |
| 416 | + """ | |
| 417 | + ROI overrides for per-pair params | |
| 418 | + """ | |
| 419 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 420 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 421 | + | |
| 422 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 423 | + if not roi_list: | |
| 424 | + return None, None | |
| 425 | + roi_entry = max(roi_list) | |
| 426 | + | |
| 427 | + return roi_entry, minimal_roi[roi_entry] | |
| 428 | + | |
| 429 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 430 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 431 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 432 | + if roi is None: | |
| 433 | + return False | |
| 434 | + else: | |
| 435 | + return current_profit > roi | |
| 436 | + | |
| 437 | +""" | |
| 438 | +Sub-strategy overrides | |
| 439 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 440 | +""" | |
| 441 | +# Sub-strategy with parameters specific to BTC stake | |
| 442 | +class Schism2_BTC(Schism2): | |
| 443 | + | |
| 444 | + timeframe = '15m' | |
| 445 | + inf_timeframe = '1h' | |
| 446 | + | |
| 447 | + minimal_roi = { | |
| 448 | + "0": 0.05, | |
| 449 | + "30": 0.025, | |
| 450 | + "60": 0.015, | |
| 451 | + "90": 0.01, | |
| 452 | + "1440": 0.005, | |
| 453 | + "2880": 0 | |
| 454 | + } | |
| 455 | + | |
| 456 | + buy_params = { | |
| 457 | + 'inf-pct-adr': 0.80616, | |
| 458 | + 'inf-rsi': 14, | |
| 459 | + 'mp': 43, | |
| 460 | + 'rmi-fast': 33, | |
| 461 | + 'rmi-slow': 16, | |
| 462 | + 'xinf-stake-rmi': 29, | |
| 463 | + 'xtf-fiat-rsi': 49, | |
| 464 | + 'xtf-stake-rsi': 53 | |
| 465 | + } | |
| 466 | + | |
| 467 | + use_sell_signal = False | |
| 468 | + | |
| 469 | +# Sub-strategy with parameters specific to ETH stake | |
| 470 | +class Schism2_ETH(Schism2): | |
| 471 | + | |
| 472 | + timeframe = '5m' | |
| 473 | + inf_timeframe = '1h' | |
| 474 | + | |
| 475 | + buy_params = { | |
| 476 | + 'inf-pct-adr': 0.81628, | |
| 477 | + 'inf-rsi': 13, | |
| 478 | + 'xinf-stake-rmi': 69, | |
| 479 | + 'mp': 40, | |
| 480 | + 'rmi-fast': 42, | |
| 481 | + 'rmi-slow': 17, | |
| 482 | + 'xtf-fiat-rsi': 15, | |
| 483 | + 'xtf-stake-rsi': 92 | |
| 484 | + } | |
| 485 | + | |
| 486 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Schism.py +474 −0
| @@ -0,0 +1,474 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | +""" | |
| 18 | +TODO: | |
| 19 | + | |
| 20 | +""" | |
| 21 | + | |
| 22 | +class Schism(IStrategy): | |
| 23 | + """ | |
| 24 | + Strategy Configuration Items | |
| 25 | + """ | |
| 26 | + | |
| 27 | + # Global Buy/Sell Params | |
| 28 | + buy_params = { | |
| 29 | + 'bounce-lookback': 5, | |
| 30 | + 'down-inf-rsi': 64, | |
| 31 | + 'down-mp': 55, | |
| 32 | + 'down-rmi-fast': 31, | |
| 33 | + 'down-rmi-slow': 16, | |
| 34 | + 'up-inf-rsi': 64, | |
| 35 | + 'up-rmi-fast': 31, | |
| 36 | + 'up-rmi-slow': 16, | |
| 37 | + 'xinf-stake-rmi': 67, | |
| 38 | + 'xtf-fiat-rsi': 17, | |
| 39 | + 'xtf-stake-rsi': 57 | |
| 40 | + } | |
| 41 | + | |
| 42 | + sell_params = { | |
| 43 | + 'rmi-high': 50, | |
| 44 | + 'rmi-low': 10 | |
| 45 | + } | |
| 46 | + | |
| 47 | + # Pair Specific Buy/Sell Params | |
| 48 | + buy_params_FOO = {} | |
| 49 | + sell_params_FOO = {} | |
| 50 | + | |
| 51 | + | |
| 52 | + # Other Global Settings | |
| 53 | + timeframe = '5m' | |
| 54 | + inf_timeframe = '1h' | |
| 55 | + | |
| 56 | + minimal_roi = { | |
| 57 | + "0": 0.10, | |
| 58 | + "10": 0.05, | |
| 59 | + "30": 0.025, | |
| 60 | + "60": 0.01, | |
| 61 | + "1440": 0 | |
| 62 | + } | |
| 63 | + | |
| 64 | + stoploss = -0.30 | |
| 65 | + | |
| 66 | + use_sell_signal = False | |
| 67 | + sell_profit_only = False | |
| 68 | + ignore_roi_if_buy_signal = True | |
| 69 | + | |
| 70 | + startup_candle_count: int = 72 | |
| 71 | + | |
| 72 | + # Startegy Specific Variable Storage | |
| 73 | + custom_trade_info = {} | |
| 74 | + custom_fiat = "USD" | |
| 75 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 76 | + | |
| 77 | + """ | |
| 78 | + Informative Pair Definitions | |
| 79 | + """ | |
| 80 | + def informative_pairs(self): | |
| 81 | + # add existing pairs from whitelist on the inf_timeframe | |
| 82 | + pairs = self.dp.current_whitelist() | |
| 83 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 84 | + | |
| 85 | + """ | |
| 86 | + # add additional informative pairs based on certain stakes | |
| 87 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 88 | + for pair in pairs: | |
| 89 | + # add in the COIN/FIAT pairs (e.g. XLM/USD) on base timeframe | |
| 90 | + coin, stake = pair.split('/') | |
| 91 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 92 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 93 | + | |
| 94 | + # add in the STAKE/FIAT pair (e.g. BTC/USD) on base and inf timeframes | |
| 95 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 96 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 97 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 98 | + """ | |
| 99 | + | |
| 100 | + return informative_pairs | |
| 101 | + | |
| 102 | + """ | |
| 103 | + Indicator Definitions | |
| 104 | + """ | |
| 105 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 106 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 107 | + | |
| 108 | + # Relative Momentum Index | |
| 109 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 110 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 111 | + | |
| 112 | + # Momentum Pinball | |
| 113 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 114 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 115 | + | |
| 116 | + # Trend Calculations | |
| 117 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 118 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 119 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 120 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 121 | + | |
| 122 | + """ | |
| 123 | + # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH | |
| 124 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 125 | + coin, stake = metadata['pair'].split('/') | |
| 126 | + fiat = self.custom_fiat | |
| 127 | + coin_fiat = f"{coin}/{fiat}" | |
| 128 | + stake_fiat = f"{stake}/{fiat}" | |
| 129 | + | |
| 130 | + # COIN/FIAT (e.g. XLM/USD) - timeframe | |
| 131 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 132 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 133 | + | |
| 134 | + # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe | |
| 135 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 136 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 137 | + | |
| 138 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 139 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 140 | + """ | |
| 141 | + | |
| 142 | + # Informative indicators for current pair on inf_timeframe | |
| 143 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 144 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 145 | + | |
| 146 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 147 | + | |
| 148 | + return dataframe | |
| 149 | + | |
| 150 | + """ | |
| 151 | + Buy Trigger Signals | |
| 152 | + """ | |
| 153 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 154 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 155 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 156 | + conditions = [] | |
| 157 | + | |
| 158 | + # Set up a pre-buy condition that we sort of "cache" | |
| 159 | + dataframe['bounce-pending'] = np.where( | |
| 160 | + (dataframe[f"rsi_{self.inf_timeframe}"] < params['down-inf-rsi']) & | |
| 161 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 162 | + (dataframe['rmi-slow'] > params['down-rmi-slow']) & | |
| 163 | + (dataframe['rmi-fast'] < params['down-rmi-fast']) & | |
| 164 | + (dataframe['mp'] <= params['down-mp']), | |
| 165 | + 1,0 | |
| 166 | + ) | |
| 167 | + | |
| 168 | + # Capture the price where we got the signal that a bounce would happen | |
| 169 | + dataframe['bounce-price'] = np.where( | |
| 170 | + dataframe['bounce-pending'] == 1, | |
| 171 | + dataframe['close'], | |
| 172 | + dataframe['close'].rolling(params['bounce-lookback'], min_periods=1).func() # 4 min/max/mean? | |
| 173 | + ) | |
| 174 | + | |
| 175 | + # Count how many times our pre-bounce happned in the last X candles | |
| 176 | + dataframe['bounce-range'] = np.where(dataframe['bounce-pending'].rolling(params['bounce-lookback'], min_periods=1).sum() >= 1,1,0) | |
| 177 | + | |
| 178 | + # Persist a buy signal for existing trades to make use of ignore_roi_if_buy_signal = True | |
| 179 | + # when this buy signal is not present a sell can happen according to the defined ROI table | |
| 180 | + if trade_data['active_trade']: | |
| 181 | + # peak_profit factor f(x)=1-x/400, rmi 30 -> 0.925, rmi 80 -> 0.80 | |
| 182 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 183 | + # grow from 30 -> 70 after 720 minutes starting after 180 minutes | |
| 184 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 185 | + | |
| 186 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 187 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 188 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 189 | + | |
| 190 | + # Normal buy triggers that apply to new trades we want to enter | |
| 191 | + else: | |
| 192 | + # Primary buy triggers | |
| 193 | + conditions.append( | |
| 194 | + (dataframe[f"rsi_{self.inf_timeframe}"] > params['up-inf-rsi']) & | |
| 195 | + (dataframe['bounce-range'] == 1) & | |
| 196 | + (dataframe['rmi-up-trend'] == 1) & | |
| 197 | + # 3(dataframe['rmi-slow'] < params['up-rmi-slow']) & | |
| 198 | + # 3(dataframe['rmi-fast'] > params['up-rmi-fast']) & | |
| 199 | + (dataframe['close'] > dataframe['bounce-price']) | |
| 200 | + ) | |
| 201 | + | |
| 202 | + """ | |
| 203 | + # If the stake is BTC or ETH apply additional conditions | |
| 204 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 205 | + # default timeframe conditions | |
| 206 | + conditions.append( | |
| 207 | + (dataframe[f"{self.config['stake_currency']}_rsi"] > params['xtf-stake-rsi']) | | |
| 208 | + (dataframe[f"{self.custom_fiat}_rsi"] < params['xtf-fiat-rsi']) | |
| 209 | + ) | |
| 210 | + # informative timeframe conditions | |
| 211 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xinf-stake-rmi']) | |
| 212 | + """ | |
| 213 | + | |
| 214 | + # Anything below here applies to persisting and new buy signal | |
| 215 | + conditions.append(dataframe['volume'].gt(0)) | |
| 216 | + | |
| 217 | + if conditions: | |
| 218 | + dataframe.loc[ | |
| 219 | + reduce(lambda x, y: x & y, conditions), | |
| 220 | + 'buy'] = 1 | |
| 221 | + | |
| 222 | + return dataframe | |
| 223 | + | |
| 224 | + """ | |
| 225 | + Sell Trigger Signals: | |
| 226 | + In this strategy all sells for profit happen according to ROI | |
| 227 | + This sell signal is designed only as a "dynamic stoploss" | |
| 228 | + """ | |
| 229 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 230 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 231 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 232 | + conditions = [] | |
| 233 | + | |
| 234 | + # add additional conditions based on time and profit | |
| 235 | + if trade_data['active_trade']: | |
| 236 | + # give some wiggle room for the trade to go negative a little bit before selling | |
| 237 | + # grow from -0.03 -> 0 after 300 minutes starting immediately | |
| 238 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 239 | + | |
| 240 | + # if we are at a loss, consider what the trend looks and preempt the stoploss | |
| 241 | + conditions.append( | |
| 242 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 243 | + (trade_data['current_profit'] > self.stoploss) | |
| 244 | + ) | |
| 245 | + | |
| 246 | + # if we have other trades, consider their profit and the # of free slots in the sell | |
| 247 | + if trade_data['other_trades']: | |
| 248 | + if trade_data['free_slots'] > 0: | |
| 249 | + """ | |
| 250 | + Less free slots, more willing to sell | |
| 251 | + 1 / free_slots * x = | |
| 252 | + 1 slot = 1/1 * -0.04 = -0.04 -> only allow sells if avg_other_proift above -0.04 | |
| 253 | + 4 slot = 1/4 * -0.04 = -0.01 -> only allow sells is avg_other_profit above -0.01 | |
| 254 | + """ | |
| 255 | + max_market_down = -0.04 # 5% | |
| 256 | + hold_pct = (1/trade_data['free_slots']) * max_market_down | |
| 257 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 258 | + else: | |
| 259 | + # if were out of slots, allow the biggest losing trade to sell regardless of avg profit | |
| 260 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 261 | + | |
| 262 | + conditions.append((dataframe['rmi-dn-trend'] == 1)) | |
| 263 | + # provide multiple cross thresholds in case we are coming from a higher point | |
| 264 | + conditions.append( | |
| 265 | + qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-high']) | | |
| 266 | + qtpylib.crossed_below(dataframe['rmi-slow'], params['rmi-low']) | |
| 267 | + ) | |
| 268 | + | |
| 269 | + conditions.append(dataframe['volume'].gt(0)) | |
| 270 | + | |
| 271 | + if conditions: | |
| 272 | + dataframe.loc[ | |
| 273 | + reduce(lambda x, y: x & y, conditions), | |
| 274 | + 'sell'] = 1 | |
| 275 | + | |
| 276 | + return dataframe | |
| 277 | + | |
| 278 | + """ | |
| 279 | + Custom Methods | |
| 280 | + """ | |
| 281 | + # Populate trades_data from the database | |
| 282 | + def populate_trades(self, pair: str) -> dict: | |
| 283 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 284 | + if not pair in self.custom_trade_info: | |
| 285 | + self.custom_trade_info[pair] = {} | |
| 286 | + | |
| 287 | + # init the temp dicts and set the trade stuff to false | |
| 288 | + trade_data = {} | |
| 289 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 290 | + self.custom_trade_info['meta'] = {} | |
| 291 | + | |
| 292 | + # active trade stuff only works in live and dry, not backtest | |
| 293 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 294 | + | |
| 295 | + # find out if we have an open trade for this pair | |
| 296 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 297 | + | |
| 298 | + # if so, get some information | |
| 299 | + if active_trade: | |
| 300 | + # get current price and update the min/max rate | |
| 301 | + current_rate = self.get_current_price(pair, True) | |
| 302 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 303 | + | |
| 304 | + # get how long the trade has been open in minutes and candles | |
| 305 | + present = arrow.utcnow() | |
| 306 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 307 | + open_minutes = (present - trade_start).total_seconds() // 60 # floor | |
| 308 | + | |
| 309 | + # set up the things we use in the strategy | |
| 310 | + trade_data['active_trade'] = True | |
| 311 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 312 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 313 | + trade_data['open_minutes'] : int = open_minutes | |
| 314 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 315 | + else: | |
| 316 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 317 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 318 | + | |
| 319 | + # if there are open trades not including the current pair, get some information | |
| 320 | + # future reference, for *all* open trades: open_trades = Trade.get_open_trades() | |
| 321 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 322 | + | |
| 323 | + if other_trades: | |
| 324 | + trade_data['other_trades'] = True | |
| 325 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 326 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 327 | + # find which of our trades is the biggest loser | |
| 328 | + if trade_data['current_profit'] < min(other_profit): | |
| 329 | + trade_data['biggest_loser'] = True | |
| 330 | + else: | |
| 331 | + trade_data['avg_other_profit'] = 0 | |
| 332 | + | |
| 333 | + # get the number of free trade slots, storing in every pairs dict due to laziness | |
| 334 | + open_trades = len(Trade.get_open_trades()) | |
| 335 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 336 | + | |
| 337 | + return trade_data | |
| 338 | + | |
| 339 | + # Get the current price from the exchange (or cache) | |
| 340 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 341 | + if not refresh: | |
| 342 | + rate = self.custom_current_price_cache.get(pair) | |
| 343 | + # Check if cache has been invalidated | |
| 344 | + if rate: | |
| 345 | + return rate | |
| 346 | + | |
| 347 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 348 | + if ask_strategy.get('use_order_book', False): | |
| 349 | + ob = self.dp.orderbook(pair, 1) | |
| 350 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 351 | + else: | |
| 352 | + ticker = self.dp.ticker(pair) | |
| 353 | + rate = ticker['last'] | |
| 354 | + | |
| 355 | + self.custom_current_price_cache[pair] = rate | |
| 356 | + return rate | |
| 357 | + | |
| 358 | + """ | |
| 359 | + Simple linear growth function: | |
| 360 | + Starts at X and grows to Y after A minutes (starting after B miniutes) | |
| 361 | + f(t) = X + (rate * t), where rate = (Y - X) / (B - A) | |
| 362 | + """ | |
| 363 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 364 | + time = max(0, trade_time - start_time) | |
| 365 | + rate = (end - start) / (end_time - start_time) | |
| 366 | + return min(end, start + (rate * time)) | |
| 367 | + | |
| 368 | + """ | |
| 369 | + Allow for buy/sell override parameters per pair. Testing, might remove. | |
| 370 | + TODO: | |
| 371 | + If good: make this more robust so you never have to edit this method. | |
| 372 | + Consider: per-pair ROI work if it seems worthwhile? | |
| 373 | + """ | |
| 374 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 375 | + buy_params = self.buy_params | |
| 376 | + sell_params = self.sell_params | |
| 377 | + | |
| 378 | + ### Stake: USD | |
| 379 | + if pair in ('ABC/XYZ', 'DEF/XYZ'): | |
| 380 | + buy_params = self.buy_params_GROUP1 | |
| 381 | + sell_params = self.sell_params_GROUP1 | |
| 382 | + elif pair in ('QRD/WTF'): | |
| 383 | + buy_params = self.buy_params_QRD | |
| 384 | + sell_params = self.sell_params_QRD | |
| 385 | + | |
| 386 | + if side == 'sell': | |
| 387 | + return sell_params | |
| 388 | + | |
| 389 | + return buy_params | |
| 390 | + | |
| 391 | + """ | |
| 392 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 393 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 394 | + """ | |
| 395 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 396 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 397 | + ob = self.dp.orderbook(pair, 1) | |
| 398 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 399 | + # Cancel buy order if price is more than 1% above the order. | |
| 400 | + if current_price > order['price'] * 1.01: | |
| 401 | + return True | |
| 402 | + return False | |
| 403 | + | |
| 404 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 405 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 406 | + ob = self.dp.orderbook(pair, 1) | |
| 407 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 408 | + # Cancel sell order if price is more than 1% below the order. | |
| 409 | + if current_price < order['price'] * 0.99: | |
| 410 | + return True | |
| 411 | + return False | |
| 412 | + | |
| 413 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 414 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 415 | + ob = self.dp.orderbook(pair, 1) | |
| 416 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 417 | + # Cancel buy order if price is more than 1% above the order. | |
| 418 | + if current_price > rate * 1.01: | |
| 419 | + return False | |
| 420 | + return True | |
| 421 | + | |
| 422 | +""" | |
| 423 | +Sub-strategy overrides | |
| 424 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 425 | +""" | |
| 426 | +# Sub-strategy with parameters specific to BTC stake | |
| 427 | +class Schism_BTC(Schism): | |
| 428 | + | |
| 429 | + timeframe = '1h' | |
| 430 | + inf_timeframe = '4h' | |
| 431 | + | |
| 432 | + buy_params = { | |
| 433 | + 'inf-rsi': 64, | |
| 434 | + 'mp': 55, | |
| 435 | + 'rmi-fast': 31, | |
| 436 | + 'rmi-slow': 16, | |
| 437 | + 'xinf-stake-rmi': 67, | |
| 438 | + 'xtf-fiat-rsi': 17, | |
| 439 | + 'xtf-stake-rsi': 57 | |
| 440 | + } | |
| 441 | + | |
| 442 | + minimal_roi = { | |
| 443 | + "0": 0.05, | |
| 444 | + "240": 0.025, | |
| 445 | + "1440": 0.01, | |
| 446 | + "4320": 0 | |
| 447 | + } | |
| 448 | + | |
| 449 | + use_sell_signal = False | |
| 450 | + | |
| 451 | +# Sub-strategy with parameters specific to ETH stake | |
| 452 | +class Schism_ETH(Schism): | |
| 453 | + | |
| 454 | + timeframe = '1h' | |
| 455 | + inf_timeframe = '4h' | |
| 456 | + | |
| 457 | + buy_params = { | |
| 458 | + 'inf-rsi': 13, | |
| 459 | + 'inf-stake-rmi': 69, | |
| 460 | + 'mp': 40, | |
| 461 | + 'rmi-fast': 42, | |
| 462 | + 'rmi-slow': 17, | |
| 463 | + 'tf-fiat-rsi': 15, | |
| 464 | + 'tf-stake-rsi': 92 | |
| 465 | + } | |
| 466 | + | |
| 467 | + minimal_roi = { | |
| 468 | + "0": 0.05, | |
| 469 | + "240": 0.025, | |
| 470 | + "1440": 0.01, | |
| 471 | + "4320": 0 | |
| 472 | + } | |
| 473 | + | |
| 474 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Schism2MM.py +238 −0
| @@ -0,0 +1,238 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI | |
| 12 | +from statistics import mean | |
| 13 | +from cachetools import TTLCache | |
| 14 | +from scipy.signal import argrelextrema | |
| 15 | + | |
| 16 | +class Schism2MM(IStrategy): | |
| 17 | + | |
| 18 | + timeframe = '5m' | |
| 19 | + inf_timeframe = '1h' | |
| 20 | + | |
| 21 | + buy_params = { | |
| 22 | + 'inf-pct-adr': 0.95, | |
| 23 | + 'inf-rsi': 65, | |
| 24 | + 'mp': 53, | |
| 25 | + 'rmi-fast': 41, | |
| 26 | + 'rmi-slow': 33 | |
| 27 | + } | |
| 28 | + | |
| 29 | + sell_params = {} | |
| 30 | + | |
| 31 | + minimal_roi = { | |
| 32 | + "0": 0.025, | |
| 33 | + "10": 0.015, | |
| 34 | + "20": 0.01, | |
| 35 | + "30": 0.005, | |
| 36 | + "120": 0 | |
| 37 | + } | |
| 38 | + | |
| 39 | + stoploss = -0.99 | |
| 40 | + | |
| 41 | + use_sell_signal = False | |
| 42 | + sell_profit_only = False | |
| 43 | + ignore_roi_if_buy_signal = True | |
| 44 | + | |
| 45 | + startup_candle_count: int = 72 | |
| 46 | + | |
| 47 | + custom_trade_info = {} | |
| 48 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 49 | + | |
| 50 | + def informative_pairs(self): | |
| 51 | + pairs = self.dp.current_whitelist() | |
| 52 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 53 | + | |
| 54 | + return informative_pairs | |
| 55 | + | |
| 56 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 57 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 58 | + | |
| 59 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 60 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 61 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 62 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 63 | + | |
| 64 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 65 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 66 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 67 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 68 | + | |
| 69 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 70 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 71 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 72 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 73 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 74 | + | |
| 75 | + min_peaks = argrelextrema(dataframe['close'].values, np.less, order=100) | |
| 76 | + | |
| 77 | + for mp in min_peaks[0]: | |
| 78 | + dataframe.at[mp, 'buy_signal'] = True | |
| 79 | + | |
| 80 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 81 | + | |
| 82 | + return dataframe | |
| 83 | + | |
| 84 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 85 | + params = self.buy_params | |
| 86 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 87 | + conditions = [] | |
| 88 | + | |
| 89 | + if trade_data['active_trade']: | |
| 90 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 91 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 300)) | |
| 92 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 93 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 94 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 95 | + else: | |
| 96 | + conditions.append( | |
| 97 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 98 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{self.inf_timeframe}"])) & | |
| 99 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 100 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 101 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 102 | + (dataframe['mp'] <= params['mp']) | |
| 103 | + ) | |
| 104 | + | |
| 105 | + conditions.append(dataframe['volume'].gt(0)) | |
| 106 | + conditions.append(dataframe['buy_signal']) | |
| 107 | + | |
| 108 | + if conditions: | |
| 109 | + dataframe.loc[ | |
| 110 | + reduce(lambda x, y: x & y, conditions), | |
| 111 | + 'buy'] = 1 | |
| 112 | + | |
| 113 | + return dataframe | |
| 114 | + | |
| 115 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 116 | + params = self.sell_params | |
| 117 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 118 | + conditions = [] | |
| 119 | + | |
| 120 | + if trade_data['active_trade']: | |
| 121 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 122 | + | |
| 123 | + conditions.append( | |
| 124 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 125 | + (trade_data['current_profit'] > self.stoploss) & | |
| 126 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 127 | + (dataframe['volume'].gt(0)) | |
| 128 | + ) | |
| 129 | + if trade_data['peak_profit'] > 0: | |
| 130 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 50)) | |
| 131 | + else: | |
| 132 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 10)) | |
| 133 | + | |
| 134 | + if trade_data['other_trades']: | |
| 135 | + if trade_data['free_slots'] > 0: | |
| 136 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 137 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 138 | + else: | |
| 139 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 140 | + | |
| 141 | + else: | |
| 142 | + conditions.append(dataframe['volume'].lt(0)) | |
| 143 | + | |
| 144 | + if conditions: | |
| 145 | + dataframe.loc[ | |
| 146 | + reduce(lambda x, y: x & y, conditions), | |
| 147 | + 'sell'] = 1 | |
| 148 | + | |
| 149 | + return dataframe | |
| 150 | + | |
| 151 | + def populate_trades(self, pair: str) -> dict: | |
| 152 | + if not pair in self.custom_trade_info: | |
| 153 | + self.custom_trade_info[pair] = {} | |
| 154 | + | |
| 155 | + trade_data = {} | |
| 156 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 157 | + | |
| 158 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 159 | + | |
| 160 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 161 | + | |
| 162 | + if active_trade: | |
| 163 | + current_rate = self.get_current_price(pair, True) | |
| 164 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 165 | + | |
| 166 | + present = arrow.utcnow() | |
| 167 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 168 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 169 | + | |
| 170 | + trade_data['active_trade'] = True | |
| 171 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 172 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 173 | + trade_data['open_minutes'] : int = open_minutes | |
| 174 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 175 | + else: | |
| 176 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 177 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 178 | + | |
| 179 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 180 | + | |
| 181 | + if other_trades: | |
| 182 | + trade_data['other_trades'] = True | |
| 183 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 184 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 185 | + if trade_data['current_profit'] < min(other_profit): | |
| 186 | + trade_data['biggest_loser'] = True | |
| 187 | + else: | |
| 188 | + trade_data['avg_other_profit'] = 0 | |
| 189 | + | |
| 190 | + open_trades = len(Trade.get_open_trades()) | |
| 191 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 192 | + return trade_data | |
| 193 | + | |
| 194 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 195 | + if not refresh: | |
| 196 | + rate = self.custom_current_price_cache.get(pair) | |
| 197 | + if rate: | |
| 198 | + return rate | |
| 199 | + | |
| 200 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 201 | + if ask_strategy.get('use_order_book', False): | |
| 202 | + ob = self.dp.orderbook(pair, 1) | |
| 203 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 204 | + else: | |
| 205 | + ticker = self.dp.ticker(pair) | |
| 206 | + rate = ticker['last'] | |
| 207 | + | |
| 208 | + self.custom_current_price_cache[pair] = rate | |
| 209 | + return rate | |
| 210 | + | |
| 211 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 212 | + time = max(0, trade_time - start_time) | |
| 213 | + rate = (end - start) / (end_time - start_time) | |
| 214 | + return min(end, start + (rate * trade_time)) | |
| 215 | + | |
| 216 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 217 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 218 | + ob = self.dp.orderbook(pair, 1) | |
| 219 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 220 | + if current_price > order['price'] * 1.01: | |
| 221 | + return True | |
| 222 | + return False | |
| 223 | + | |
| 224 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 225 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 226 | + ob = self.dp.orderbook(pair, 1) | |
| 227 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 228 | + if current_price < order['price'] * 0.99: | |
| 229 | + return True | |
| 230 | + return False | |
| 231 | + | |
| 232 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 233 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 234 | + ob = self.dp.orderbook(pair, 1) | |
| 235 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 236 | + if current_price > rate * 1.01: | |
| 237 | + return False | |
| 238 | + return True | |
| No newline at the end of the file |
added strategies/old/Schism6.py +232 −0
| @@ -0,0 +1,232 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI | |
| 12 | +from statistics import mean | |
| 13 | +from cachetools import TTLCache | |
| 14 | + | |
| 15 | + | |
| 16 | +class Schism6(IStrategy): | |
| 17 | + | |
| 18 | + timeframe = '5m' | |
| 19 | + inf_timeframe = '1h' | |
| 20 | + | |
| 21 | + buy_params = { | |
| 22 | + 'inf-pct-adr': 0.86884, | |
| 23 | + 'inf-rsi': 65, | |
| 24 | + 'mp': 53, | |
| 25 | + 'rmi-fast': 41, | |
| 26 | + 'rmi-slow': 33 | |
| 27 | + } | |
| 28 | + | |
| 29 | + sell_params = {} | |
| 30 | + | |
| 31 | + minimal_roi = { | |
| 32 | + "0": 0.025, | |
| 33 | + "10": 0.015, | |
| 34 | + "20": 0.01, | |
| 35 | + "30": 0.005, | |
| 36 | + "120": 0 | |
| 37 | + } | |
| 38 | + | |
| 39 | + stoploss = -0.5 | |
| 40 | + | |
| 41 | + use_sell_signal = True | |
| 42 | + sell_profit_only = False | |
| 43 | + ignore_roi_if_buy_signal = True | |
| 44 | + | |
| 45 | + startup_candle_count: int = 72 | |
| 46 | + | |
| 47 | + custom_trade_info = {} | |
| 48 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 49 | + | |
| 50 | + def informative_pairs(self): | |
| 51 | + pairs = self.dp.current_whitelist() | |
| 52 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 53 | + | |
| 54 | + return informative_pairs | |
| 55 | + | |
| 56 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 57 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 58 | + | |
| 59 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 60 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 61 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 62 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 63 | + | |
| 64 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 65 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 66 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 67 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 68 | + | |
| 69 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 70 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 71 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 72 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 73 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 74 | + | |
| 75 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 76 | + | |
| 77 | + return dataframe | |
| 78 | + | |
| 79 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 80 | + params = self.buy_params | |
| 81 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 82 | + conditions = [] | |
| 83 | + | |
| 84 | + if trade_data['active_trade']: | |
| 85 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 86 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 300)) | |
| 87 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 88 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 89 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 90 | + else: | |
| 91 | + conditions.append( | |
| 92 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 93 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{self.inf_timeframe}"])) & | |
| 94 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 95 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 96 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 97 | + (dataframe['mp'] <= params['mp']) | |
| 98 | + ) | |
| 99 | + | |
| 100 | + conditions.append(dataframe['volume'].gt(0)) | |
| 101 | + | |
| 102 | + if conditions: | |
| 103 | + dataframe.loc[ | |
| 104 | + reduce(lambda x, y: x & y, conditions), | |
| 105 | + 'buy'] = 1 | |
| 106 | + | |
| 107 | + return dataframe | |
| 108 | + | |
| 109 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 110 | + params = self.sell_params | |
| 111 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 112 | + conditions = [] | |
| 113 | + | |
| 114 | + if trade_data['active_trade']: | |
| 115 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 116 | + | |
| 117 | + conditions.append( | |
| 118 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 119 | + (trade_data['current_profit'] > self.stoploss) & | |
| 120 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 121 | + (dataframe['volume'].gt(0)) | |
| 122 | + ) | |
| 123 | + if trade_data['peak_profit'] > 0: | |
| 124 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 50)) | |
| 125 | + else: | |
| 126 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 10)) | |
| 127 | + | |
| 128 | + if trade_data['other_trades']: | |
| 129 | + if trade_data['free_slots'] > 0: | |
| 130 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 131 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 132 | + else: | |
| 133 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 134 | + | |
| 135 | + else: | |
| 136 | + conditions.append(dataframe['volume'].lt(0)) | |
| 137 | + | |
| 138 | + if conditions: | |
| 139 | + dataframe.loc[ | |
| 140 | + reduce(lambda x, y: x & y, conditions), | |
| 141 | + 'sell'] = 1 | |
| 142 | + | |
| 143 | + return dataframe | |
| 144 | + | |
| 145 | + def populate_trades(self, pair: str) -> dict: | |
| 146 | + if not pair in self.custom_trade_info: | |
| 147 | + self.custom_trade_info[pair] = {} | |
| 148 | + | |
| 149 | + trade_data = {} | |
| 150 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 151 | + | |
| 152 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 153 | + | |
| 154 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 155 | + | |
| 156 | + if active_trade: | |
| 157 | + current_rate = self.get_current_price(pair, True) | |
| 158 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 159 | + | |
| 160 | + present = arrow.utcnow() | |
| 161 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 162 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 163 | + | |
| 164 | + trade_data['active_trade'] = True | |
| 165 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 166 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 167 | + trade_data['open_minutes'] : int = open_minutes | |
| 168 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 169 | + else: | |
| 170 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 171 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 172 | + | |
| 173 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 174 | + | |
| 175 | + if other_trades: | |
| 176 | + trade_data['other_trades'] = True | |
| 177 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 178 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 179 | + if trade_data['current_profit'] < min(other_profit): | |
| 180 | + trade_data['biggest_loser'] = True | |
| 181 | + else: | |
| 182 | + trade_data['avg_other_profit'] = 0 | |
| 183 | + | |
| 184 | + open_trades = len(Trade.get_open_trades()) | |
| 185 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 186 | + return trade_data | |
| 187 | + | |
| 188 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 189 | + if not refresh: | |
| 190 | + rate = self.custom_current_price_cache.get(pair) | |
| 191 | + if rate: | |
| 192 | + return rate | |
| 193 | + | |
| 194 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 195 | + if ask_strategy.get('use_order_book', False): | |
| 196 | + ob = self.dp.orderbook(pair, 1) | |
| 197 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 198 | + else: | |
| 199 | + ticker = self.dp.ticker(pair) | |
| 200 | + rate = ticker['last'] | |
| 201 | + | |
| 202 | + self.custom_current_price_cache[pair] = rate | |
| 203 | + return rate | |
| 204 | + | |
| 205 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 206 | + time = max(0, trade_time - start_time) | |
| 207 | + rate = (end - start) / (end_time - start_time) | |
| 208 | + return min(end, start + (rate * time)) | |
| 209 | + | |
| 210 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 211 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 212 | + ob = self.dp.orderbook(pair, 1) | |
| 213 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 214 | + if current_price > order['price'] * 1.01: | |
| 215 | + return True | |
| 216 | + return False | |
| 217 | + | |
| 218 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 219 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 220 | + ob = self.dp.orderbook(pair, 1) | |
| 221 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 222 | + if current_price < order['price'] * 0.99: | |
| 223 | + return True | |
| 224 | + return False | |
| 225 | + | |
| 226 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 227 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 228 | + ob = self.dp.orderbook(pair, 1) | |
| 229 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 230 | + if current_price > rate * 1.01: | |
| 231 | + return False | |
| 232 | + return True | |
| No newline at the end of the file |
added strategies/old/SchismLess-v2.py +235 −0
| @@ -0,0 +1,235 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | +from technical.indicators import RMI | |
| 12 | +from statistics import mean | |
| 13 | +from cachetools import TTLCache | |
| 14 | + | |
| 15 | + | |
| 16 | +class Schism(IStrategy): | |
| 17 | + | |
| 18 | + timeframe = '5m' | |
| 19 | + inf_timeframe = '1h' | |
| 20 | + | |
| 21 | + buy_params = { | |
| 22 | + 'rmi-slow': 20, | |
| 23 | + 'rmi-fast': 20, | |
| 24 | + 'mp': 50, | |
| 25 | + 'inf-rsi': 30, | |
| 26 | + 'inf-pct-adr': 0.8 | |
| 27 | + } | |
| 28 | + | |
| 29 | + sell_params = {} | |
| 30 | + | |
| 31 | + minimal_roi = { | |
| 32 | + "0": 0.10, | |
| 33 | + "15": 0.05, | |
| 34 | + "30": 0.025, | |
| 35 | + "60": 0.01, | |
| 36 | + "120": 0.005, | |
| 37 | + "1440": 0 | |
| 38 | + } | |
| 39 | + | |
| 40 | + stoploss = -0.40 | |
| 41 | + | |
| 42 | + use_sell_signal = True | |
| 43 | + sell_profit_only = False | |
| 44 | + ignore_roi_if_buy_signal = True | |
| 45 | + | |
| 46 | + startup_candle_count: int = 72 | |
| 47 | + | |
| 48 | + custom_trade_info = {} | |
| 49 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 50 | + | |
| 51 | + def informative_pairs(self): | |
| 52 | + pairs = self.dp.current_whitelist() | |
| 53 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 54 | + | |
| 55 | + return informative_pairs | |
| 56 | + | |
| 57 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 58 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 59 | + | |
| 60 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 61 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 62 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 63 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 64 | + | |
| 65 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 66 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 67 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 68 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 69 | + | |
| 70 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 71 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 72 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 73 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 74 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 75 | + | |
| 76 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 77 | + | |
| 78 | + return dataframe | |
| 79 | + | |
| 80 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 81 | + params = self.buy_params | |
| 82 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 83 | + conditions = [] | |
| 84 | + | |
| 85 | + if trade_data['active_trade']: | |
| 86 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 87 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 300)) | |
| 88 | + | |
| 89 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 90 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 91 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 92 | + else: | |
| 93 | + conditions.append( | |
| 94 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 95 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{self.inf_timeframe}"])) & | |
| 96 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 97 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 98 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 99 | + (dataframe['mp'] <= params['mp']) | |
| 100 | + ) | |
| 101 | + | |
| 102 | + conditions.append(dataframe['volume'].gt(0)) | |
| 103 | + | |
| 104 | + if conditions: | |
| 105 | + dataframe.loc[ | |
| 106 | + reduce(lambda x, y: x & y, conditions), | |
| 107 | + 'buy'] = 1 | |
| 108 | + | |
| 109 | + return dataframe | |
| 110 | + | |
| 111 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 112 | + params = self.sell_params | |
| 113 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 114 | + conditions = [] | |
| 115 | + | |
| 116 | + if trade_data['active_trade']: | |
| 117 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 118 | + | |
| 119 | + conditions.append( | |
| 120 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 121 | + (trade_data['current_profit'] > self.stoploss) & | |
| 122 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 123 | + (dataframe['volume'].gt(0)) | |
| 124 | + ) | |
| 125 | + if trade_data['peak_profit'] > 0: | |
| 126 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 50)) | |
| 127 | + else: | |
| 128 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 10)) | |
| 129 | + | |
| 130 | + if trade_data['other_trades']: | |
| 131 | + if trade_data['free_slots'] > 0: | |
| 132 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 133 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 134 | + else: | |
| 135 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 136 | + | |
| 137 | + else: | |
| 138 | + conditions.append(dataframe['volume'].lt(0)) | |
| 139 | + | |
| 140 | + if conditions: | |
| 141 | + dataframe.loc[ | |
| 142 | + reduce(lambda x, y: x & y, conditions), | |
| 143 | + 'sell'] = 1 | |
| 144 | + | |
| 145 | + return dataframe | |
| 146 | + | |
| 147 | + def populate_trades(self, pair: str) -> dict: | |
| 148 | + if not pair in self.custom_trade_info: | |
| 149 | + self.custom_trade_info[pair] = {} | |
| 150 | + | |
| 151 | + trade_data = {} | |
| 152 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 153 | + | |
| 154 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 155 | + | |
| 156 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 157 | + | |
| 158 | + if active_trade: | |
| 159 | + current_rate = self.get_current_price(pair, True) | |
| 160 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 161 | + | |
| 162 | + present = arrow.utcnow() | |
| 163 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 164 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 165 | + | |
| 166 | + trade_data['active_trade'] = True | |
| 167 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 168 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 169 | + trade_data['open_minutes'] : int = open_minutes | |
| 170 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 171 | + else: | |
| 172 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 173 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 174 | + | |
| 175 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 176 | + | |
| 177 | + if other_trades: | |
| 178 | + trade_data['other_trades'] = True | |
| 179 | + total_other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 180 | + trade_data['avg_other_profit'] = mean(total_other_profit) | |
| 181 | + if trade_data['current_profit'] < min(other_profit): | |
| 182 | + trade_data['biggest_loser'] = True | |
| 183 | + else: | |
| 184 | + trade_data['avg_other_profit'] = 0 | |
| 185 | + | |
| 186 | + open_trades = len(Trade.get_open_trades()) | |
| 187 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 188 | + | |
| 189 | + return trade_data | |
| 190 | + | |
| 191 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 192 | + if not refresh: | |
| 193 | + rate = self.custom_current_price_cache.get(pair) | |
| 194 | + if rate: | |
| 195 | + return rate | |
| 196 | + | |
| 197 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 198 | + if ask_strategy.get('use_order_book', False): | |
| 199 | + ob = self.dp.orderbook(pair, 1) | |
| 200 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 201 | + else: | |
| 202 | + ticker = self.dp.ticker(pair) | |
| 203 | + rate = ticker['last'] | |
| 204 | + | |
| 205 | + self.custom_current_price_cache[pair] = rate | |
| 206 | + return rate | |
| 207 | + | |
| 208 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 209 | + time = max(0, trade_time - start_time) | |
| 210 | + rate = (end - start) / (end_time - start_time) | |
| 211 | + return min(end, start + (rate * trade_time)) | |
| 212 | + | |
| 213 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 214 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 215 | + ob = self.dp.orderbook(pair, 1) | |
| 216 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 217 | + if current_price > order['price'] * 1.01: | |
| 218 | + return True | |
| 219 | + return False | |
| 220 | + | |
| 221 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 222 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 223 | + ob = self.dp.orderbook(pair, 1) | |
| 224 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 225 | + if current_price < order['price'] * 0.99: | |
| 226 | + return True | |
| 227 | + return False | |
| 228 | + | |
| 229 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 230 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 231 | + ob = self.dp.orderbook(pair, 1) | |
| 232 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 233 | + if current_price > rate * 1.01: | |
| 234 | + return False | |
| 235 | + return True | |
| No newline at the end of the file |
added strategies/old/SchismLess.py +231 −0
| @@ -0,0 +1,231 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from typing import Dict, List, Optional, Tuple | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | +class Schism(IStrategy): | |
| 17 | + timeframe = '15m' | |
| 18 | + inf_timeframe = '4h' | |
| 19 | + | |
| 20 | + buy_params = { | |
| 21 | + 'inf-rsi': 11, | |
| 22 | + 'mp': 65, | |
| 23 | + 'rmi-fast': 32, | |
| 24 | + 'rmi-slow': 22 | |
| 25 | + } | |
| 26 | + | |
| 27 | + sell_params = {} | |
| 28 | + | |
| 29 | + minimal_roi = { | |
| 30 | + "0": 0.05, | |
| 31 | + "60": 0.025, | |
| 32 | + "180": 0.01, | |
| 33 | + "1440": 0 | |
| 34 | + } | |
| 35 | + | |
| 36 | + stoploss = -0.20 | |
| 37 | + | |
| 38 | + use_sell_signal = False | |
| 39 | + sell_profit_only = False | |
| 40 | + ignore_roi_if_buy_signal = True | |
| 41 | + | |
| 42 | + startup_candle_count: int = 72 | |
| 43 | + | |
| 44 | + custom_trade_info = {} | |
| 45 | + custom_fiat = "USD" | |
| 46 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 47 | + | |
| 48 | + def informative_pairs(self): | |
| 49 | + pairs = self.dp.current_whitelist() | |
| 50 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 51 | + | |
| 52 | + return informative_pairs | |
| 53 | + | |
| 54 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 55 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 56 | + | |
| 57 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 58 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 59 | + | |
| 60 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 61 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 62 | + | |
| 63 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 64 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 65 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 66 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 67 | + | |
| 68 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 69 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 70 | + | |
| 71 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 72 | + | |
| 73 | + return dataframe | |
| 74 | + | |
| 75 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 76 | + params = self.buy_params | |
| 77 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 78 | + conditions = [] | |
| 79 | + | |
| 80 | + if trade_data['active_trade']: | |
| 81 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 82 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 83 | + | |
| 84 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 85 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 86 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 87 | + | |
| 88 | + else: | |
| 89 | + conditions.append( | |
| 90 | + (dataframe[f"rsi_{self.inf_timeframe}"] < params['inf-rsi']) & | |
| 91 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 92 | + (dataframe['rmi-slow'] >= params['rmi-slow']) & | |
| 93 | + (dataframe['rmi-fast'] <= params['rmi-fast']) & | |
| 94 | + (dataframe['mp'] <= params['mp']) | |
| 95 | + ) | |
| 96 | + | |
| 97 | + conditions.append(dataframe['volume'].gt(0)) | |
| 98 | + | |
| 99 | + if conditions: | |
| 100 | + dataframe.loc[ | |
| 101 | + reduce(lambda x, y: x & y, conditions), | |
| 102 | + 'buy'] = 1 | |
| 103 | + | |
| 104 | + return dataframe | |
| 105 | + | |
| 106 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 107 | + params = self.sell_params | |
| 108 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 109 | + conditions = [] | |
| 110 | + | |
| 111 | + if trade_data['active_trade']: | |
| 112 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 113 | + | |
| 114 | + conditions.append( | |
| 115 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 116 | + (trade_data['current_profit'] > self.stoploss) & | |
| 117 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 118 | + (dataframe['volume'].gt(0)) | |
| 119 | + ) | |
| 120 | + if trade_data['peak_profit'] > 0: | |
| 121 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 50)) | |
| 122 | + else: | |
| 123 | + conditions.append(qtpylib.crossed_below(dataframe['rmi-slow'], 10)) | |
| 124 | + | |
| 125 | + if trade_data['other_trades']: | |
| 126 | + if trade_data['free_slots'] > 0: | |
| 127 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 128 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 129 | + else: | |
| 130 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 131 | + | |
| 132 | + else: | |
| 133 | + conditions.append(dataframe['volume'].lt(0)) | |
| 134 | + | |
| 135 | + if conditions: | |
| 136 | + dataframe.loc[ | |
| 137 | + reduce(lambda x, y: x & y, conditions), | |
| 138 | + 'sell'] = 1 | |
| 139 | + | |
| 140 | + return dataframe | |
| 141 | + | |
| 142 | + def populate_trades(self, pair: str) -> dict: | |
| 143 | + if not pair in self.custom_trade_info: | |
| 144 | + self.custom_trade_info[pair] = {} | |
| 145 | + | |
| 146 | + trade_data = {} | |
| 147 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 148 | + self.custom_trade_info['meta'] = {} | |
| 149 | + | |
| 150 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 151 | + | |
| 152 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 153 | + | |
| 154 | + if active_trade: | |
| 155 | + current_rate = self.get_current_price(pair, True) | |
| 156 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 157 | + | |
| 158 | + present = arrow.utcnow() | |
| 159 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 160 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 161 | + | |
| 162 | + trade_data['active_trade'] = True | |
| 163 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 164 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 165 | + trade_data['open_minutes'] : int = open_minutes | |
| 166 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 167 | + else: | |
| 168 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 169 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 170 | + | |
| 171 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 172 | + | |
| 173 | + if other_trades: | |
| 174 | + trade_data['other_trades'] = True | |
| 175 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 176 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 177 | + if trade_data['current_profit'] < min(other_profit): | |
| 178 | + trade_data['biggest_loser'] = True | |
| 179 | + else: | |
| 180 | + trade_data['avg_other_profit'] = 0 | |
| 181 | + | |
| 182 | + open_trades = len(Trade.get_open_trades()) | |
| 183 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 184 | + | |
| 185 | + return trade_data | |
| 186 | + | |
| 187 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 188 | + if not refresh: | |
| 189 | + rate = self.custom_current_price_cache.get(pair) | |
| 190 | + if rate: | |
| 191 | + return rate | |
| 192 | + | |
| 193 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 194 | + if ask_strategy.get('use_order_book', False): | |
| 195 | + ob = self.dp.orderbook(pair, 1) | |
| 196 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 197 | + else: | |
| 198 | + ticker = self.dp.ticker(pair) | |
| 199 | + rate = ticker['last'] | |
| 200 | + | |
| 201 | + self.custom_current_price_cache[pair] = rate | |
| 202 | + return rate | |
| 203 | + | |
| 204 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 205 | + time = max(0, trade_time - start_time) | |
| 206 | + rate = (end - start) / (end_time - start_time) | |
| 207 | + return min(end, start + (rate * trade_time)) | |
| 208 | + | |
| 209 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 210 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 211 | + ob = self.dp.orderbook(pair, 1) | |
| 212 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 213 | + if current_price > order['price'] * 1.01: | |
| 214 | + return True | |
| 215 | + return False | |
| 216 | + | |
| 217 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 218 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 219 | + ob = self.dp.orderbook(pair, 1) | |
| 220 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 221 | + if current_price < order['price'] * 0.99: | |
| 222 | + return True | |
| 223 | + return False | |
| 224 | + | |
| 225 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 226 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 227 | + ob = self.dp.orderbook(pair, 1) | |
| 228 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 229 | + if current_price > rate * 1.01: | |
| 230 | + return False | |
| 231 | + return True | |
| No newline at the end of the file |
added strategies/old/Solipsis-Con-v1.py +679 −0
| @@ -0,0 +1,679 @@ | ||
| 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 | |
| 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 statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | +from technical.consensus import Consensus | |
| 16 | + | |
| 17 | +# Get rid of pandas warnings during backtesting | |
| 18 | +import pandas as pd | |
| 19 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 20 | + | |
| 21 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 22 | +import sys | |
| 23 | +from pathlib import Path | |
| 24 | +sys.path.append(str(Path(__file__).parent)) | |
| 25 | + | |
| 26 | +import custom_indicators as cta | |
| 27 | + | |
| 28 | +""" | |
| 29 | +TODO: | |
| 30 | + - Continue to hunt for a better all around buy signal. | |
| 31 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 32 | + - ADR guards are helping but need to reduce losing trade counts. | |
| 33 | + - Need to reduce drawdown. | |
| 34 | + - Tweak ROI Trend Ride | |
| 35 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 36 | + - Maybe further exploit the ROI table itself using trade data? | |
| 37 | + - Per-pair automatic ROI points based on ADR/ATR or something similar? | |
| 38 | + - Tweak sell signal | |
| 39 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 40 | + - Further enchance and optimize custom stop loss | |
| 41 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 42 | + | |
| 43 | +STRATEGY NOTES: | |
| 44 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 45 | + --enable-protections as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 46 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 47 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 48 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 49 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 50 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 51 | + - If running backtest/hyperopt around the portion of the sell signal that is testable, keep in mind in live/dry | |
| 52 | + it will not sell nearly as frequently due to the profit guard and other_profit / free_slot guards. | |
| 53 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 54 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 55 | + ROI based sells will be higher than the backtest shows. | |
| 56 | + - It is *not* worthwhile to hyperopt for roi as it does not take into account the roi trend ride we are doing and | |
| 57 | + having ROI points that are too high will sort of be counter-productive to how this strategy works even if it seems | |
| 58 | + to produce better results in backtesting. | |
| 59 | + - It *might be* worthwhile to hyperopt the stoploss but we can't hyperopt any of the parameters in the custom stoploss | |
| 60 | + so hyperopting the stoploss is only changing the initial position relative to the other settings. | |
| 61 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 62 | + - The custom stoploss has settings to emulate the same functionality however. | |
| 63 | + - It is *highly* recommended to backtest with use_sell_signal = False because it will not behave remotely the same in dry/live | |
| 64 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only or 'buy sell' and at least 1000 total epochs several times. | |
| 65 | + | |
| 66 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 67 | + | |
| 68 | + custom_pair_params = [ | |
| 69 | + { | |
| 70 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 71 | + 'buy_params': {}, | |
| 72 | + 'sell_params': {} | |
| 73 | + } | |
| 74 | + ] | |
| 75 | + | |
| 76 | +""" | |
| 77 | + | |
| 78 | +class SolipsisCon(IStrategy): | |
| 79 | + | |
| 80 | + # Recommended for USD/USDT/etc. | |
| 81 | + timeframe = '5m' | |
| 82 | + inf_timeframe = '1h' | |
| 83 | + | |
| 84 | + buy_params = { | |
| 85 | + 'consensus-buy': 4, | |
| 86 | + 'inf-guard': 'both', | |
| 87 | + 'inf-pct-adr-bot': 0.06607, | |
| 88 | + 'inf-pct-adr-top': 0.81639, | |
| 89 | + 'xbtc-base-enable': True, | |
| 90 | + 'xbtc-consensus-buy': 37, | |
| 91 | + 'xbtc-inf-consensus-buy': 29, | |
| 92 | + 'xbtc-inf-enable': False, | |
| 93 | + 'xtra-base-fiat-rmi': 34, | |
| 94 | + 'xtra-base-stake-rmi': 38, | |
| 95 | + 'xtra-inf-stake-rmi': 52 | |
| 96 | + } | |
| 97 | + | |
| 98 | + sell_params = { | |
| 99 | + 'consensus-sell': 62 | |
| 100 | + } | |
| 101 | + | |
| 102 | + # Custom buy/sell parameters per pair | |
| 103 | + custom_pair_params = [] | |
| 104 | + | |
| 105 | + # Recommended on 5m timeframe | |
| 106 | + minimal_roi = { | |
| 107 | + "0": 0.05, | |
| 108 | + "30": 0.025, | |
| 109 | + "120": 0.01, | |
| 110 | + "360": 0.01, | |
| 111 | + "720": 0.005, | |
| 112 | + "1440": 0 | |
| 113 | + } | |
| 114 | + | |
| 115 | + # Optional | |
| 116 | + dynamic_roi = { | |
| 117 | + 'dynamic_roi_enabled': True, | |
| 118 | + 'dynamic_roi_type': 'connect' | |
| 119 | + } | |
| 120 | + | |
| 121 | + stoploss = -0.30 | |
| 122 | + | |
| 123 | + # Optional | |
| 124 | + use_custom_stoploss = False | |
| 125 | + custom_stop = { | |
| 126 | + 'mode': 'decay', # decay, decay-only | |
| 127 | + # Linear Decay Parameters | |
| 128 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 129 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 130 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 131 | + 'decay-end': -0.03, # ending value | |
| 132 | + # Current vs Min Profit | |
| 133 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 134 | + 'cur-threshold': 0, # how far negative should current profit be before we consider moving it up based on cur/min | |
| 135 | + # Positive Trailing | |
| 136 | + 'pos-trail': False, # enable trailing once positive | |
| 137 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 138 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 139 | + } | |
| 140 | + | |
| 141 | + # Recommended | |
| 142 | + use_sell_signal = True | |
| 143 | + sell_profit_only = False | |
| 144 | + ignore_roi_if_buy_signal = True | |
| 145 | + | |
| 146 | + # Required | |
| 147 | + startup_candle_count: int = 72 | |
| 148 | + process_only_new_candles = False | |
| 149 | + | |
| 150 | + # Strategy Specific Variable Storage | |
| 151 | + custom_trade_info = {} | |
| 152 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 153 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 154 | + | |
| 155 | + """ | |
| 156 | + Informative Pair Definitions | |
| 157 | + """ | |
| 158 | + def informative_pairs(self): | |
| 159 | + pairs = self.dp.current_whitelist() | |
| 160 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 161 | + | |
| 162 | + # add extra informative pairs if the stake is BTC or ETH | |
| 163 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 164 | + for pair in pairs: | |
| 165 | + coin, stake = pair.split('/') | |
| 166 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 167 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 168 | + | |
| 169 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 170 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 171 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 172 | + # if BTC/STAKE is not in whitelist, add it as an informative pair | |
| 173 | + else: | |
| 174 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 175 | + if not btc_stake in pairs: | |
| 176 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 177 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 178 | + | |
| 179 | + return informative_pairs | |
| 180 | + | |
| 181 | + """ | |
| 182 | + Indicator Definitions | |
| 183 | + """ | |
| 184 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 185 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 186 | + | |
| 187 | + c = Consensus(dataframe) | |
| 188 | + | |
| 189 | + # Overlap / MA's | |
| 190 | + c.evaluate_tema(period=12) | |
| 191 | + c.evaluate_ema(period=8) | |
| 192 | + c.evaluate_ema(period=13) | |
| 193 | + c.evaluate_ema(period=21) | |
| 194 | + c.evaluate_ema(period=34) | |
| 195 | + c.evaluate_ema(period=55) | |
| 196 | + c.evaluate_ichimoku() # slightly slow | |
| 197 | + c.evaluate_hull() # very slow | |
| 198 | + c.evaluate_vwma(period=20) | |
| 199 | + | |
| 200 | + # Oscillators | |
| 201 | + c.evaluate_rsi(period=14) | |
| 202 | + c.evaluate_stoch() | |
| 203 | + c.evaluate_cci() # slightly slow | |
| 204 | + c.evaluate_adx() | |
| 205 | + c.evaluate_macd() | |
| 206 | + c.evaluate_momentum() | |
| 207 | + c.evaluate_williams() | |
| 208 | + # c.evaluate_ultimate_oscilator() # extremely slow | |
| 209 | + # missing: awesome osc | |
| 210 | + # missing: bull bear | |
| 211 | + # missing: stoch rsi | |
| 212 | + | |
| 213 | + c.evaluate_macd_cross_over() | |
| 214 | + c.evaluate_osc() | |
| 215 | + c.evaluate_cmf() | |
| 216 | + c.evaluate_cmo() # slightly slow | |
| 217 | + c.evaluate_laguerre() # slow | |
| 218 | + | |
| 219 | + dataframe['consensus_buy'] = c.score()['buy'] | |
| 220 | + dataframe['consensus_sell'] = c.score()['sell'] | |
| 221 | + | |
| 222 | + # Trend Indicators for ROI | |
| 223 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 224 | + | |
| 225 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 226 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 227 | + | |
| 228 | + # Base pair informative timeframe indicators | |
| 229 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 230 | + | |
| 231 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 232 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 233 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 234 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 235 | + | |
| 236 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 237 | + | |
| 238 | + # Other stake specific informative indicators | |
| 239 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 240 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 241 | + coin, stake = metadata['pair'].split('/') | |
| 242 | + fiat = self.custom_fiat | |
| 243 | + coin_fiat = f"{coin}/{fiat}" | |
| 244 | + stake_fiat = f"{stake}/{fiat}" | |
| 245 | + | |
| 246 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 247 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 248 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 249 | + | |
| 250 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 251 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 252 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 253 | + | |
| 254 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 255 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 256 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 257 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 258 | + | |
| 259 | + # Informatives for BTC/STAKE if not in whitelist | |
| 260 | + else: | |
| 261 | + pairs = self.dp.current_whitelist() | |
| 262 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 263 | + if not btc_stake in pairs: | |
| 264 | + # BTC/STAKE - Base Timeframe | |
| 265 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 266 | + cbtc = Consensus(btc_stake_tf) | |
| 267 | + | |
| 268 | + cbtc.evaluate_tema(period=12) | |
| 269 | + cbtc.evaluate_ema(period=8) | |
| 270 | + cbtc.evaluate_ema(period=13) | |
| 271 | + cbtc.evaluate_ema(period=21) | |
| 272 | + cbtc.evaluate_ema(period=34) | |
| 273 | + cbtc.evaluate_ema(period=55) | |
| 274 | + cbtc.evaluate_ichimoku() | |
| 275 | + cbtc.evaluate_vwma(period=20) | |
| 276 | + cbtc.evaluate_rsi(period=14) | |
| 277 | + cbtc.evaluate_stoch() | |
| 278 | + cbtc.evaluate_cci() | |
| 279 | + cbtc.evaluate_adx() | |
| 280 | + cbtc.evaluate_macd() | |
| 281 | + cbtc.evaluate_momentum() | |
| 282 | + cbtc.evaluate_williams() | |
| 283 | + cbtc.evaluate_macd_cross_over() | |
| 284 | + cbtc.evaluate_osc() | |
| 285 | + cbtc.evaluate_cmf() | |
| 286 | + cbtc.evaluate_cmo() | |
| 287 | + cbtc.evaluate_laguerre() | |
| 288 | + | |
| 289 | + dataframe['BTC_consensus_buy'] = cbtc.score()['buy'] | |
| 290 | + | |
| 291 | + # BTC/STAKE - Informative Timeframe | |
| 292 | + # btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 293 | + # dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 294 | + | |
| 295 | + return dataframe | |
| 296 | + | |
| 297 | + """ | |
| 298 | + Buy Signal | |
| 299 | + """ | |
| 300 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 301 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 302 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 303 | + conditions = [] | |
| 304 | + | |
| 305 | + # If active trade, look at trend to persist a buy signal for ignore_roi_if_buy_signal | |
| 306 | + if trade_data['active_trade']: | |
| 307 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 308 | + rmi_grow = cta.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 309 | + | |
| 310 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 311 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 312 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 313 | + | |
| 314 | + # Standard signals for entering new trades | |
| 315 | + else: | |
| 316 | + | |
| 317 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 318 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 319 | + conditions.append( | |
| 320 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 321 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 322 | + ) | |
| 323 | + | |
| 324 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 325 | + conditions.append( | |
| 326 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 327 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 328 | + ) | |
| 329 | + | |
| 330 | + conditions.append(dataframe['consensus_buy'] > params['consensus-buy']) | |
| 331 | + | |
| 332 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 333 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 334 | + conditions.append( | |
| 335 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 336 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 337 | + ) | |
| 338 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 339 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 340 | + else: | |
| 341 | + pairs = self.dp.current_whitelist() | |
| 342 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 343 | + if not btc_stake in pairs: | |
| 344 | + conditions.append(dataframe['BTC_consensus_buy'] > params['xbtc-consensus-buy']) | |
| 345 | + | |
| 346 | + # Applies to active or new trades | |
| 347 | + conditions.append(dataframe['volume'].gt(0)) | |
| 348 | + | |
| 349 | + if conditions: | |
| 350 | + dataframe.loc[ | |
| 351 | + reduce(lambda x, y: x & y, conditions), | |
| 352 | + 'buy'] = 1 | |
| 353 | + | |
| 354 | + return dataframe | |
| 355 | + | |
| 356 | + """ | |
| 357 | + Sell Signal | |
| 358 | + """ | |
| 359 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 360 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 361 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 362 | + conditions = [] | |
| 363 | + | |
| 364 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 365 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 366 | + if trade_data['active_trade']: | |
| 367 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 368 | + # a trade to go into the negative a little bit before we react to sell. | |
| 369 | + loss_cutoff = cta.linear_growth(-0.03, 0, 0, 240, trade_data['open_minutes']) | |
| 370 | + | |
| 371 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 372 | + | |
| 373 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 374 | + if trade_data['other_trades']: | |
| 375 | + if trade_data['free_slots'] > 0: | |
| 376 | + # If the average of all our other trades is below a certain threshold based | |
| 377 | + # on free slots available, hold and wait for market recovery. | |
| 378 | + hold_pct = (1/trade_data['free_slots']) * -0.04 | |
| 379 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 380 | + else: | |
| 381 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 382 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 383 | + | |
| 384 | + conditions.append(dataframe['consensus_sell'] > params['consensus-sell']) | |
| 385 | + | |
| 386 | + if conditions: | |
| 387 | + dataframe.loc[ | |
| 388 | + reduce(lambda x, y: x & y, conditions), | |
| 389 | + 'sell'] = 1 | |
| 390 | + | |
| 391 | + return dataframe | |
| 392 | + | |
| 393 | + """ | |
| 394 | + Custom Stoploss | |
| 395 | + """ | |
| 396 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 397 | + cs = self.custom_stop | |
| 398 | + | |
| 399 | + open_minutes: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 400 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 401 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 402 | + profit_diff = current_profit - min_profit | |
| 403 | + | |
| 404 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 405 | + if cs['pos-trail'] == True: | |
| 406 | + if current_profit > cs['pos-threshold']: | |
| 407 | + return current_profit - cs['pos-trail-dist'] | |
| 408 | + | |
| 409 | + # decay-only is literally just the decay, decay uses the decay unless profit is increasing | |
| 410 | + if cs['mode'] == 'decay' or cs['mode'] == 'decay-only': | |
| 411 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], open_minutes) | |
| 412 | + if cs['mode'] == 'decay-only': | |
| 413 | + return decay_stoploss | |
| 414 | + | |
| 415 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 416 | + if (current_profit > min_profit) and current_profit < cs['cur-threshold']: | |
| 417 | + if profit_diff > cs['cur-min-diff']: | |
| 418 | + return min_profit | |
| 419 | + return -1 | |
| 420 | + | |
| 421 | + return decay_stoploss | |
| 422 | + | |
| 423 | + if cs['mode'] == 'dynamic': | |
| 424 | + if not pair in cs: | |
| 425 | + cs[pair] = {} | |
| 426 | + | |
| 427 | + cs[pair]['current_profit'] | |
| 428 | + cs[pair]['min_profit'] | |
| 429 | + cs[pair]['max_profit'] | |
| 430 | + | |
| 431 | + # if all else fails, keep the stoploss where it is | |
| 432 | + return -1 | |
| 433 | + | |
| 434 | + """ | |
| 435 | + Trade Timeout Overloads | |
| 436 | + """ | |
| 437 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 438 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 439 | + ob = self.dp.orderbook(pair, 1) | |
| 440 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 441 | + if current_price > order['price'] * 1.01: | |
| 442 | + return True | |
| 443 | + return False | |
| 444 | + | |
| 445 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 446 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 447 | + ob = self.dp.orderbook(pair, 1) | |
| 448 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 449 | + if current_price < order['price'] * 0.99: | |
| 450 | + return True | |
| 451 | + return False | |
| 452 | + | |
| 453 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 454 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 455 | + ob = self.dp.orderbook(pair, 1) | |
| 456 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 457 | + if current_price > rate * 1.01: | |
| 458 | + return False | |
| 459 | + return True | |
| 460 | + | |
| 461 | + """ | |
| 462 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 463 | + """ | |
| 464 | + def min_roi_reached_dynamic(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 465 | + | |
| 466 | + dynamic_roi = self.dynamic_roi | |
| 467 | + minimal_roi = self.minimal_roi | |
| 468 | + | |
| 469 | + if not dynamic_roi: | |
| 470 | + return None, None | |
| 471 | + | |
| 472 | + if 'dynamic_roi_type' in dynamic_roi and dynamic_roi['dynamic_roi_type'] \ | |
| 473 | + in ['linear', 'exponential', 'connect']: | |
| 474 | + roi_type = dynamic_roi['dynamic_roi_type'] | |
| 475 | + # linear decay: f(t) = start - (rate * t) | |
| 476 | + if roi_type == 'linear': | |
| 477 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 478 | + 'dynamic_roi_time' in dynamic_roi: | |
| 479 | + start = dynamic_roi['dynamic_roi_start'] | |
| 480 | + end = dynamic_roi['dynamic_roi_end'] | |
| 481 | + time = dynamic_roi['dynamic_roi_time'] | |
| 482 | + rate = (start - end) / time | |
| 483 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 484 | + else: | |
| 485 | + return None, None | |
| 486 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 487 | + elif roi_type == 'exponential': | |
| 488 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 489 | + 'dynamic_roi_rate' in dynamic_roi: | |
| 490 | + start = dynamic_roi['dynamic_roi_start'] | |
| 491 | + end = dynamic_roi['dynamic_roi_end'] | |
| 492 | + rate = dynamic_roi['dynamic_roi_rate'] | |
| 493 | + min_roi = max(end, start * np.exp(-rate*trade_dur)) | |
| 494 | + else: | |
| 495 | + return None, None | |
| 496 | + # "connect the dots" between the points on the minima_roi table | |
| 497 | + elif roi_type == 'connect': | |
| 498 | + if not minimal_roi: | |
| 499 | + return None, None | |
| 500 | + # figure out where we are in the defined roi table | |
| 501 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 502 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 503 | + # if we are past the final point in the table, use that key/vaule pair | |
| 504 | + if not past_roi: | |
| 505 | + return None, None | |
| 506 | + current_entry = max(past_roi) | |
| 507 | + if not next_roi: | |
| 508 | + return current_entry, minimal_roi[current_entry] | |
| 509 | + next_entry = min(next_roi) | |
| 510 | + # use the slope-intercept formula between the two points | |
| 511 | + # y = mx + b | |
| 512 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 513 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 514 | + m = (y1-y2)/(x1-x2) | |
| 515 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 516 | + min_roi = (m * trade_dur) + b | |
| 517 | + else: | |
| 518 | + return None, None | |
| 519 | + | |
| 520 | + return trade_dur, min_roi | |
| 521 | + | |
| 522 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 523 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 524 | + | |
| 525 | + if self.dynamic_roi and 'dynamic_roi_enabled' in self.dynamic_roi \ | |
| 526 | + and self.dynamic_roi['dynamic_roi_enabled']: | |
| 527 | + _, roi = self.min_roi_reached_dynamic(trade_dur) | |
| 528 | + else: | |
| 529 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 530 | + if roi is None: | |
| 531 | + return False | |
| 532 | + else: | |
| 533 | + return current_profit > roi | |
| 534 | + | |
| 535 | + """ | |
| 536 | + Custom Methods for Strategy Parameters, Trade, and Price Data | |
| 537 | + Consider splitting this out into a helper file. | |
| 538 | + """ | |
| 539 | + def populate_trades(self, pair: str) -> dict: | |
| 540 | + """ | |
| 541 | + Query the database and populate the custom_trade_info dict. | |
| 542 | + """ | |
| 543 | + if not pair in self.custom_trade_info: | |
| 544 | + self.custom_trade_info[pair] = {} | |
| 545 | + | |
| 546 | + trade_data = {} | |
| 547 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 548 | + | |
| 549 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 550 | + | |
| 551 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 552 | + | |
| 553 | + if active_trade: | |
| 554 | + current_rate = self.get_current_price(pair, True) | |
| 555 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 556 | + | |
| 557 | + present = arrow.utcnow() | |
| 558 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 559 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 560 | + | |
| 561 | + trade_data['active_trade'] = True | |
| 562 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 563 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 564 | + trade_data['open_minutes'] : int = open_minutes | |
| 565 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 566 | + else: | |
| 567 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 568 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 569 | + | |
| 570 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 571 | + | |
| 572 | + if other_trades: | |
| 573 | + trade_data['other_trades'] = True | |
| 574 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 575 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 576 | + if trade_data['current_profit'] < min(other_profit): | |
| 577 | + trade_data['biggest_loser'] = True | |
| 578 | + else: | |
| 579 | + trade_data['avg_other_profit'] = 0 | |
| 580 | + | |
| 581 | + open_trades = len(Trade.get_open_trades()) | |
| 582 | + # this was lazy. | |
| 583 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 584 | + | |
| 585 | + return trade_data | |
| 586 | + | |
| 587 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 588 | + """ | |
| 589 | + Query the exchange for current price information, used in profit calculations. | |
| 590 | + Implements a cache to prevent excessive api calls. | |
| 591 | + """ | |
| 592 | + if not refresh: | |
| 593 | + rate = self.custom_current_price_cache.get(pair) | |
| 594 | + if rate: | |
| 595 | + return rate | |
| 596 | + | |
| 597 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 598 | + if ask_strategy.get('use_order_book', False): | |
| 599 | + ob = self.dp.orderbook(pair, 1) | |
| 600 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 601 | + else: | |
| 602 | + ticker = self.dp.ticker(pair) | |
| 603 | + rate = ticker['last'] | |
| 604 | + | |
| 605 | + self.custom_current_price_cache[pair] = rate | |
| 606 | + return rate | |
| 607 | + | |
| 608 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 609 | + """ | |
| 610 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 611 | + TODO: | |
| 612 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 613 | + """ | |
| 614 | + buy_params = self.buy_params | |
| 615 | + sell_params = self.sell_params | |
| 616 | + | |
| 617 | + if self.custom_pair_params: | |
| 618 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 619 | + if custom_params['buy_params']: | |
| 620 | + buy_params = custom_params['buy_params'] | |
| 621 | + if custom_params['sell_params']: | |
| 622 | + sell_params = custom_params['sell_params'] | |
| 623 | + | |
| 624 | + if side == 'sell': | |
| 625 | + return sell_params | |
| 626 | + | |
| 627 | + return buy_params | |
| 628 | + | |
| 629 | +# Sub-strategy with parameters specific to BTC stake | |
| 630 | +class SolipsisCon_BTC(SolipsisCon): | |
| 631 | + | |
| 632 | + timeframe = '1h' | |
| 633 | + inf_timeframe = '4h' | |
| 634 | + | |
| 635 | + buy_params = { | |
| 636 | + 'inf-rsi': 64, | |
| 637 | + 'mp': 55, | |
| 638 | + 'rmi-fast': 31, | |
| 639 | + 'rmi-slow': 16, | |
| 640 | + 'xinf-stake-rmi': 67, | |
| 641 | + 'xtf-fiat-rsi': 17, | |
| 642 | + 'xtf-stake-rsi': 57 | |
| 643 | + } | |
| 644 | + | |
| 645 | + minimal_roi = { | |
| 646 | + "0": 0.05, | |
| 647 | + "240": 0.025, | |
| 648 | + "1440": 0.01, | |
| 649 | + "4320": 0 | |
| 650 | + } | |
| 651 | + | |
| 652 | + stoploss = -0.30 | |
| 653 | + use_custom_stoploss = False | |
| 654 | + | |
| 655 | +# Sub-strategy with parameters specific to ETH stake | |
| 656 | +class Solipsis_ETH(SolipsisCon): | |
| 657 | + | |
| 658 | + timeframe = '1h' | |
| 659 | + inf_timeframe = '4h' | |
| 660 | + | |
| 661 | + buy_params = { | |
| 662 | + 'inf-rsi': 13, | |
| 663 | + 'inf-stake-rmi': 69, | |
| 664 | + 'mp': 40, | |
| 665 | + 'rmi-fast': 42, | |
| 666 | + 'rmi-slow': 17, | |
| 667 | + 'tf-fiat-rsi': 15, | |
| 668 | + 'tf-stake-rsi': 92 | |
| 669 | + } | |
| 670 | + | |
| 671 | + minimal_roi = { | |
| 672 | + "0": 0.05, | |
| 673 | + "240": 0.025, | |
| 674 | + "1440": 0.01, | |
| 675 | + "4320": 0 | |
| 676 | + } | |
| 677 | + | |
| 678 | + stoploss = -0.30 | |
| 679 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-Con.py +679 −0
| @@ -0,0 +1,679 @@ | ||
| 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 | |
| 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 statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | +from technical.consensus import Consensus | |
| 16 | + | |
| 17 | +# Get rid of pandas warnings during backtesting | |
| 18 | +import pandas as pd | |
| 19 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 20 | + | |
| 21 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 22 | +import sys | |
| 23 | +from pathlib import Path | |
| 24 | +sys.path.append(str(Path(__file__).parent)) | |
| 25 | + | |
| 26 | +import custom_indicators as cta | |
| 27 | + | |
| 28 | +""" | |
| 29 | +TODO: | |
| 30 | + - Continue to hunt for a better all around buy signal. | |
| 31 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 32 | + - ADR guards are helping but need to reduce losing trade counts. | |
| 33 | + - Need to reduce drawdown. | |
| 34 | + - Tweak ROI Trend Ride | |
| 35 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 36 | + - Maybe further exploit the ROI table itself using trade data? | |
| 37 | + - Per-pair automatic ROI points based on ADR/ATR or something similar? | |
| 38 | + - Tweak sell signal | |
| 39 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 40 | + - Further enchance and optimize custom stop loss | |
| 41 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 42 | + | |
| 43 | +STRATEGY NOTES: | |
| 44 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 45 | + --enable-protections as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 46 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 47 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 48 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 49 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 50 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 51 | + - If running backtest/hyperopt around the portion of the sell signal that is testable, keep in mind in live/dry | |
| 52 | + it will not sell nearly as frequently due to the profit guard and other_profit / free_slot guards. | |
| 53 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 54 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 55 | + ROI based sells will be higher than the backtest shows. | |
| 56 | + - It is *not* worthwhile to hyperopt for roi as it does not take into account the roi trend ride we are doing and | |
| 57 | + having ROI points that are too high will sort of be counter-productive to how this strategy works even if it seems | |
| 58 | + to produce better results in backtesting. | |
| 59 | + - It *might be* worthwhile to hyperopt the stoploss but we can't hyperopt any of the parameters in the custom stoploss | |
| 60 | + so hyperopting the stoploss is only changing the initial position relative to the other settings. | |
| 61 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 62 | + - The custom stoploss has settings to emulate the same functionality however. | |
| 63 | + - It is *highly* recommended to backtest with use_sell_signal = False because it will not behave remotely the same in dry/live | |
| 64 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only or 'buy sell' and at least 1000 total epochs several times. | |
| 65 | + | |
| 66 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 67 | + | |
| 68 | + custom_pair_params = [ | |
| 69 | + { | |
| 70 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 71 | + 'buy_params': {}, | |
| 72 | + 'sell_params': {} | |
| 73 | + } | |
| 74 | + ] | |
| 75 | + | |
| 76 | +""" | |
| 77 | + | |
| 78 | +class SolipsisCon(IStrategy): | |
| 79 | + | |
| 80 | + # Recommended for USD/USDT/etc. | |
| 81 | + timeframe = '5m' | |
| 82 | + inf_timeframe = '1h' | |
| 83 | + | |
| 84 | + buy_params = { | |
| 85 | + 'consensus-buy': 4, | |
| 86 | + 'inf-guard': 'both', | |
| 87 | + 'inf-pct-adr-bot': 0.06607, | |
| 88 | + 'inf-pct-adr-top': 0.81639, | |
| 89 | + 'xbtc-base-enable': True, | |
| 90 | + 'xbtc-consensus-buy': 37, | |
| 91 | + 'xbtc-inf-consensus-buy': 29, | |
| 92 | + 'xbtc-inf-enable': False, | |
| 93 | + 'xtra-base-fiat-rmi': 34, | |
| 94 | + 'xtra-base-stake-rmi': 38, | |
| 95 | + 'xtra-inf-stake-rmi': 52 | |
| 96 | + } | |
| 97 | + | |
| 98 | + sell_params = { | |
| 99 | + 'consensus-sell': 62 | |
| 100 | + } | |
| 101 | + | |
| 102 | + # Custom buy/sell parameters per pair | |
| 103 | + custom_pair_params = [] | |
| 104 | + | |
| 105 | + # Recommended on 5m timeframe | |
| 106 | + minimal_roi = { | |
| 107 | + "0": 0.05, | |
| 108 | + "30": 0.025, | |
| 109 | + "120": 0.01, | |
| 110 | + "360": 0.01, | |
| 111 | + "720": 0.005, | |
| 112 | + "1440": 0 | |
| 113 | + } | |
| 114 | + | |
| 115 | + # Optional | |
| 116 | + dynamic_roi = { | |
| 117 | + 'dynamic_roi_enabled': True, | |
| 118 | + 'dynamic_roi_type': 'connect' | |
| 119 | + } | |
| 120 | + | |
| 121 | + stoploss = -0.30 | |
| 122 | + | |
| 123 | + # Optional | |
| 124 | + use_custom_stoploss = False | |
| 125 | + custom_stop = { | |
| 126 | + 'mode': 'decay', # decay, decay-only | |
| 127 | + # Linear Decay Parameters | |
| 128 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 129 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 130 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 131 | + 'decay-end': -0.03, # ending value | |
| 132 | + # Current vs Min Profit | |
| 133 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 134 | + 'cur-threshold': 0, # how far negative should current profit be before we consider moving it up based on cur/min | |
| 135 | + # Positive Trailing | |
| 136 | + 'pos-trail': False, # enable trailing once positive | |
| 137 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 138 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 139 | + } | |
| 140 | + | |
| 141 | + # Recommended | |
| 142 | + use_sell_signal = True | |
| 143 | + sell_profit_only = False | |
| 144 | + ignore_roi_if_buy_signal = True | |
| 145 | + | |
| 146 | + # Required | |
| 147 | + startup_candle_count: int = 72 | |
| 148 | + process_only_new_candles = False | |
| 149 | + | |
| 150 | + # Strategy Specific Variable Storage | |
| 151 | + custom_trade_info = {} | |
| 152 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 153 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 154 | + | |
| 155 | + """ | |
| 156 | + Informative Pair Definitions | |
| 157 | + """ | |
| 158 | + def informative_pairs(self): | |
| 159 | + pairs = self.dp.current_whitelist() | |
| 160 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 161 | + | |
| 162 | + # add extra informative pairs if the stake is BTC or ETH | |
| 163 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 164 | + for pair in pairs: | |
| 165 | + coin, stake = pair.split('/') | |
| 166 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 167 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 168 | + | |
| 169 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 170 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 171 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 172 | + # if BTC/STAKE is not in whitelist, add it as an informative pair | |
| 173 | + else: | |
| 174 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 175 | + if not btc_stake in pairs: | |
| 176 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 177 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 178 | + | |
| 179 | + return informative_pairs | |
| 180 | + | |
| 181 | + """ | |
| 182 | + Indicator Definitions | |
| 183 | + """ | |
| 184 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 185 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 186 | + | |
| 187 | + c = Consensus(dataframe) | |
| 188 | + | |
| 189 | + # Overlap / MA's | |
| 190 | + c.evaluate_tema(period=12) | |
| 191 | + c.evaluate_ema(period=8) | |
| 192 | + c.evaluate_ema(period=13) | |
| 193 | + c.evaluate_ema(period=21) | |
| 194 | + c.evaluate_ema(period=34) | |
| 195 | + c.evaluate_ema(period=55) | |
| 196 | + c.evaluate_ichimoku() # slightly slow | |
| 197 | + c.evaluate_hull() # very slow | |
| 198 | + c.evaluate_vwma(period=20) | |
| 199 | + | |
| 200 | + # Oscillators | |
| 201 | + c.evaluate_rsi(period=14) | |
| 202 | + c.evaluate_stoch() | |
| 203 | + c.evaluate_cci() # slightly slow | |
| 204 | + c.evaluate_adx() | |
| 205 | + c.evaluate_macd() | |
| 206 | + c.evaluate_momentum() | |
| 207 | + c.evaluate_williams() | |
| 208 | + # c.evaluate_ultimate_oscilator() # extremely slow | |
| 209 | + # missing: awesome osc | |
| 210 | + # missing: bull bear | |
| 211 | + # missing: stoch rsi | |
| 212 | + | |
| 213 | + c.evaluate_macd_cross_over() | |
| 214 | + c.evaluate_osc() | |
| 215 | + c.evaluate_cmf() | |
| 216 | + c.evaluate_cmo() # slightly slow | |
| 217 | + c.evaluate_laguerre() # slow | |
| 218 | + | |
| 219 | + dataframe['consensus_buy'] = c.score()['buy'] | |
| 220 | + dataframe['consensus_sell'] = c.score()['sell'] | |
| 221 | + | |
| 222 | + # Trend Indicators for ROI | |
| 223 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 224 | + | |
| 225 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 226 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 227 | + | |
| 228 | + # Base pair informative timeframe indicators | |
| 229 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 230 | + | |
| 231 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 232 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 233 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 234 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 235 | + | |
| 236 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 237 | + | |
| 238 | + # Other stake specific informative indicators | |
| 239 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 240 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 241 | + coin, stake = metadata['pair'].split('/') | |
| 242 | + fiat = self.custom_fiat | |
| 243 | + coin_fiat = f"{coin}/{fiat}" | |
| 244 | + stake_fiat = f"{stake}/{fiat}" | |
| 245 | + | |
| 246 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 247 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 248 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 249 | + | |
| 250 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 251 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 252 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 253 | + | |
| 254 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 255 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 256 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 257 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 258 | + | |
| 259 | + # Informatives for BTC/STAKE if not in whitelist | |
| 260 | + else: | |
| 261 | + pairs = self.dp.current_whitelist() | |
| 262 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 263 | + if not btc_stake in pairs: | |
| 264 | + # BTC/STAKE - Base Timeframe | |
| 265 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 266 | + cbtc = Consensus(btc_stake_tf) | |
| 267 | + | |
| 268 | + cbtc.evaluate_tema(period=12) | |
| 269 | + cbtc.evaluate_ema(period=8) | |
| 270 | + cbtc.evaluate_ema(period=13) | |
| 271 | + cbtc.evaluate_ema(period=21) | |
| 272 | + cbtc.evaluate_ema(period=34) | |
| 273 | + cbtc.evaluate_ema(period=55) | |
| 274 | + cbtc.evaluate_ichimoku() | |
| 275 | + cbtc.evaluate_vwma(period=20) | |
| 276 | + cbtc.evaluate_rsi(period=14) | |
| 277 | + cbtc.evaluate_stoch() | |
| 278 | + cbtc.evaluate_cci() | |
| 279 | + cbtc.evaluate_adx() | |
| 280 | + cbtc.evaluate_macd() | |
| 281 | + cbtc.evaluate_momentum() | |
| 282 | + cbtc.evaluate_williams() | |
| 283 | + cbtc.evaluate_macd_cross_over() | |
| 284 | + cbtc.evaluate_osc() | |
| 285 | + cbtc.evaluate_cmf() | |
| 286 | + cbtc.evaluate_cmo() | |
| 287 | + cbtc.evaluate_laguerre() | |
| 288 | + | |
| 289 | + dataframe['BTC_consensus_buy'] = cbtc.score()['buy'] | |
| 290 | + | |
| 291 | + # BTC/STAKE - Informative Timeframe | |
| 292 | + # btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 293 | + # dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 294 | + | |
| 295 | + return dataframe | |
| 296 | + | |
| 297 | + """ | |
| 298 | + Buy Signal | |
| 299 | + """ | |
| 300 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 301 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 302 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 303 | + conditions = [] | |
| 304 | + | |
| 305 | + # If active trade, look at trend to persist a buy signal for ignore_roi_if_buy_signal | |
| 306 | + if trade_data['active_trade']: | |
| 307 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 308 | + rmi_grow = cta.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 309 | + | |
| 310 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 311 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 312 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 313 | + | |
| 314 | + # Standard signals for entering new trades | |
| 315 | + else: | |
| 316 | + | |
| 317 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 318 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 319 | + conditions.append( | |
| 320 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 321 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 322 | + ) | |
| 323 | + | |
| 324 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 325 | + conditions.append( | |
| 326 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 327 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 328 | + ) | |
| 329 | + | |
| 330 | + conditions.append(dataframe['consensus_buy'] > params['consensus-buy']) | |
| 331 | + | |
| 332 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 333 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 334 | + conditions.append( | |
| 335 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 336 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 337 | + ) | |
| 338 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 339 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 340 | + else: | |
| 341 | + pairs = self.dp.current_whitelist() | |
| 342 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 343 | + if not btc_stake in pairs: | |
| 344 | + conditions.append(dataframe['BTC_consensus_buy'] > params['xbtc-consensus-buy']) | |
| 345 | + | |
| 346 | + # Applies to active or new trades | |
| 347 | + conditions.append(dataframe['volume'].gt(0)) | |
| 348 | + | |
| 349 | + if conditions: | |
| 350 | + dataframe.loc[ | |
| 351 | + reduce(lambda x, y: x & y, conditions), | |
| 352 | + 'buy'] = 1 | |
| 353 | + | |
| 354 | + return dataframe | |
| 355 | + | |
| 356 | + """ | |
| 357 | + Sell Signal | |
| 358 | + """ | |
| 359 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 360 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 361 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 362 | + conditions = [] | |
| 363 | + | |
| 364 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 365 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 366 | + if trade_data['active_trade']: | |
| 367 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 368 | + # a trade to go into the negative a little bit before we react to sell. | |
| 369 | + loss_cutoff = cta.linear_growth(-0.03, 0, 0, 240, trade_data['open_minutes']) | |
| 370 | + | |
| 371 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 372 | + | |
| 373 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 374 | + if trade_data['other_trades']: | |
| 375 | + if trade_data['free_slots'] > 0: | |
| 376 | + # If the average of all our other trades is below a certain threshold based | |
| 377 | + # on free slots available, hold and wait for market recovery. | |
| 378 | + hold_pct = (1/trade_data['free_slots']) * -0.04 | |
| 379 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 380 | + else: | |
| 381 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 382 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 383 | + | |
| 384 | + conditions.append(dataframe['consensus_sell'] > params['consensus-sell']) | |
| 385 | + | |
| 386 | + if conditions: | |
| 387 | + dataframe.loc[ | |
| 388 | + reduce(lambda x, y: x & y, conditions), | |
| 389 | + 'sell'] = 1 | |
| 390 | + | |
| 391 | + return dataframe | |
| 392 | + | |
| 393 | + """ | |
| 394 | + Custom Stoploss | |
| 395 | + """ | |
| 396 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 397 | + cs = self.custom_stop | |
| 398 | + | |
| 399 | + open_minutes: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 400 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 401 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 402 | + profit_diff = current_profit - min_profit | |
| 403 | + | |
| 404 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 405 | + if cs['pos-trail'] == True: | |
| 406 | + if current_profit > cs['pos-threshold']: | |
| 407 | + return current_profit - cs['pos-trail-dist'] | |
| 408 | + | |
| 409 | + # decay-only is literally just the decay, decay uses the decay unless profit is increasing | |
| 410 | + if cs['mode'] == 'decay' or cs['mode'] == 'decay-only': | |
| 411 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], open_minutes) | |
| 412 | + if cs['mode'] == 'decay-only': | |
| 413 | + return decay_stoploss | |
| 414 | + | |
| 415 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 416 | + if (current_profit > min_profit) and current_profit < cs['cur-threshold']: | |
| 417 | + if profit_diff > cs['cur-min-diff']: | |
| 418 | + return min_profit | |
| 419 | + return -1 | |
| 420 | + | |
| 421 | + return decay_stoploss | |
| 422 | + | |
| 423 | + if cs['mode'] == 'dynamic': | |
| 424 | + if not pair in cs: | |
| 425 | + cs[pair] = {} | |
| 426 | + | |
| 427 | + cs[pair]['current_profit'] | |
| 428 | + cs[pair]['min_profit'] | |
| 429 | + cs[pair]['max_profit'] | |
| 430 | + | |
| 431 | + # if all else fails, keep the stoploss where it is | |
| 432 | + return -1 | |
| 433 | + | |
| 434 | + """ | |
| 435 | + Trade Timeout Overloads | |
| 436 | + """ | |
| 437 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 438 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 439 | + ob = self.dp.orderbook(pair, 1) | |
| 440 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 441 | + if current_price > order['price'] * 1.01: | |
| 442 | + return True | |
| 443 | + return False | |
| 444 | + | |
| 445 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 446 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 447 | + ob = self.dp.orderbook(pair, 1) | |
| 448 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 449 | + if current_price < order['price'] * 0.99: | |
| 450 | + return True | |
| 451 | + return False | |
| 452 | + | |
| 453 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 454 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 455 | + ob = self.dp.orderbook(pair, 1) | |
| 456 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 457 | + if current_price > rate * 1.01: | |
| 458 | + return False | |
| 459 | + return True | |
| 460 | + | |
| 461 | + """ | |
| 462 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 463 | + """ | |
| 464 | + def min_roi_reached_dynamic(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 465 | + | |
| 466 | + dynamic_roi = self.dynamic_roi | |
| 467 | + minimal_roi = self.minimal_roi | |
| 468 | + | |
| 469 | + if not dynamic_roi: | |
| 470 | + return None, None | |
| 471 | + | |
| 472 | + if 'dynamic_roi_type' in dynamic_roi and dynamic_roi['dynamic_roi_type'] \ | |
| 473 | + in ['linear', 'exponential', 'connect']: | |
| 474 | + roi_type = dynamic_roi['dynamic_roi_type'] | |
| 475 | + # linear decay: f(t) = start - (rate * t) | |
| 476 | + if roi_type == 'linear': | |
| 477 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 478 | + 'dynamic_roi_time' in dynamic_roi: | |
| 479 | + start = dynamic_roi['dynamic_roi_start'] | |
| 480 | + end = dynamic_roi['dynamic_roi_end'] | |
| 481 | + time = dynamic_roi['dynamic_roi_time'] | |
| 482 | + rate = (start - end) / time | |
| 483 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 484 | + else: | |
| 485 | + return None, None | |
| 486 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 487 | + elif roi_type == 'exponential': | |
| 488 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 489 | + 'dynamic_roi_rate' in dynamic_roi: | |
| 490 | + start = dynamic_roi['dynamic_roi_start'] | |
| 491 | + end = dynamic_roi['dynamic_roi_end'] | |
| 492 | + rate = dynamic_roi['dynamic_roi_rate'] | |
| 493 | + min_roi = max(end, start * np.exp(-rate*trade_dur)) | |
| 494 | + else: | |
| 495 | + return None, None | |
| 496 | + # "connect the dots" between the points on the minima_roi table | |
| 497 | + elif roi_type == 'connect': | |
| 498 | + if not minimal_roi: | |
| 499 | + return None, None | |
| 500 | + # figure out where we are in the defined roi table | |
| 501 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 502 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 503 | + # if we are past the final point in the table, use that key/vaule pair | |
| 504 | + if not past_roi: | |
| 505 | + return None, None | |
| 506 | + current_entry = max(past_roi) | |
| 507 | + if not next_roi: | |
| 508 | + return current_entry, minimal_roi[current_entry] | |
| 509 | + next_entry = min(next_roi) | |
| 510 | + # use the slope-intercept formula between the two points | |
| 511 | + # y = mx + b | |
| 512 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 513 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 514 | + m = (y1-y2)/(x1-x2) | |
| 515 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 516 | + min_roi = (m * trade_dur) + b | |
| 517 | + else: | |
| 518 | + return None, None | |
| 519 | + | |
| 520 | + return trade_dur, min_roi | |
| 521 | + | |
| 522 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 523 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 524 | + | |
| 525 | + if self.dynamic_roi and 'dynamic_roi_enabled' in self.dynamic_roi \ | |
| 526 | + and self.dynamic_roi['dynamic_roi_enabled']: | |
| 527 | + _, roi = self.min_roi_reached_dynamic(trade_dur) | |
| 528 | + else: | |
| 529 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 530 | + if roi is None: | |
| 531 | + return False | |
| 532 | + else: | |
| 533 | + return current_profit > roi | |
| 534 | + | |
| 535 | + """ | |
| 536 | + Custom Methods for Strategy Parameters, Trade, and Price Data | |
| 537 | + Consider splitting this out into a helper file. | |
| 538 | + """ | |
| 539 | + def populate_trades(self, pair: str) -> dict: | |
| 540 | + """ | |
| 541 | + Query the database and populate the custom_trade_info dict. | |
| 542 | + """ | |
| 543 | + if not pair in self.custom_trade_info: | |
| 544 | + self.custom_trade_info[pair] = {} | |
| 545 | + | |
| 546 | + trade_data = {} | |
| 547 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 548 | + | |
| 549 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 550 | + | |
| 551 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 552 | + | |
| 553 | + if active_trade: | |
| 554 | + current_rate = self.get_current_price(pair, True) | |
| 555 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 556 | + | |
| 557 | + present = arrow.utcnow() | |
| 558 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 559 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 560 | + | |
| 561 | + trade_data['active_trade'] = True | |
| 562 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 563 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 564 | + trade_data['open_minutes'] : int = open_minutes | |
| 565 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 566 | + else: | |
| 567 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 568 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 569 | + | |
| 570 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 571 | + | |
| 572 | + if other_trades: | |
| 573 | + trade_data['other_trades'] = True | |
| 574 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 575 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 576 | + if trade_data['current_profit'] < min(other_profit): | |
| 577 | + trade_data['biggest_loser'] = True | |
| 578 | + else: | |
| 579 | + trade_data['avg_other_profit'] = 0 | |
| 580 | + | |
| 581 | + open_trades = len(Trade.get_open_trades()) | |
| 582 | + # this was lazy. | |
| 583 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 584 | + | |
| 585 | + return trade_data | |
| 586 | + | |
| 587 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 588 | + """ | |
| 589 | + Query the exchange for current price information, used in profit calculations. | |
| 590 | + Implements a cache to prevent excessive api calls. | |
| 591 | + """ | |
| 592 | + if not refresh: | |
| 593 | + rate = self.custom_current_price_cache.get(pair) | |
| 594 | + if rate: | |
| 595 | + return rate | |
| 596 | + | |
| 597 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 598 | + if ask_strategy.get('use_order_book', False): | |
| 599 | + ob = self.dp.orderbook(pair, 1) | |
| 600 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 601 | + else: | |
| 602 | + ticker = self.dp.ticker(pair) | |
| 603 | + rate = ticker['last'] | |
| 604 | + | |
| 605 | + self.custom_current_price_cache[pair] = rate | |
| 606 | + return rate | |
| 607 | + | |
| 608 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 609 | + """ | |
| 610 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 611 | + TODO: | |
| 612 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 613 | + """ | |
| 614 | + buy_params = self.buy_params | |
| 615 | + sell_params = self.sell_params | |
| 616 | + | |
| 617 | + if self.custom_pair_params: | |
| 618 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 619 | + if custom_params['buy_params']: | |
| 620 | + buy_params = custom_params['buy_params'] | |
| 621 | + if custom_params['sell_params']: | |
| 622 | + sell_params = custom_params['sell_params'] | |
| 623 | + | |
| 624 | + if side == 'sell': | |
| 625 | + return sell_params | |
| 626 | + | |
| 627 | + return buy_params | |
| 628 | + | |
| 629 | +# Sub-strategy with parameters specific to BTC stake | |
| 630 | +class SolipsisCon_BTC(SolipsisCon): | |
| 631 | + | |
| 632 | + timeframe = '1h' | |
| 633 | + inf_timeframe = '4h' | |
| 634 | + | |
| 635 | + buy_params = { | |
| 636 | + 'inf-rsi': 64, | |
| 637 | + 'mp': 55, | |
| 638 | + 'rmi-fast': 31, | |
| 639 | + 'rmi-slow': 16, | |
| 640 | + 'xinf-stake-rmi': 67, | |
| 641 | + 'xtf-fiat-rsi': 17, | |
| 642 | + 'xtf-stake-rsi': 57 | |
| 643 | + } | |
| 644 | + | |
| 645 | + minimal_roi = { | |
| 646 | + "0": 0.05, | |
| 647 | + "240": 0.025, | |
| 648 | + "1440": 0.01, | |
| 649 | + "4320": 0 | |
| 650 | + } | |
| 651 | + | |
| 652 | + stoploss = -0.30 | |
| 653 | + use_custom_stoploss = False | |
| 654 | + | |
| 655 | +# Sub-strategy with parameters specific to ETH stake | |
| 656 | +class Solipsis_ETH(SolipsisCon): | |
| 657 | + | |
| 658 | + timeframe = '1h' | |
| 659 | + inf_timeframe = '4h' | |
| 660 | + | |
| 661 | + buy_params = { | |
| 662 | + 'inf-rsi': 13, | |
| 663 | + 'inf-stake-rmi': 69, | |
| 664 | + 'mp': 40, | |
| 665 | + 'rmi-fast': 42, | |
| 666 | + 'rmi-slow': 17, | |
| 667 | + 'tf-fiat-rsi': 15, | |
| 668 | + 'tf-stake-rsi': 92 | |
| 669 | + } | |
| 670 | + | |
| 671 | + minimal_roi = { | |
| 672 | + "0": 0.05, | |
| 673 | + "240": 0.025, | |
| 674 | + "1440": 0.01, | |
| 675 | + "4320": 0 | |
| 676 | + } | |
| 677 | + | |
| 678 | + stoploss = -0.30 | |
| 679 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-tradedbexp.py +748 −0
| @@ -0,0 +1,748 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +import array as arr | |
| 6 | + | |
| 7 | +from freqtrade.strategy.interface import IStrategy | |
| 8 | +from freqtrade.strategy import merge_informative_pair | |
| 9 | +from typing import Dict, List, Optional, Tuple | |
| 10 | +from pandas import DataFrame, Series | |
| 11 | +from functools import reduce | |
| 12 | +from datetime import datetime, timedelta | |
| 13 | +from freqtrade.persistence import Trade | |
| 14 | +from statistics import mean | |
| 15 | +from cachetools import TTLCache | |
| 16 | + | |
| 17 | +# Get rid of pandas warnings during backtesting | |
| 18 | +import pandas as pd | |
| 19 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 20 | + | |
| 21 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 22 | +import sys | |
| 23 | +from pathlib import Path | |
| 24 | +sys.path.append(str(Path(__file__).parent)) | |
| 25 | + | |
| 26 | +import custom_indicators as cta | |
| 27 | + | |
| 28 | +""" | |
| 29 | +FEATURES: | |
| 30 | + - ROI override, extending use of ignore_roi_if_buy_signal = True by stimulating a sticking buy signal for active trades | |
| 31 | + which are in an upward trend. This ensures we extract maximum profit from trades rather than relying on static ROI points. | |
| 32 | + - Custom Stoploss with several modes and options (review the code). | |
| 33 | + - Dynamic ROI table with several modes and options (review the code). | |
| 34 | + - Custom sell which takes profit as well as other trade performance into consideration when selling. | |
| 35 | + - Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 36 | + - Ability to provide custom buy/sell parameters on a per-pair or group of pairs basis (may extend this to ROI and/or stoploss settings) | |
| 37 | + - Custom indicator file to keep primary strategy clean(ish). | |
| 38 | + - Child strategies for stake specific settings. | |
| 39 | + - Several methods to aid in using active trade data and realtime price data as part of the strategy. | |
| 40 | + | |
| 41 | +STRATEGY NOTES: | |
| 42 | + - If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) is *highly recommended* that you remove BTC/STAKE | |
| 43 | + from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC | |
| 44 | + itself. | |
| 45 | + - If trading on a different stake, such as BTC or ETH, this strategy has additional informative indicators it uses, if you use a stake | |
| 46 | + other than BTC/ETH (outside the standard fiat/stablecoin stakes) you may want to look at the code to include that stake in the list. | |
| 47 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 48 | + "--enable-protections" as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 49 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 50 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 51 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 52 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 53 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 54 | + - If running backtest/hyperopt around the portion of the sell signal that is testable, keep in mind in live/dry | |
| 55 | + it will not sell nearly as frequently due to the profit guard and other_profit / free_slot guards. | |
| 56 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 57 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 58 | + ROI based sells will be higher than the backtest shows. | |
| 59 | + - It is *not* worthwhile to hyperopt for roi as it does not take into account the roi trend ride we are doing and | |
| 60 | + having ROI points that are too high will sort of be counter-productive to how this strategy works even if it seems | |
| 61 | + to produce better results in backtesting. | |
| 62 | + - It *might be* worthwhile to hyperopt the stoploss but we can't hyperopt any of the parameters in the custom stoploss | |
| 63 | + so hyperopting the stoploss is only changing the initial position relative to the other settings. | |
| 64 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 65 | + - The custom stoploss has settings to emulate the same functionality, however. | |
| 66 | + - Might be worthwhile to disable the trailing stop in solipsis, hyperopt the trailing, and use those settings with the | |
| 67 | + Solipsis implementation, *if* you want a positive trailing stop, but the ROI ride should be preferred over the positive stoploss. | |
| 68 | + - It is *highly* recommended to backtest with use_sell_signal = False because it will not behave remotely the same in dry/live | |
| 69 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only or 'buy sell' and at least 1000 total epochs several times. There are | |
| 70 | + a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 71 | + | |
| 72 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 73 | + | |
| 74 | + custom_pair_params = [ | |
| 75 | + { | |
| 76 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 77 | + 'buy_params': {}, | |
| 78 | + 'sell_params': {} | |
| 79 | + } | |
| 80 | + ] | |
| 81 | + | |
| 82 | +TODO: | |
| 83 | + - Continue to hunt for a better all around buy signal. | |
| 84 | + - Completely eliminate any trades from hitting the initial stoploss (default: -30%) | |
| 85 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 86 | + - Need to reduce drawdown. | |
| 87 | + - Tweak ROI Trend Ride | |
| 88 | + - Maybe further exploit the ROI table itself using trade data? | |
| 89 | + - Per-pair automatic ROI points based on ADR/ATR or something similar? | |
| 90 | + - Tweak sell signal | |
| 91 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 92 | + - Further enchance and optimize custom stop loss | |
| 93 | +""" | |
| 94 | + | |
| 95 | +class Solipsis(IStrategy): | |
| 96 | + | |
| 97 | + # Recommended for USD/USDT/etc. | |
| 98 | + timeframe = '5m' | |
| 99 | + inf_timeframe = '1h' | |
| 100 | + | |
| 101 | + buy_params = { | |
| 102 | + 'base-mp': 48, | |
| 103 | + 'base-rmi-fast': 44, | |
| 104 | + 'base-rmi-slow': 21, | |
| 105 | + 'inf-guard': 'both', | |
| 106 | + 'inf-pct-adr-bot': 0.17436, | |
| 107 | + 'inf-pct-adr-top': 0.84712, | |
| 108 | + 'xbtc-base-rmi': 70, | |
| 109 | + 'xbtc-inf-rmi': 14, | |
| 110 | + 'xtra-base-fiat-rmi': 14, | |
| 111 | + 'xtra-base-stake-rmi': 50, | |
| 112 | + 'xtra-inf-stake-rmi': 31 | |
| 113 | + } | |
| 114 | + | |
| 115 | + sell_params = { | |
| 116 | + 'sell-rmi-drop': 0.82934 | |
| 117 | + } | |
| 118 | + | |
| 119 | + # Custom buy/sell parameters per pair | |
| 120 | + custom_pair_params = [] | |
| 121 | + | |
| 122 | + # Recommended on 5m timeframe | |
| 123 | + minimal_roi = { | |
| 124 | + "0": 0.05, | |
| 125 | + "30": 0.025, | |
| 126 | + "120": 0.01, | |
| 127 | + "360": 0.01, | |
| 128 | + "720": 0.005, | |
| 129 | + "1440": 0 | |
| 130 | + } | |
| 131 | + | |
| 132 | + # Optional | |
| 133 | + dynamic_roi = { | |
| 134 | + 'dynamic_roi_enabled': True, | |
| 135 | + 'dynamic_roi_type': 'connect' | |
| 136 | + } | |
| 137 | + | |
| 138 | + stoploss = -0.30 | |
| 139 | + | |
| 140 | + # Optional | |
| 141 | + use_custom_stoploss = False | |
| 142 | + custom_stop = { | |
| 143 | + 'mode': 'decay', # decay, decay-only | |
| 144 | + # Linear Decay Parameters | |
| 145 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 146 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 147 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 148 | + 'decay-end': -0.03, # ending value | |
| 149 | + # Current vs Min Profit | |
| 150 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 151 | + 'cur-threshold': 0, # how far negative should current profit be before we consider moving it up based on cur/min | |
| 152 | + # Positive Trailing | |
| 153 | + 'pos-trail': False, # enable trailing once positive | |
| 154 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 155 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 156 | + } | |
| 157 | + | |
| 158 | + # Recommended | |
| 159 | + use_sell_signal = True | |
| 160 | + sell_profit_only = False | |
| 161 | + ignore_roi_if_buy_signal = True | |
| 162 | + | |
| 163 | + # Required | |
| 164 | + startup_candle_count: int = 72 | |
| 165 | + process_only_new_candles = False | |
| 166 | + | |
| 167 | + # Strategy Specific Variable Storage | |
| 168 | + custom_trade_info = {} | |
| 169 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 170 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 171 | + | |
| 172 | + """ | |
| 173 | + Informative Pair Definitions | |
| 174 | + """ | |
| 175 | + def informative_pairs(self): | |
| 176 | + # add all whitelisted pairs on informative timeframe | |
| 177 | + pairs = self.dp.current_whitelist() | |
| 178 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 179 | + | |
| 180 | + # add extra informative pairs if the stake is BTC or ETH | |
| 181 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 182 | + for pair in pairs: | |
| 183 | + coin, stake = pair.split('/') | |
| 184 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 185 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 186 | + | |
| 187 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 188 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 189 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 190 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 191 | + else: | |
| 192 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 193 | + if not btc_stake in pairs: | |
| 194 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 195 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 196 | + | |
| 197 | + return informative_pairs | |
| 198 | + | |
| 199 | + """ | |
| 200 | + Indicator Definitions | |
| 201 | + """ | |
| 202 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 203 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 204 | + | |
| 205 | + # Base timeframe indicators | |
| 206 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 207 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 208 | + | |
| 209 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 210 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 211 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 212 | + | |
| 213 | + # Trends, Peaks and Crosses | |
| 214 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 215 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 216 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 217 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 218 | + dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max() | |
| 219 | + | |
| 220 | + # Base pair informative timeframe indicators | |
| 221 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 222 | + | |
| 223 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 224 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 225 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 226 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 227 | + | |
| 228 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 229 | + | |
| 230 | + # Other stake specific informative indicators | |
| 231 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 232 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 233 | + coin, stake = metadata['pair'].split('/') | |
| 234 | + fiat = self.custom_fiat | |
| 235 | + coin_fiat = f"{coin}/{fiat}" | |
| 236 | + stake_fiat = f"{stake}/{fiat}" | |
| 237 | + | |
| 238 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 239 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 240 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 241 | + | |
| 242 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 243 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 244 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 245 | + | |
| 246 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 247 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 248 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 249 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 250 | + | |
| 251 | + # Informatives for BTC/STAKE if not in whitelist | |
| 252 | + else: | |
| 253 | + pairs = self.dp.current_whitelist() | |
| 254 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 255 | + if not btc_stake in pairs: | |
| 256 | + # BTC/STAKE - Base Timeframe | |
| 257 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 258 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 259 | + | |
| 260 | + # BTC/STAKE - Informative Timeframe | |
| 261 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 262 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 263 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 264 | + | |
| 265 | + return dataframe | |
| 266 | + | |
| 267 | + """ | |
| 268 | + Buy Signal | |
| 269 | + """ | |
| 270 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 271 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 272 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 273 | + conditions = [] | |
| 274 | + | |
| 275 | + # If active trade, look at trend to persist a buy signal for ignore_roi_if_buy_signal | |
| 276 | + if trade_data['active_trade']: | |
| 277 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 278 | + rmi_grow = cta.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 279 | + | |
| 280 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 281 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 282 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 283 | + | |
| 284 | + # Standard signals for entering new trades | |
| 285 | + else: | |
| 286 | + | |
| 287 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 288 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 289 | + conditions.append( | |
| 290 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 291 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 292 | + ) | |
| 293 | + | |
| 294 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 295 | + conditions.append( | |
| 296 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 297 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 298 | + ) | |
| 299 | + | |
| 300 | + # Base Timeframe | |
| 301 | + conditions.append( | |
| 302 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 303 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 304 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 305 | + (dataframe['mp'] <= params['base-mp']) | |
| 306 | + ) | |
| 307 | + | |
| 308 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 309 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 310 | + conditions.append( | |
| 311 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 312 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 313 | + ) | |
| 314 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 315 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 316 | + else: | |
| 317 | + pairs = self.dp.current_whitelist() | |
| 318 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 319 | + if not btc_stake in pairs: | |
| 320 | + conditions.append( | |
| 321 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 322 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 323 | + ) | |
| 324 | + | |
| 325 | + # Applies to active or new trades | |
| 326 | + conditions.append(dataframe['volume'].gt(0)) | |
| 327 | + | |
| 328 | + if conditions: | |
| 329 | + dataframe.loc[ | |
| 330 | + reduce(lambda x, y: x & y, conditions), | |
| 331 | + 'buy'] = 1 | |
| 332 | + | |
| 333 | + return dataframe | |
| 334 | + | |
| 335 | + """ | |
| 336 | + Sell Signal | |
| 337 | + """ | |
| 338 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 339 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 340 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 341 | + conditions = [] | |
| 342 | + | |
| 343 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 344 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 345 | + if trade_data['active_trade']: | |
| 346 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 347 | + # a trade to go into the negative a little bit before we react to sell. | |
| 348 | + loss_cutoff = cta.linear_growth(-0.03, 0, 0, 240, trade_data['open_minutes']) | |
| 349 | + | |
| 350 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 351 | + | |
| 352 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 353 | + if trade_data['other_trades']: | |
| 354 | + if trade_data['free_slots'] > 0: | |
| 355 | + # If the average of all our other trades is below a certain threshold based | |
| 356 | + # on free slots available, hold and wait for market recovery. | |
| 357 | + hold_pct = (1/trade_data['free_slots']) * -0.04 | |
| 358 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 359 | + else: | |
| 360 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 361 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 362 | + | |
| 363 | + # Primary sell trigger | |
| 364 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 365 | + conditions.append( | |
| 366 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 367 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 368 | + (dataframe['volume'].gt(0)) | |
| 369 | + ) | |
| 370 | + | |
| 371 | + if conditions: | |
| 372 | + dataframe.loc[ | |
| 373 | + reduce(lambda x, y: x & y, conditions), | |
| 374 | + 'sell'] = 1 | |
| 375 | + | |
| 376 | + return dataframe | |
| 377 | + | |
| 378 | + """ | |
| 379 | + Custom Stoploss | |
| 380 | + """ | |
| 381 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 382 | + cs = self.custom_stop | |
| 383 | + | |
| 384 | + # Attempting to populate some of the trade data used elsewhere in the strategy with the trade object from here in backtest/hyperopt | |
| 385 | + if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 386 | + self.custom_trade_info[pair] = self.populate_trades(pair, trade=trade, time=current_time, rate=current_rate, profit=current_profit) | |
| 387 | + | |
| 388 | + trade_data = self.custom_trade_info[pair] | |
| 389 | + | |
| 390 | + print(f"Trade Data from Populate Trades: {trade_data}") | |
| 391 | + | |
| 392 | + open_minutes: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 393 | + min_profit = trade.calc_profit_ratio(trade.min_rate) # min array no object? | |
| 394 | + max_profit = trade.calc_profit_ratio(trade.max_rate) # max array no object? | |
| 395 | + profit_diff = current_profit - min_profit | |
| 396 | + | |
| 397 | + print(f"Trade object in stoploss {trade}") | |
| 398 | + print(f"Open Minutes: {open_minutes}") | |
| 399 | + print(f"Current Rate: {current_rate}") | |
| 400 | + print(f"Current Profit: {current_profit}") | |
| 401 | + print(f"Min Profit: {min_profit}") | |
| 402 | + print(f"Max Profit: {max_profit}") | |
| 403 | + | |
| 404 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 405 | + if cs['pos-trail'] == True: | |
| 406 | + if current_profit > cs['pos-threshold']: | |
| 407 | + return current_profit - cs['pos-trail-dist'] | |
| 408 | + | |
| 409 | + # decay-only is literally just the decay, decay uses the decay unless profit is increasing | |
| 410 | + if cs['mode'] == 'decay' or cs['mode'] == 'decay-only': | |
| 411 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], open_minutes) | |
| 412 | + if cs['mode'] == 'decay-only': | |
| 413 | + return decay_stoploss | |
| 414 | + | |
| 415 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 416 | + if (current_profit > min_profit) and current_profit < cs['cur-threshold']: | |
| 417 | + if profit_diff > cs['cur-min-diff']: | |
| 418 | + return min_profit | |
| 419 | + return -1 | |
| 420 | + | |
| 421 | + return decay_stoploss | |
| 422 | + | |
| 423 | + if cs['mode'] == 'dynamic': | |
| 424 | + if not pair in cs: | |
| 425 | + cs[pair] = {} | |
| 426 | + | |
| 427 | + cs[pair]['current_profit'] | |
| 428 | + cs[pair]['min_profit'] | |
| 429 | + cs[pair]['max_profit'] | |
| 430 | + | |
| 431 | + | |
| 432 | + # if all else fails, keep the stoploss where it is | |
| 433 | + return -1 | |
| 434 | + | |
| 435 | + """ | |
| 436 | + Trade Timeout Overloads | |
| 437 | + """ | |
| 438 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 439 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 440 | + ob = self.dp.orderbook(pair, 1) | |
| 441 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 442 | + if current_price > order['price'] * 1.01: | |
| 443 | + return True | |
| 444 | + return False | |
| 445 | + | |
| 446 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 447 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 448 | + ob = self.dp.orderbook(pair, 1) | |
| 449 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 450 | + if current_price < order['price'] * 0.99: | |
| 451 | + return True | |
| 452 | + return False | |
| 453 | + | |
| 454 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 455 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 456 | + ob = self.dp.orderbook(pair, 1) | |
| 457 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 458 | + if current_price > rate * 1.01: | |
| 459 | + return False | |
| 460 | + return True | |
| 461 | + | |
| 462 | + """ | |
| 463 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 464 | + """ | |
| 465 | + def min_roi_reached_dynamic(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 466 | + | |
| 467 | + dynamic_roi = self.dynamic_roi | |
| 468 | + minimal_roi = self.minimal_roi | |
| 469 | + | |
| 470 | + if not dynamic_roi: | |
| 471 | + return None, None | |
| 472 | + | |
| 473 | + if 'dynamic_roi_type' in dynamic_roi and dynamic_roi['dynamic_roi_type'] \ | |
| 474 | + in ['linear', 'exponential', 'connect']: | |
| 475 | + roi_type = dynamic_roi['dynamic_roi_type'] | |
| 476 | + # linear decay: f(t) = start - (rate * t) | |
| 477 | + if roi_type == 'linear': | |
| 478 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 479 | + 'dynamic_roi_time' in dynamic_roi: | |
| 480 | + start = dynamic_roi['dynamic_roi_start'] | |
| 481 | + end = dynamic_roi['dynamic_roi_end'] | |
| 482 | + time = dynamic_roi['dynamic_roi_time'] | |
| 483 | + rate = (start - end) / time | |
| 484 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 485 | + else: | |
| 486 | + return None, None | |
| 487 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 488 | + elif roi_type == 'exponential': | |
| 489 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 490 | + 'dynamic_roi_rate' in dynamic_roi: | |
| 491 | + start = dynamic_roi['dynamic_roi_start'] | |
| 492 | + end = dynamic_roi['dynamic_roi_end'] | |
| 493 | + rate = dynamic_roi['dynamic_roi_rate'] | |
| 494 | + min_roi = max(end, start * np.exp(-rate*trade_dur)) | |
| 495 | + else: | |
| 496 | + return None, None | |
| 497 | + # "connect the dots" between the points on the minima_roi table | |
| 498 | + elif roi_type == 'connect': | |
| 499 | + if not minimal_roi: | |
| 500 | + return None, None | |
| 501 | + # figure out where we are in the defined roi table | |
| 502 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 503 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 504 | + # if we are past the final point in the table, use that key/vaule pair | |
| 505 | + if not past_roi: | |
| 506 | + return None, None | |
| 507 | + current_entry = max(past_roi) | |
| 508 | + if not next_roi: | |
| 509 | + return current_entry, minimal_roi[current_entry] | |
| 510 | + next_entry = min(next_roi) | |
| 511 | + # use the slope-intercept formula between the two points | |
| 512 | + # y = mx + b | |
| 513 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 514 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 515 | + m = (y1-y2)/(x1-x2) | |
| 516 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 517 | + min_roi = (m * trade_dur) + b | |
| 518 | + else: | |
| 519 | + return None, None | |
| 520 | + | |
| 521 | + return trade_dur, min_roi | |
| 522 | + | |
| 523 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 524 | + | |
| 525 | + if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 526 | + self.custom_trade_info[trade.pair] = self.populate_trades(trade.pair, trade=trade, time=current_time, profit=current_profit) | |
| 527 | + | |
| 528 | + trade_data = self.custom_trade_info[trade.pair] | |
| 529 | + | |
| 530 | + open_minutes = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 531 | + min_profit = trade.calc_profit_ratio(trade.min_rate) # min array no object? | |
| 532 | + max_profit = trade.calc_profit_ratio(trade.max_rate) # max array no object? | |
| 533 | + profit_diff = current_profit - min_profit | |
| 534 | + | |
| 535 | + if trade.pair == 'XMR/USD': | |
| 536 | + print(f"Trade object in ROI {trade}") | |
| 537 | + print(f"Open Minutes: {open_minutes}") | |
| 538 | + #print(f"Current Rate: {current_rate}") | |
| 539 | + print(f"Current Profit: {current_profit}") | |
| 540 | + print(f"Min Profit: {min_profit}") | |
| 541 | + print(f"Max Profit: {max_profit}") | |
| 542 | + | |
| 543 | + print(f"Trade Data from Populate Trades:") | |
| 544 | + print(f"Active Trade: {trade_data['active_trade']}") | |
| 545 | + print(f"Open Minutes: {trade_data['open_minutes']}") | |
| 546 | + print(f"Current Profit: {trade_data['current_profit']}") | |
| 547 | + print(f"Peak Profit DB: {trade_data['peak_profit-db']}") | |
| 548 | + print(f"Peak Profit Ar: {trade_data['peak_profit-array']}") | |
| 549 | + print(f"Min Profit DB: {trade_data['min_profit-db']}") | |
| 550 | + print(f"Min Profit Ar: {trade_data['min_profit-array']}") | |
| 551 | + | |
| 552 | + print(f"Profit Array for XMR/USD:") | |
| 553 | + print(trade_data['profit_array']) | |
| 554 | + | |
| 555 | + | |
| 556 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 557 | + | |
| 558 | + if self.dynamic_roi and 'dynamic_roi_enabled' in self.dynamic_roi \ | |
| 559 | + and self.dynamic_roi['dynamic_roi_enabled']: | |
| 560 | + _, roi = self.min_roi_reached_dynamic(trade_dur) | |
| 561 | + else: | |
| 562 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 563 | + if roi is None: | |
| 564 | + return False | |
| 565 | + else: | |
| 566 | + return current_profit > roi | |
| 567 | + | |
| 568 | + """ | |
| 569 | + Custom Methods for Strategy Parameters, Trade, and Price Data | |
| 570 | + Consider splitting this out into a helper file. | |
| 571 | + """ | |
| 572 | + def populate_trades(self, pair: str, **kwargs) -> dict: | |
| 573 | + """ | |
| 574 | + Query the database and populate the custom_trade_info dict. | |
| 575 | + """ | |
| 576 | + if not pair in self.custom_trade_info: | |
| 577 | + self.custom_trade_info[pair] = {} | |
| 578 | + | |
| 579 | + trade_data = {} | |
| 580 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 581 | + | |
| 582 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 583 | + | |
| 584 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 585 | + | |
| 586 | + if active_trade: | |
| 587 | + current_rate = self.get_current_price(pair, True) | |
| 588 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 589 | + | |
| 590 | + present = arrow.utcnow() | |
| 591 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 592 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 593 | + | |
| 594 | + trade_data['active_trade'] = True | |
| 595 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 596 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) # if above 0 | |
| 597 | + trade_data['min_profit'] = active_trade[0].calc_profit_ratio(active_trade[0].min_rate) | |
| 598 | + trade_data['open_minutes'] : int = open_minutes | |
| 599 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 600 | + else: | |
| 601 | + trade_data['current_profit'] = trade_data['peak_profit'] = trade_data['min_profit'] = 0.0 | |
| 602 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 603 | + | |
| 604 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 605 | + | |
| 606 | + if other_trades: | |
| 607 | + trade_data['other_trades'] = True | |
| 608 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 609 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 610 | + if trade_data['current_profit'] < min(other_profit): | |
| 611 | + trade_data['biggest_loser'] = True | |
| 612 | + else: | |
| 613 | + trade_data['avg_other_profit'] = 0 | |
| 614 | + | |
| 615 | + open_trades = len(Trade.get_open_trades()) | |
| 616 | + # this was lazy. | |
| 617 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 618 | + | |
| 619 | + # Attempting a hack to get *some* data during backtest | |
| 620 | + elif self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 621 | + # kwargs: trade=trade, time=current_time, rate=current_rate, profit=current_profit | |
| 622 | + active_trade = kwargs.get('trade', False) | |
| 623 | + | |
| 624 | + if not 'profit_array' in self.custom_trade_info[pair]: | |
| 625 | + self.custom_trade_info[pair]['profit_array'] = arr.array('f') | |
| 626 | + else: | |
| 627 | + trade_data['profit_array'] = self.custom_trade_info[pair]['profit_array'] | |
| 628 | + | |
| 629 | + if active_trade: | |
| 630 | + current_time = kwargs.get('time', 0) | |
| 631 | + # current_rate = kwargs.get('rate', 0.0) | |
| 632 | + current_profit = kwargs.get('profit', 0.0) | |
| 633 | + | |
| 634 | + open_minutes: int = (current_time - active_trade.open_date).total_seconds() // 60 | |
| 635 | + | |
| 636 | + trade_data['active_trade'] = True | |
| 637 | + trade_data['open_minutes'] = open_minutes | |
| 638 | + trade_data['current_profit'] = current_profit | |
| 639 | + trade_data['profit_array'].append(current_profit) | |
| 640 | + | |
| 641 | + # active_trade.adjust_min_max_rates(current_rate) | |
| 642 | + | |
| 643 | + trade_data['peak_profit-db'] = max(0, active_trade.calc_profit_ratio(active_trade.max_rate)) | |
| 644 | + trade_data['min_profit-db'] = active_trade.calc_profit_ratio(active_trade.min_rate) | |
| 645 | + | |
| 646 | + trade_data['peak_profit-array'] = max(0, max(trade_data['profit_array'])) | |
| 647 | + trade_data['min_profit-array'] = min(trade_data['profit_array']) | |
| 648 | + | |
| 649 | + else: | |
| 650 | + trade_data['profit_array'] = arr.array('f') | |
| 651 | + trade_data['current_profit'] = trade_data['peak_profit'] = trade_data['min_profit'] = 0.0 | |
| 652 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 653 | + | |
| 654 | + return trade_data | |
| 655 | + | |
| 656 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 657 | + """ | |
| 658 | + Query the exchange for current price information, used in profit calculations. | |
| 659 | + Implements a cache to prevent excessive api calls. | |
| 660 | + """ | |
| 661 | + if not refresh: | |
| 662 | + rate = self.custom_current_price_cache.get(pair) | |
| 663 | + if rate: | |
| 664 | + return rate | |
| 665 | + | |
| 666 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 667 | + if ask_strategy.get('use_order_book', False): | |
| 668 | + ob = self.dp.orderbook(pair, 1) | |
| 669 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 670 | + else: | |
| 671 | + ticker = self.dp.ticker(pair) | |
| 672 | + rate = ticker['last'] | |
| 673 | + | |
| 674 | + self.custom_current_price_cache[pair] = rate | |
| 675 | + return rate | |
| 676 | + | |
| 677 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 678 | + """ | |
| 679 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 680 | + TODO: | |
| 681 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 682 | + """ | |
| 683 | + buy_params = self.buy_params | |
| 684 | + sell_params = self.sell_params | |
| 685 | + | |
| 686 | + if self.custom_pair_params: | |
| 687 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 688 | + if custom_params['buy_params']: | |
| 689 | + buy_params = custom_params['buy_params'] | |
| 690 | + if custom_params['sell_params']: | |
| 691 | + sell_params = custom_params['sell_params'] | |
| 692 | + | |
| 693 | + if side == 'sell': | |
| 694 | + return sell_params | |
| 695 | + | |
| 696 | + return buy_params | |
| 697 | + | |
| 698 | +# Sub-strategy with parameters specific to BTC stake | |
| 699 | +class Solipsis_BTC(Solipsis): | |
| 700 | + | |
| 701 | + timeframe = '1h' | |
| 702 | + inf_timeframe = '4h' | |
| 703 | + | |
| 704 | + buy_params = { | |
| 705 | + 'inf-rsi': 64, | |
| 706 | + 'mp': 55, | |
| 707 | + 'rmi-fast': 31, | |
| 708 | + 'rmi-slow': 16, | |
| 709 | + 'xinf-stake-rmi': 67, | |
| 710 | + 'xtf-fiat-rsi': 17, | |
| 711 | + 'xtf-stake-rsi': 57 | |
| 712 | + } | |
| 713 | + | |
| 714 | + minimal_roi = { | |
| 715 | + "0": 0.05, | |
| 716 | + "240": 0.025, | |
| 717 | + "1440": 0.01, | |
| 718 | + "4320": 0 | |
| 719 | + } | |
| 720 | + | |
| 721 | + stoploss = -0.30 | |
| 722 | + use_custom_stoploss = False | |
| 723 | + | |
| 724 | +# Sub-strategy with parameters specific to ETH stake | |
| 725 | +class Solipsis_ETH(Solipsis): | |
| 726 | + | |
| 727 | + timeframe = '1h' | |
| 728 | + inf_timeframe = '4h' | |
| 729 | + | |
| 730 | + buy_params = { | |
| 731 | + 'inf-rsi': 13, | |
| 732 | + 'inf-stake-rmi': 69, | |
| 733 | + 'mp': 40, | |
| 734 | + 'rmi-fast': 42, | |
| 735 | + 'rmi-slow': 17, | |
| 736 | + 'tf-fiat-rsi': 15, | |
| 737 | + 'tf-stake-rsi': 92 | |
| 738 | + } | |
| 739 | + | |
| 740 | + minimal_roi = { | |
| 741 | + "0": 0.05, | |
| 742 | + "240": 0.025, | |
| 743 | + "1440": 0.01, | |
| 744 | + "4320": 0 | |
| 745 | + } | |
| 746 | + | |
| 747 | + stoploss = -0.30 | |
| 748 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v1.py +746 −0
| @@ -0,0 +1,746 @@ | ||
| 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 | |
| 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 statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | +# Get rid of pandas warnings during backtesting | |
| 17 | +import pandas as pd | |
| 18 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 19 | + | |
| 20 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 21 | +import sys | |
| 22 | +from pathlib import Path | |
| 23 | +sys.path.append(str(Path(__file__).parent)) | |
| 24 | + | |
| 25 | +import custom_indicators as cta | |
| 26 | + | |
| 27 | +""" | |
| 28 | +TODO: | |
| 29 | + - Continue to hunt for a better all around buy signal. | |
| 30 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 31 | + - ADR guards are helping but need to reduce losing trade counts. | |
| 32 | + - Need to reduce drawdown. | |
| 33 | + - Tweak ROI Trend Ride | |
| 34 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 35 | + - Maybe further exploit the ROI table itself using trade data? | |
| 36 | + - Per-pair automatic ROI points based on ADR/ATR or something similar? | |
| 37 | + - Tweak sell signal | |
| 38 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 39 | + - Further enchance and optimize custom stop loss | |
| 40 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 41 | + | |
| 42 | +STRATEGY NOTES: | |
| 43 | + - It is recommended to configure protections *if/as* you will use them in live and run a hyperopt/backtest with | |
| 44 | + --enable-protections as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 45 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 46 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 47 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 48 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 49 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 50 | + - If running backtest/hyperopt around the portion of the sell signal that is testable, keep in mind in live/dry | |
| 51 | + it will not sell nearly as frequently due to the profit guard and other_profit / free_slot guards. | |
| 52 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 53 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 54 | + ROI based sells will be higher than the backtest shows. | |
| 55 | + - It is *not* worthwhile to hyperopt for roi as it does not take into account the roi trend ride we are doing and | |
| 56 | + having ROI points that are too high will sort of be counter-productive to how this strategy works even if it seems | |
| 57 | + to produce better results in backtesting. | |
| 58 | + - It is *probably not* worthwhile to hyperopt the stoploss as we can't hyperopt any of the parameters in the custom stoploss | |
| 59 | + so hyperopting the stoploss is only looking at one aspect of it. | |
| 60 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 61 | + - It is *highly* recommended to backtest with use_sell_signal = False because it will not behave remotely the same in dry/live | |
| 62 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only or 'buy sell' and at least 5000 total epochs, but a preliminary | |
| 63 | + set of sane defaults is: | |
| 64 | + | |
| 65 | + buy_params = { | |
| 66 | + 'base-fib-level': 0.618, | |
| 67 | + 'base-mp': 30, | |
| 68 | + 'base-pmax': 'up', | |
| 69 | + 'base-pmax-enable': False, | |
| 70 | + 'base-rmi-fast': 50, | |
| 71 | + 'base-rmi-slow': 20, | |
| 72 | + 'base-trend': 'down', | |
| 73 | + 'inf-fib-level': 0.236, | |
| 74 | + 'inf-guard': 'upper', | |
| 75 | + 'inf-pct-adr-bot': 0.05, | |
| 76 | + 'inf-pct-adr-top': 0.80, | |
| 77 | + 'inf-rsi': 20, | |
| 78 | + 'xtra-base-fiat-rsi': 30, | |
| 79 | + 'xtra-base-stake-rsi': 60, | |
| 80 | + 'xtra-inf-stake-rmi': 20 | |
| 81 | + } | |
| 82 | + | |
| 83 | + sell_params = { | |
| 84 | + 'sell-rmi-drop': 0.50, | |
| 85 | + 'sell-pmax-enable': False | |
| 86 | + } | |
| 87 | + | |
| 88 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 89 | + | |
| 90 | + custom_pair_params = [ | |
| 91 | + { | |
| 92 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 93 | + 'buy_params': { | |
| 94 | + 'base-fib-level': 0.618, | |
| 95 | + 'base-mp': 30, | |
| 96 | + 'base-pmax': 'up', | |
| 97 | + 'base-pmax-enable': False, | |
| 98 | + 'base-rmi-fast': 50, | |
| 99 | + 'base-rmi-slow': 20, | |
| 100 | + 'base-trend': 'down', | |
| 101 | + 'inf-fib-level': 0.236, | |
| 102 | + 'inf-guard': 'upper', | |
| 103 | + 'inf-pct-adr-bot': 0.05, | |
| 104 | + 'inf-pct-adr-top': 0.80, | |
| 105 | + 'inf-rsi': 20, | |
| 106 | + 'xtra-base-fiat-rsi': 30, | |
| 107 | + 'xtra-base-stake-rsi': 60, | |
| 108 | + 'xtra-inf-stake-rmi': 20 | |
| 109 | + }, | |
| 110 | + 'sell_params': { | |
| 111 | + 'sell-pmax-enable': True, | |
| 112 | + 'sell-rmi-drop': 0.89661 | |
| 113 | + } | |
| 114 | + } | |
| 115 | + ] | |
| 116 | + | |
| 117 | +""" | |
| 118 | + | |
| 119 | +class Solipsis(IStrategy): | |
| 120 | + | |
| 121 | + # Recommended for USD/USDT/etc. | |
| 122 | + timeframe = '5m' | |
| 123 | + inf_timeframe = '1h' | |
| 124 | + | |
| 125 | + buy_params = { | |
| 126 | + 'base-fib-level': 0.618, | |
| 127 | + 'base-mp': 84, | |
| 128 | + 'base-pmax': 'up', | |
| 129 | + 'base-pmax-enable': True, # False | |
| 130 | + 'base-rmi-fast': 44, | |
| 131 | + 'base-rmi-slow': 27, | |
| 132 | + 'base-trend': 'down', | |
| 133 | + 'inf-fib-level': 0.0, | |
| 134 | + 'inf-guard': 'both', | |
| 135 | + 'inf-pct-adr-bot': 0.05725, | |
| 136 | + 'inf-pct-adr-top': 0.98309, | |
| 137 | + 'inf-rsi': 22, | |
| 138 | + 'xtra-base-fiat-rsi': 70, | |
| 139 | + 'xtra-base-stake-rsi': 50, | |
| 140 | + 'xtra-inf-stake-rmi': 47 | |
| 141 | + } | |
| 142 | + | |
| 143 | + # Sell hyperspace params: | |
| 144 | + sell_params = { | |
| 145 | + 'sell-pmax-enable': True, | |
| 146 | + 'sell-rmi-drop': 0.89661 | |
| 147 | + } | |
| 148 | + | |
| 149 | + # Custom buy/sell parameters per pair | |
| 150 | + custom_pair_params = [] | |
| 151 | + | |
| 152 | + # Recommended on 5m timeframe | |
| 153 | + minimal_roi = { | |
| 154 | + "0": 0.05, | |
| 155 | + "30": 0.025, | |
| 156 | + "120": 0.01, | |
| 157 | + "360": 0.01, | |
| 158 | + "720": 0.005, | |
| 159 | + "1440": 0 | |
| 160 | + } | |
| 161 | + | |
| 162 | + # Optional | |
| 163 | + dynamic_roi = { | |
| 164 | + 'dynamic_roi_enabled': True, | |
| 165 | + 'dynamic_roi_type': 'connect' | |
| 166 | + } | |
| 167 | + | |
| 168 | + stoploss = -0.30 | |
| 169 | + | |
| 170 | + # Optional | |
| 171 | + use_custom_stoploss = True | |
| 172 | + custom_stop = { | |
| 173 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 174 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 175 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 176 | + 'decay-end': -0.03, # ending value | |
| 177 | + 'pos-trail': False, # enable trailing once positive | |
| 178 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 179 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 180 | + } | |
| 181 | + | |
| 182 | + # Recommended | |
| 183 | + use_sell_signal = True | |
| 184 | + sell_profit_only = False | |
| 185 | + ignore_roi_if_buy_signal = True | |
| 186 | + | |
| 187 | + # Required | |
| 188 | + startup_candle_count: int = 72 | |
| 189 | + process_only_new_candles = False | |
| 190 | + | |
| 191 | + # Strategy Specific Variable Storage | |
| 192 | + custom_trade_info = {} | |
| 193 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 194 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 195 | + | |
| 196 | + # Parameters dealing with the ROI ride the sell signal behind active_trade | |
| 197 | + # These changes can only be tested in dry-run or live trading | |
| 198 | + custom_active_trade = { | |
| 199 | + # linear decay on RMI trend threshold | |
| 200 | + 'roi-pft-factor': 400, | |
| 201 | + 'roi-rmi-start': 30, | |
| 202 | + 'roi-rmi-end': 70, | |
| 203 | + 'roi-delay': 180, | |
| 204 | + 'roi-time': 720, | |
| 205 | + # loss thresholds | |
| 206 | + 'sell-mkt-down': -0.04, | |
| 207 | + 'loss-start': -0.03, | |
| 208 | + 'loss-end': 0, | |
| 209 | + 'loss-delay': 0, | |
| 210 | + 'loss-time': 240 | |
| 211 | + } | |
| 212 | + | |
| 213 | + """ | |
| 214 | + Informative Pair Definitions | |
| 215 | + """ | |
| 216 | + def informative_pairs(self): | |
| 217 | + pairs = self.dp.current_whitelist() | |
| 218 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 219 | + | |
| 220 | + # add extra informative pairs if the stake is BTC or ETH | |
| 221 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 222 | + for pair in pairs: | |
| 223 | + coin, stake = pair.split('/') | |
| 224 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 225 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 226 | + | |
| 227 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 228 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 229 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 230 | + | |
| 231 | + return informative_pairs | |
| 232 | + | |
| 233 | + """ | |
| 234 | + Indicator Definitions | |
| 235 | + """ | |
| 236 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 237 | + buy_params = self.get_pair_params(metadata['pair'], 'buy') | |
| 238 | + sell_params = self.get_pair_params(metadata['pair'], 'sell') | |
| 239 | + | |
| 240 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 241 | + | |
| 242 | + # Base timeframe indicators | |
| 243 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 244 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 245 | + | |
| 246 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 247 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 248 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 249 | + | |
| 250 | + # RMI Trends and Peaks | |
| 251 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 252 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 253 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 254 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 255 | + dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max() | |
| 256 | + | |
| 257 | + # Fibonacci Retracements | |
| 258 | + dataframe['fib-ret'] = cta.fib_ret(dataframe) | |
| 259 | + | |
| 260 | + # PMAX | |
| 261 | + # matype = ema, src = hl2 | |
| 262 | + # pmax is really slow, only enable it if its actually being used. | |
| 263 | + if buy_params['base-pmax-enable'] == True or sell_params['sell-pmax-enable'] == True: | |
| 264 | + atr, ma, pmax, pm_loc = cta.PMAX(dataframe, period=10, multiplier=3, length=12, MAtype=1, src=2) | |
| 265 | + dataframe['pmax-trend'] = pm_loc | |
| 266 | + else: | |
| 267 | + dataframe['pmax-trend'] = False | |
| 268 | + | |
| 269 | + # Other stake specific informative indicators | |
| 270 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 271 | + # TODO: Re-evaluate the value of these informative indicators | |
| 272 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 273 | + coin, stake = metadata['pair'].split('/') | |
| 274 | + fiat = self.custom_fiat | |
| 275 | + coin_fiat = f"{coin}/{fiat}" | |
| 276 | + stake_fiat = f"{stake}/{fiat}" | |
| 277 | + | |
| 278 | + # Informative COIN/FIAT e.g. XLM/USD | |
| 279 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 280 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 281 | + | |
| 282 | + # Informative STAKE/FIAT e.g. BTC/USD | |
| 283 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 284 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 285 | + | |
| 286 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 287 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = cta.RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 288 | + | |
| 289 | + # Base pair informative timeframe indicators | |
| 290 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 291 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 292 | + | |
| 293 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 294 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 295 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 296 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 297 | + | |
| 298 | + informative['fib-ret'] = cta.fib_ret(informative) | |
| 299 | + | |
| 300 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 301 | + | |
| 302 | + return dataframe | |
| 303 | + | |
| 304 | + """ | |
| 305 | + Buy Signal | |
| 306 | + """ | |
| 307 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 308 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 309 | + at = self.custom_active_trade | |
| 310 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 311 | + conditions = [] | |
| 312 | + | |
| 313 | + """ | |
| 314 | + The primary "secret sauce" of Solipsis is to take advantage of the ignore_roi_if_buy_signal setting. | |
| 315 | + Ideally, the ROI table is very tight and aggressive allowing for quick exits on ROI without reliance | |
| 316 | + on a sell signal. However, if certain criteria are met for an open trade, we stimulate a sticking buy | |
| 317 | + signal on purpose to prevent the bot from selling to the ROI in the midst of an upward trend. | |
| 318 | + | |
| 319 | + This is not currently able to be backtested or hyperopted so all settings here must be tested and validated | |
| 320 | + in dry-run or live. It is safe to assume that when backtesting, all sells for reason roi will have likely been | |
| 321 | + for higher profits in live trading than in backtest. | |
| 322 | + """ | |
| 323 | + | |
| 324 | + # If active trade, look at trend to persist a buy signal for ignore_roi_if_buy_signal | |
| 325 | + if trade_data['active_trade']: | |
| 326 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / at['roi-pft-factor'])) | |
| 327 | + rmi_grow = cta.linear_growth(at['roi-rmi-start'], at['roi-rmi-end'], | |
| 328 | + at['roi-delay'], at['roi-time'], trade_data['open_minutes']) | |
| 329 | + | |
| 330 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 331 | + # TODO: Experiment with replacing or augmenting this with PMAX | |
| 332 | + conditions.append( | |
| 333 | + ( | |
| 334 | + (params['base-pmax-enable'] == True) & | |
| 335 | + (dataframe['pmax-trend'] == 'up') | |
| 336 | + ) | ( | |
| 337 | + (dataframe['rmi-up-trend'] == 1) & | |
| 338 | + (dataframe['rmi-slow'] >= rmi_grow) | |
| 339 | + ) | |
| 340 | + ) | |
| 341 | + | |
| 342 | + # Standard signals for entering new trades | |
| 343 | + else: | |
| 344 | + | |
| 345 | + # Guards on informative timeframe | |
| 346 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 347 | + conditions.append( | |
| 348 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 349 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 350 | + ) | |
| 351 | + | |
| 352 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 353 | + conditions.append( | |
| 354 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 355 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 356 | + ) | |
| 357 | + | |
| 358 | + # Informative Timeframe | |
| 359 | + conditions.append( | |
| 360 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 361 | + (dataframe[f"fib-ret_{self.inf_timeframe}"] >= params['inf-fib-level']) | |
| 362 | + ) | |
| 363 | + | |
| 364 | + if params['base-pmax-enable'] == True: | |
| 365 | + conditions.append((dataframe['pmax-trend'] == params['base-pmax'])) | |
| 366 | + | |
| 367 | + # # Base Timeframe | |
| 368 | + # Look for bottom of downward trend and expect bounce | |
| 369 | + if params['base-trend'] == 'down': | |
| 370 | + conditions.append( | |
| 371 | + (dataframe['fib-ret'] <= params['base-fib-level']) & | |
| 372 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 373 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 374 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 375 | + (dataframe['mp'] <= params['base-mp']) | |
| 376 | + ) | |
| 377 | + | |
| 378 | + # Look for upward trend | |
| 379 | + elif params['base-trend'] == 'up': | |
| 380 | + conditions.append( | |
| 381 | + (dataframe['fib-ret'] >= params['base-fib-level']) & | |
| 382 | + (dataframe['rmi-up-trend'] == 1) & | |
| 383 | + (dataframe['rmi-slow'] <= params['base-rmi-slow']) & | |
| 384 | + (dataframe['rmi-fast'] >= params['base-rmi-fast']) & | |
| 385 | + (dataframe['mp'] >= params['base-mp']) | |
| 386 | + ) | |
| 387 | + | |
| 388 | + # Extra conditions for BTC/ETH stakes on additional informative pairs | |
| 389 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 390 | + conditions.append( | |
| 391 | + (dataframe[f"{self.config['stake_currency']}_rsi"] < params['xtra-base-stake-rsi']) | | |
| 392 | + (dataframe[f"{self.custom_fiat}_rsi"] > params['xtra-base-fiat-rsi']) | |
| 393 | + ) | |
| 394 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 395 | + | |
| 396 | + # Applies to active or new trades | |
| 397 | + conditions.append(dataframe['volume'].gt(0)) | |
| 398 | + | |
| 399 | + if conditions: | |
| 400 | + dataframe.loc[ | |
| 401 | + reduce(lambda x, y: x & y, conditions), | |
| 402 | + 'buy'] = 1 | |
| 403 | + | |
| 404 | + return dataframe | |
| 405 | + | |
| 406 | + """ | |
| 407 | + Sell Signal | |
| 408 | + """ | |
| 409 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 410 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 411 | + at = self.custom_active_trade | |
| 412 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 413 | + conditions = [] | |
| 414 | + | |
| 415 | + """ | |
| 416 | + Previous Schism sell implementation has been *partially* replaced by custom_stoploss. | |
| 417 | + Doing it there makes it able to be backtested more realistically but some of the functionality | |
| 418 | + such as the ability to use other trades or the # of slots in our decision need to remain here. | |
| 419 | + | |
| 420 | + The current sell is meant to be a pre-stoploss bailout but most sells at a loss | |
| 421 | + should happen due to the stoploss in live/dry. | |
| 422 | + | |
| 423 | + ** Only part of this signal functions in backtest/hyperopt. Can only be optimized in live/dry. | |
| 424 | + ** Results in backtest/hyperopts will sell far more readily than in live due to the profit guards. | |
| 425 | + """ | |
| 426 | + | |
| 427 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 428 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 429 | + if trade_data['active_trade']: | |
| 430 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 431 | + # a trade to go into the negative a little bit before we react to sell. | |
| 432 | + loss_cutoff = cta.linear_growth(at['loss-start'], at['loss-end'], | |
| 433 | + at['loss-delay'], at['loss-time'], trade_data['open_minutes']) | |
| 434 | + | |
| 435 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 436 | + | |
| 437 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 438 | + if trade_data['other_trades']: | |
| 439 | + if trade_data['free_slots'] > 0: | |
| 440 | + # If the average of all our other trades is below a certain threshold based | |
| 441 | + # on free slots available, hold and wait for market recovery. | |
| 442 | + hold_pct = (1/trade_data['free_slots']) * at['sell-mkt-down'] | |
| 443 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 444 | + else: | |
| 445 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 446 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 447 | + | |
| 448 | + # Primary sell trigger | |
| 449 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 450 | + conditions.append( | |
| 451 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 452 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 453 | + (dataframe['volume'].gt(0)) | |
| 454 | + ) | |
| 455 | + | |
| 456 | + # TODO: Evaluate PMAX in dry/live | |
| 457 | + if params['sell-pmax-enable'] == True: | |
| 458 | + conditions.append((dataframe['pmax-trend'] == 'down')) | |
| 459 | + | |
| 460 | + if conditions: | |
| 461 | + dataframe.loc[ | |
| 462 | + reduce(lambda x, y: x & y, conditions), | |
| 463 | + 'sell'] = 1 | |
| 464 | + | |
| 465 | + return dataframe | |
| 466 | + | |
| 467 | + """ | |
| 468 | + Custom Stoploss | |
| 469 | + """ | |
| 470 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 471 | + start = self.custom_stop['decay-start'] | |
| 472 | + end = self.custom_stop['decay-end'] | |
| 473 | + time = self.custom_stop['decay-time'] | |
| 474 | + delay = self.custom_stop['decay-delay'] | |
| 475 | + pos_trail = self.custom_stop['pos-trail'] | |
| 476 | + pos_threshold = self.custom_stop['pos-threshold'] | |
| 477 | + pos_trail_dist = self.custom_stop['pos-trail-dist'] | |
| 478 | + | |
| 479 | + open_minutes: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 480 | + | |
| 481 | + decay_stoploss = cta.linear_growth(start, end, delay, time, open_minutes) | |
| 482 | + | |
| 483 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 484 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 485 | + profit_diff = current_profit - min_profit | |
| 486 | + | |
| 487 | + if pos_trail == True: | |
| 488 | + # if trade is positive above threshold, immediately move the stoploss up to x% behind it | |
| 489 | + if current_profit > pos_threshold: | |
| 490 | + return current_profit - pos_trail_dist | |
| 491 | + | |
| 492 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 493 | + if current_profit > min_profit: | |
| 494 | + if profit_diff > 0.015: | |
| 495 | + return min_profit | |
| 496 | + return -1 | |
| 497 | + | |
| 498 | + # otherwise return the time decaying stoploss | |
| 499 | + return decay_stoploss | |
| 500 | + | |
| 501 | + """ | |
| 502 | + Trade Timeout Overloads | |
| 503 | + """ | |
| 504 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 505 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 506 | + ob = self.dp.orderbook(pair, 1) | |
| 507 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 508 | + if current_price > order['price'] * 1.01: | |
| 509 | + return True | |
| 510 | + return False | |
| 511 | + | |
| 512 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 513 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 514 | + ob = self.dp.orderbook(pair, 1) | |
| 515 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 516 | + if current_price < order['price'] * 0.99: | |
| 517 | + return True | |
| 518 | + return False | |
| 519 | + | |
| 520 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 521 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 522 | + ob = self.dp.orderbook(pair, 1) | |
| 523 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 524 | + if current_price > rate * 1.01: | |
| 525 | + return False | |
| 526 | + return True | |
| 527 | + | |
| 528 | + """ | |
| 529 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 530 | + """ | |
| 531 | + def min_roi_reached_dynamic(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 532 | + | |
| 533 | + dynamic_roi = self.dynamic_roi | |
| 534 | + minimal_roi = self.minimal_roi | |
| 535 | + | |
| 536 | + if not dynamic_roi: | |
| 537 | + return None, None | |
| 538 | + | |
| 539 | + if 'dynamic_roi_type' in dynamic_roi and dynamic_roi['dynamic_roi_type'] \ | |
| 540 | + in ['linear', 'exponential', 'connect']: | |
| 541 | + roi_type = dynamic_roi['dynamic_roi_type'] | |
| 542 | + # linear decay: f(t) = start - (rate * t) | |
| 543 | + if roi_type == 'linear': | |
| 544 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 545 | + 'dynamic_roi_time' in dynamic_roi: | |
| 546 | + start = dynamic_roi['dynamic_roi_start'] | |
| 547 | + end = dynamic_roi['dynamic_roi_end'] | |
| 548 | + time = dynamic_roi['dynamic_roi_time'] | |
| 549 | + rate = (start - end) / time | |
| 550 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 551 | + else: | |
| 552 | + return None, None | |
| 553 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 554 | + elif roi_type == 'exponential': | |
| 555 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 556 | + 'dynamic_roi_rate' in dynamic_roi: | |
| 557 | + start = dynamic_roi['dynamic_roi_start'] | |
| 558 | + end = dynamic_roi['dynamic_roi_end'] | |
| 559 | + rate = dynamic_roi['dynamic_roi_rate'] | |
| 560 | + min_roi = max(end, start * np.exp(-rate*trade_dur)) | |
| 561 | + else: | |
| 562 | + return None, None | |
| 563 | + # "connect the dots" between the points on the minima_roi table | |
| 564 | + elif roi_type == 'connect': | |
| 565 | + if not minimal_roi: | |
| 566 | + return None, None | |
| 567 | + # figure out where we are in the defined roi table | |
| 568 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 569 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 570 | + # if we are past the final point in the table, use that key/vaule pair | |
| 571 | + if not past_roi: | |
| 572 | + return None, None | |
| 573 | + current_entry = max(past_roi) | |
| 574 | + if not next_roi: | |
| 575 | + return current_entry, minimal_roi[current_entry] | |
| 576 | + next_entry = min(next_roi) | |
| 577 | + # use the slope-intercept formula between the two points | |
| 578 | + # y = mx + b | |
| 579 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 580 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 581 | + m = (y1-y2)/(x1-x2) | |
| 582 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 583 | + min_roi = (m * trade_dur) + b | |
| 584 | + else: | |
| 585 | + return None, None | |
| 586 | + | |
| 587 | + return trade_dur, min_roi | |
| 588 | + | |
| 589 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 590 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 591 | + | |
| 592 | + if self.dynamic_roi and 'dynamic_roi_enabled' in self.dynamic_roi \ | |
| 593 | + and self.dynamic_roi['dynamic_roi_enabled']: | |
| 594 | + _, roi = self.min_roi_reached_dynamic(trade_dur) | |
| 595 | + else: | |
| 596 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 597 | + if roi is None: | |
| 598 | + return False | |
| 599 | + else: | |
| 600 | + return current_profit > roi | |
| 601 | + | |
| 602 | + """ | |
| 603 | + Custom Methods for Strategy Parameters, Trade, and Price Data | |
| 604 | + Consider splitting this out into a helper file. | |
| 605 | + """ | |
| 606 | + def populate_trades(self, pair: str) -> dict: | |
| 607 | + """ | |
| 608 | + Query the database and populate the custom_trade_info dict. | |
| 609 | + """ | |
| 610 | + if not pair in self.custom_trade_info: | |
| 611 | + self.custom_trade_info[pair] = {} | |
| 612 | + | |
| 613 | + trade_data = {} | |
| 614 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 615 | + | |
| 616 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 617 | + | |
| 618 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 619 | + | |
| 620 | + if active_trade: | |
| 621 | + current_rate = self.get_current_price(pair, True) | |
| 622 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 623 | + | |
| 624 | + present = arrow.utcnow() | |
| 625 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 626 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 627 | + | |
| 628 | + trade_data['active_trade'] = True | |
| 629 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 630 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 631 | + trade_data['open_minutes'] : int = open_minutes | |
| 632 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 633 | + else: | |
| 634 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 635 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 636 | + | |
| 637 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 638 | + | |
| 639 | + if other_trades: | |
| 640 | + trade_data['other_trades'] = True | |
| 641 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 642 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 643 | + if trade_data['current_profit'] < min(other_profit): | |
| 644 | + trade_data['biggest_loser'] = True | |
| 645 | + else: | |
| 646 | + trade_data['avg_other_profit'] = 0 | |
| 647 | + | |
| 648 | + open_trades = len(Trade.get_open_trades()) | |
| 649 | + # this was lazy. | |
| 650 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 651 | + | |
| 652 | + return trade_data | |
| 653 | + | |
| 654 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 655 | + """ | |
| 656 | + Query the exchange for current price information, used in profit calculations. | |
| 657 | + Implements a cache to prevent excessive api calls. | |
| 658 | + """ | |
| 659 | + if not refresh: | |
| 660 | + rate = self.custom_current_price_cache.get(pair) | |
| 661 | + if rate: | |
| 662 | + return rate | |
| 663 | + | |
| 664 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 665 | + if ask_strategy.get('use_order_book', False): | |
| 666 | + ob = self.dp.orderbook(pair, 1) | |
| 667 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 668 | + else: | |
| 669 | + ticker = self.dp.ticker(pair) | |
| 670 | + rate = ticker['last'] | |
| 671 | + | |
| 672 | + self.custom_current_price_cache[pair] = rate | |
| 673 | + return rate | |
| 674 | + | |
| 675 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 676 | + """ | |
| 677 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 678 | + TODO: | |
| 679 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 680 | + """ | |
| 681 | + buy_params = self.buy_params | |
| 682 | + sell_params = self.sell_params | |
| 683 | + | |
| 684 | + if self.custom_pair_params: | |
| 685 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 686 | + if custom_params['buy_params']: | |
| 687 | + buy_params = custom_params['buy_params'] | |
| 688 | + if custom_params['sell_params']: | |
| 689 | + sell_params = custom_params['sell_params'] | |
| 690 | + | |
| 691 | + if side == 'sell': | |
| 692 | + return sell_params | |
| 693 | + | |
| 694 | + return buy_params | |
| 695 | + | |
| 696 | +# Sub-strategy with parameters specific to BTC stake | |
| 697 | +class Solipsis_BTC(Solipsis): | |
| 698 | + | |
| 699 | + timeframe = '1h' | |
| 700 | + inf_timeframe = '4h' | |
| 701 | + | |
| 702 | + buy_params = { | |
| 703 | + 'inf-rsi': 64, | |
| 704 | + 'mp': 55, | |
| 705 | + 'rmi-fast': 31, | |
| 706 | + 'rmi-slow': 16, | |
| 707 | + 'xinf-stake-rmi': 67, | |
| 708 | + 'xtf-fiat-rsi': 17, | |
| 709 | + 'xtf-stake-rsi': 57 | |
| 710 | + } | |
| 711 | + | |
| 712 | + minimal_roi = { | |
| 713 | + "0": 0.05, | |
| 714 | + "240": 0.025, | |
| 715 | + "1440": 0.01, | |
| 716 | + "4320": 0 | |
| 717 | + } | |
| 718 | + | |
| 719 | + stoploss = -0.30 | |
| 720 | + use_custom_stoploss = False | |
| 721 | + | |
| 722 | +# Sub-strategy with parameters specific to ETH stake | |
| 723 | +class Solipsis_ETH(Solipsis): | |
| 724 | + | |
| 725 | + timeframe = '1h' | |
| 726 | + inf_timeframe = '4h' | |
| 727 | + | |
| 728 | + buy_params = { | |
| 729 | + 'inf-rsi': 13, | |
| 730 | + 'inf-stake-rmi': 69, | |
| 731 | + 'mp': 40, | |
| 732 | + 'rmi-fast': 42, | |
| 733 | + 'rmi-slow': 17, | |
| 734 | + 'tf-fiat-rsi': 15, | |
| 735 | + 'tf-stake-rsi': 92 | |
| 736 | + } | |
| 737 | + | |
| 738 | + minimal_roi = { | |
| 739 | + "0": 0.05, | |
| 740 | + "240": 0.025, | |
| 741 | + "1440": 0.01, | |
| 742 | + "4320": 0 | |
| 743 | + } | |
| 744 | + | |
| 745 | + stoploss = -0.30 | |
| 746 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v2.4.py +581 −0
| @@ -0,0 +1,581 @@ | ||
| 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 | |
| 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 | +from technical.consensus import Consensus | |
| 25 | + | |
| 26 | +class Solipsis(IStrategy): | |
| 27 | + | |
| 28 | + # Recommended for USD/USDT/etc. | |
| 29 | + timeframe = '5m' | |
| 30 | + inf_timeframe = '1h' | |
| 31 | + | |
| 32 | + buy_params = { | |
| 33 | + 'consensus-buy': 0, | |
| 34 | + 'inf-guard': 'upper', | |
| 35 | + 'inf-pct-adr-bot': 0.09086, | |
| 36 | + 'inf-pct-adr-top': 0.78614, | |
| 37 | + 'xbtc-consensus-buy': 31, | |
| 38 | + 'xtra-base-fiat-rmi': 15, | |
| 39 | + 'xtra-base-stake-rmi': 23, | |
| 40 | + 'xtra-inf-stake-rmi': 33 | |
| 41 | + } | |
| 42 | + | |
| 43 | + sell_params = {} | |
| 44 | + | |
| 45 | + # Custom buy/sell parameters per pair | |
| 46 | + custom_pair_params = [] | |
| 47 | + | |
| 48 | + # Recommended on 5m timeframe | |
| 49 | + minimal_roi = { | |
| 50 | + "0": 0.01, | |
| 51 | + "360": 0.005, | |
| 52 | + "720": 0 | |
| 53 | + } | |
| 54 | + | |
| 55 | + dynamic_roi = { | |
| 56 | + 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 57 | + 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 58 | + 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 59 | + 'rmi-end': 70, # ending value | |
| 60 | + 'grow-delay': 180, # delay on growth | |
| 61 | + 'grow-time': 720, # finish time of growth | |
| 62 | + 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 63 | + 'min-roc-atr': 0 # minimum roi value to return in roc or atr mode | |
| 64 | + } | |
| 65 | + | |
| 66 | + stoploss = -0.30 | |
| 67 | + | |
| 68 | + use_custom_stoploss = True | |
| 69 | + custom_stop = { | |
| 70 | + # Linear Decay Parameters | |
| 71 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 72 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 73 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 74 | + 'decay-end': -0.01, # ending value | |
| 75 | + # Profit and TA | |
| 76 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 77 | + 'cur-threshold': -0.01, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 78 | + 'roc-bail': -0.04, # value for roc to use for dynamic bailout | |
| 79 | + 'con-bail': 50, # value for consensus-sell to use for dynamic bailout | |
| 80 | + 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 81 | + 'con-trend': 50, # consensus-buy value to pause stoploss decay | |
| 82 | + 'bail-how': 'atr', # set the stoploss to the atr offset below current price, or immediate | |
| 83 | + # Positive Trailing | |
| 84 | + 'pos-trail': True, # enable trailing once positive | |
| 85 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 86 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 87 | + } | |
| 88 | + | |
| 89 | + # Recommended | |
| 90 | + use_sell_signal = False | |
| 91 | + sell_profit_only = False | |
| 92 | + ignore_roi_if_buy_signal = True | |
| 93 | + | |
| 94 | + # Required | |
| 95 | + startup_candle_count: int = 72 | |
| 96 | + process_only_new_candles = False | |
| 97 | + | |
| 98 | + # Strategy Specific Variable Storage | |
| 99 | + custom_trade_info = {} | |
| 100 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 101 | + | |
| 102 | + """ | |
| 103 | + Informative Pair Definitions | |
| 104 | + """ | |
| 105 | + def informative_pairs(self): | |
| 106 | + # add all whitelisted pairs on informative timeframe | |
| 107 | + pairs = self.dp.current_whitelist() | |
| 108 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 109 | + | |
| 110 | + # add extra informative pairs if the stake is BTC or ETH | |
| 111 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 112 | + for pair in pairs: | |
| 113 | + coin, stake = pair.split('/') | |
| 114 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 115 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 116 | + | |
| 117 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 118 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 119 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 120 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 121 | + else: | |
| 122 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 123 | + if not btc_stake in pairs: | |
| 124 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 125 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 126 | + | |
| 127 | + return informative_pairs | |
| 128 | + | |
| 129 | + """ | |
| 130 | + Indicator Definitions | |
| 131 | + """ | |
| 132 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 133 | + if not metadata['pair'] in self.custom_trade_info: | |
| 134 | + self.custom_trade_info[metadata['pair']] = {} | |
| 135 | + | |
| 136 | + c = Consensus(dataframe) | |
| 137 | + | |
| 138 | + # Overlap / MA's | |
| 139 | + c.evaluate_tema(period=12) | |
| 140 | + c.evaluate_ema(period=6) | |
| 141 | + c.evaluate_ema(period=12) | |
| 142 | + c.evaluate_sma(period=12) | |
| 143 | + c.evaluate_ichimoku() # slightly slow | |
| 144 | + #c.evaluate_hull() # very slow | |
| 145 | + c.evaluate_vwma(period=20) | |
| 146 | + | |
| 147 | + # Oscillators | |
| 148 | + c.evaluate_rsi(period=14) | |
| 149 | + c.evaluate_stoch() | |
| 150 | + #c.evaluate_cci() # slightly slow | |
| 151 | + #c.evaluate_adx() | |
| 152 | + c.evaluate_macd() | |
| 153 | + c.evaluate_momentum() | |
| 154 | + c.evaluate_williams() | |
| 155 | + # c.evaluate_ultimate_oscilator() # extremely slow | |
| 156 | + # missing: awesome osc | |
| 157 | + # missing: bull bear | |
| 158 | + # missing: stoch rsi | |
| 159 | + | |
| 160 | + #c.evaluate_macd_cross_over() | |
| 161 | + c.evaluate_osc() | |
| 162 | + c.evaluate_cmf() | |
| 163 | + c.evaluate_cmo() # slightly slow | |
| 164 | + #c.evaluate_laguerre() # slow | |
| 165 | + | |
| 166 | + dataframe['consensus-buy'] = c.score()['buy'] | |
| 167 | + dataframe['consensus-sell'] = c.score()['sell'] | |
| 168 | + | |
| 169 | + # Indicators for ROI and Custom Stoploss | |
| 170 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 171 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 172 | + | |
| 173 | + # Trend Indicators for ROI | |
| 174 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 175 | + | |
| 176 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 177 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 178 | + | |
| 179 | + # Base pair informative timeframe indicators | |
| 180 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 181 | + | |
| 182 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 183 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 184 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 185 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 186 | + | |
| 187 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 188 | + | |
| 189 | + # Other stake specific informative indicators | |
| 190 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 191 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 192 | + coin, stake = metadata['pair'].split('/') | |
| 193 | + fiat = self.custom_fiat | |
| 194 | + coin_fiat = f"{coin}/{fiat}" | |
| 195 | + stake_fiat = f"{stake}/{fiat}" | |
| 196 | + | |
| 197 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 198 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 199 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 200 | + | |
| 201 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 202 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 203 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 204 | + | |
| 205 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 206 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 207 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 208 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 209 | + | |
| 210 | + # Informatives for BTC/STAKE if not in whitelist | |
| 211 | + else: | |
| 212 | + pairs = self.dp.current_whitelist() | |
| 213 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 214 | + if not btc_stake in pairs: | |
| 215 | + # BTC/STAKE - Base Timeframe | |
| 216 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 217 | + cbtc = Consensus(btc_stake_tf) | |
| 218 | + | |
| 219 | + cbtc.evaluate_tema(period=12) | |
| 220 | + cbtc.evaluate_ema(period=12) | |
| 221 | + cbtc.evaluate_ema(period=24) | |
| 222 | + cbtc.evaluate_sma(period=12) | |
| 223 | + cbtc.evaluate_ichimoku() | |
| 224 | + cbtc.evaluate_vwma(period=20) | |
| 225 | + cbtc.evaluate_rsi(period=14) | |
| 226 | + cbtc.evaluate_stoch() | |
| 227 | + cbtc.evaluate_macd() | |
| 228 | + cbtc.evaluate_momentum() | |
| 229 | + cbtc.evaluate_williams() | |
| 230 | + cbtc.evaluate_osc() | |
| 231 | + cbtc.evaluate_cmf() | |
| 232 | + cbtc.evaluate_cmo() | |
| 233 | + cbtc.evaluate_laguerre() | |
| 234 | + | |
| 235 | + dataframe['BTC_consensus-buy'] = cbtc.score()['buy'] | |
| 236 | + | |
| 237 | + # BTC/STAKE - Informative Timeframe | |
| 238 | + # btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 239 | + # dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 240 | + | |
| 241 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 242 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 243 | + # Attempting to use a temporary holding place for dynamic roi backtest return value... | |
| 244 | + if not 'backtest' in self.custom_trade_info: | |
| 245 | + self.custom_trade_info['backtest'] = {} | |
| 246 | + | |
| 247 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 248 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 249 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 250 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 251 | + self.custom_trade_info[metadata['pair']]['consensus-buy'] = dataframe[['date', 'consensus-buy']].copy().set_index('date') | |
| 252 | + self.custom_trade_info[metadata['pair']]['consensus-sell'] = dataframe[['date', 'consensus-sell']].copy().set_index('date') | |
| 253 | + | |
| 254 | + return dataframe | |
| 255 | + | |
| 256 | + """ | |
| 257 | + Buy Signal | |
| 258 | + """ | |
| 259 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 260 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 261 | + conditions = [] | |
| 262 | + | |
| 263 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 264 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 265 | + conditions.append( | |
| 266 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 267 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 268 | + ) | |
| 269 | + | |
| 270 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 271 | + conditions.append( | |
| 272 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 273 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 274 | + ) | |
| 275 | + | |
| 276 | + conditions.append(dataframe['consensus-buy'] > params['consensus-buy']) | |
| 277 | + | |
| 278 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 279 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 280 | + conditions.append( | |
| 281 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 282 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 283 | + ) | |
| 284 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 285 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 286 | + else: | |
| 287 | + pairs = self.dp.current_whitelist() | |
| 288 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 289 | + if not btc_stake in pairs: | |
| 290 | + conditions.append(dataframe['BTC_consensus-buy'] > params['xbtc-consensus-buy']) | |
| 291 | + | |
| 292 | + # Applies to active or new trades | |
| 293 | + conditions.append(dataframe['volume'].gt(0)) | |
| 294 | + | |
| 295 | + if conditions: | |
| 296 | + dataframe.loc[ | |
| 297 | + reduce(lambda x, y: x & y, conditions), | |
| 298 | + 'buy'] = 1 | |
| 299 | + | |
| 300 | + return dataframe | |
| 301 | + | |
| 302 | + """ | |
| 303 | + Sell Signal | |
| 304 | + """ | |
| 305 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 306 | + # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 307 | + | |
| 308 | + dataframe['sell'] = 0 | |
| 309 | + | |
| 310 | + return dataframe | |
| 311 | + | |
| 312 | + """ | |
| 313 | + Custom Stoploss | |
| 314 | + """ | |
| 315 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 316 | + cs = self.get_pair_params(pair, 'custom_stop') | |
| 317 | + | |
| 318 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 319 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 320 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 321 | + profit_diff = current_profit - min_profit | |
| 322 | + | |
| 323 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], trade_dur) | |
| 324 | + | |
| 325 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 326 | + if cs['pos-trail'] == True: | |
| 327 | + if current_profit > cs['pos-threshold']: | |
| 328 | + return current_profit - cs['pos-trail-dist'] | |
| 329 | + | |
| 330 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 331 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 332 | + roc = dataframe['roc'].iat[-1] | |
| 333 | + atr = dataframe['atr'].iat[-1] | |
| 334 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 335 | + consensus_buy = dataframe['consensus-buy'].iat[-1] | |
| 336 | + consensus_sell = dataframe['consensus-sell'].iat[-1] | |
| 337 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 338 | + else: | |
| 339 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 340 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 341 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 342 | + consensus_buy = self.custom_trade_info[trade.pair]['consensus-buy'].loc[current_time]['consensus-buy'] | |
| 343 | + consensus_sell = self.custom_trade_info[trade.pair]['consensus-sell'].loc[current_time]['consensus-sell'] | |
| 344 | + | |
| 345 | + if current_profit < cs['cur-threshold']: | |
| 346 | + # Dynamic bailout based on rate of change | |
| 347 | + if (roc/100) <= cs['roc-bail'] or cs['con-bail'] <= consensus_sell: | |
| 348 | + if cs['bail-how'] == 'atr': | |
| 349 | + return ((current_rate - atr)/current_rate) - 1 | |
| 350 | + elif cs['bail-how'] == 'immediate': | |
| 351 | + return current_rate | |
| 352 | + else: | |
| 353 | + return decay_stoploss | |
| 354 | + | |
| 355 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 356 | + if (current_profit > min_profit) or roc > 0 or rmi_slow >= cs['rmi-trend'] or consensus_buy >= cs['con-trend']: | |
| 357 | + if profit_diff > cs['cur-min-diff']: | |
| 358 | + return min_profit | |
| 359 | + return -1 | |
| 360 | + | |
| 361 | + return decay_stoploss | |
| 362 | + | |
| 363 | + """ | |
| 364 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 365 | + """ | |
| 366 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 367 | + | |
| 368 | + dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 369 | + minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 370 | + | |
| 371 | + if not dynamic_roi or not minimal_roi: | |
| 372 | + return None, None | |
| 373 | + | |
| 374 | + _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 375 | + | |
| 376 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 377 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 378 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 379 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 380 | + roc = dataframe['roc'].iat[-1] | |
| 381 | + atr = dataframe['atr'].iat[-1] | |
| 382 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 383 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 384 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 385 | + else: | |
| 386 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 387 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 388 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 389 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 390 | + | |
| 391 | + d = dynamic_roi | |
| 392 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 393 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 394 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 395 | + open_rate = trade.open_rate | |
| 396 | + | |
| 397 | + atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 398 | + roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 399 | + | |
| 400 | + # atr as the fallback (if > min-roc-atr) | |
| 401 | + if d['fallback'] == 'atr': | |
| 402 | + min_roi = atr_roi | |
| 403 | + # roc as the fallback (if > min-roc-atr) | |
| 404 | + elif d['fallback'] == 'roc': | |
| 405 | + min_roi = roc_roi | |
| 406 | + # atr or table as the fallback (whichever is larger) | |
| 407 | + elif d['fallback'] == 'atr-table': | |
| 408 | + min_roi = max(table_roi, atr_roi) | |
| 409 | + # roc or table as the fallback (whichever is larger) | |
| 410 | + elif d['fallback'] == 'roc-table': | |
| 411 | + min_roi = max(table_roi, roc_roi) | |
| 412 | + # default to table | |
| 413 | + else: | |
| 414 | + min_roi = table_roi | |
| 415 | + | |
| 416 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 417 | + if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 418 | + if current_profit > min_roi and (current_profit < (max_profit * profit_factor)): | |
| 419 | + min_roi = min_roi | |
| 420 | + else: | |
| 421 | + min_roi = 100 | |
| 422 | + | |
| 423 | + """ | |
| 424 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 425 | + if (current_profit > (max_profit * profit_factor)) and (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 426 | + min_roi = 100 | |
| 427 | + """ | |
| 428 | + | |
| 429 | + else: | |
| 430 | + min_roi = table_roi | |
| 431 | + | |
| 432 | + # Attempting to wedge the dynamic roi value into a thing so we can trick backtesting... | |
| 433 | + if self.config['runmode'].value not in ('live', 'dry_run'): | |
| 434 | + # Theoretically, if backtesting uses this value, ROI was triggered so we need to trick it with a sell | |
| 435 | + # rate other than what is on the standard ROI table... | |
| 436 | + self.custom_trade_info['backtest']['roi'] = max(min_roi, current_profit) | |
| 437 | + | |
| 438 | + return trade_dur, min_roi | |
| 439 | + | |
| 440 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 441 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 442 | + | |
| 443 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 444 | + if not roi_list: | |
| 445 | + return None, None | |
| 446 | + roi_entry = max(roi_list) | |
| 447 | + min_roi = minimal_roi[roi_entry] | |
| 448 | + | |
| 449 | + # Attempting to take the dynamic roi value out of a thing so we can trick backtesting... | |
| 450 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 451 | + if pair == 'backtest': | |
| 452 | + min_roi = self.custom_trade_info['backtest']['roi'] | |
| 453 | + | |
| 454 | + return roi_entry, min_roi | |
| 455 | + | |
| 456 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 457 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 458 | + | |
| 459 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 460 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 461 | + else: | |
| 462 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 463 | + if roi is None: | |
| 464 | + return False | |
| 465 | + else: | |
| 466 | + return current_profit > roi | |
| 467 | + | |
| 468 | + """ | |
| 469 | + Trade Timeout Overloads | |
| 470 | + """ | |
| 471 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 472 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 473 | + ob = self.dp.orderbook(pair, 1) | |
| 474 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 475 | + if current_price > order['price'] * 1.01: | |
| 476 | + return True | |
| 477 | + return False | |
| 478 | + | |
| 479 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 480 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 481 | + ob = self.dp.orderbook(pair, 1) | |
| 482 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 483 | + if current_price < order['price'] * 0.99: | |
| 484 | + return True | |
| 485 | + return False | |
| 486 | + | |
| 487 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 488 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 489 | + ob = self.dp.orderbook(pair, 1) | |
| 490 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 491 | + if current_price > rate * 1.01: | |
| 492 | + return False | |
| 493 | + return True | |
| 494 | + | |
| 495 | + """ | |
| 496 | + Custom Methods | |
| 497 | + """ | |
| 498 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 499 | + buy_params = self.buy_params | |
| 500 | + sell_params = self.sell_params | |
| 501 | + minimal_roi = self.minimal_roi | |
| 502 | + custom_stop = self.custom_stop | |
| 503 | + dynamic_roi = self.dynamic_roi | |
| 504 | + | |
| 505 | + if self.custom_pair_params: | |
| 506 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 507 | + if custom_params['buy_params']: | |
| 508 | + buy_params = custom_params['buy_params'] | |
| 509 | + if custom_params['sell_params']: | |
| 510 | + sell_params = custom_params['sell_params'] | |
| 511 | + if custom_params['minimal_roi']: | |
| 512 | + custom_stop = custom_params['minimal_roi'] | |
| 513 | + if custom_params['custom_stop']: | |
| 514 | + custom_stop = custom_params['custom_stop'] | |
| 515 | + if custom_params['dynamic_roi']: | |
| 516 | + dynamic_roi = custom_params['dynamic_roi'] | |
| 517 | + | |
| 518 | + if params == 'buy': | |
| 519 | + return buy_params | |
| 520 | + if params == 'sell': | |
| 521 | + return sell_params | |
| 522 | + if params == 'minimal_roi': | |
| 523 | + return minimal_roi | |
| 524 | + if params == 'custom_stop': | |
| 525 | + return custom_stop | |
| 526 | + if params == 'dynamic_roi': | |
| 527 | + return dynamic_roi | |
| 528 | + | |
| 529 | + return False | |
| 530 | + | |
| 531 | +# Sub-strategy with parameters specific to BTC stake | |
| 532 | +class Solipsis_BTC(Solipsis): | |
| 533 | + | |
| 534 | + timeframe = '1h' | |
| 535 | + inf_timeframe = '4h' | |
| 536 | + | |
| 537 | + buy_params = { | |
| 538 | + 'inf-rsi': 64, | |
| 539 | + 'mp': 55, | |
| 540 | + 'rmi-fast': 31, | |
| 541 | + 'rmi-slow': 16, | |
| 542 | + 'xinf-stake-rmi': 67, | |
| 543 | + 'xtf-fiat-rsi': 17, | |
| 544 | + 'xtf-stake-rsi': 57 | |
| 545 | + } | |
| 546 | + | |
| 547 | + minimal_roi = { | |
| 548 | + "0": 0.05, | |
| 549 | + "240": 0.025, | |
| 550 | + "1440": 0.01, | |
| 551 | + "4320": 0 | |
| 552 | + } | |
| 553 | + | |
| 554 | + stoploss = -0.30 | |
| 555 | + use_custom_stoploss = False | |
| 556 | + | |
| 557 | +# Sub-strategy with parameters specific to ETH stake | |
| 558 | +class Solipsis_ETH(Solipsis): | |
| 559 | + | |
| 560 | + timeframe = '1h' | |
| 561 | + inf_timeframe = '4h' | |
| 562 | + | |
| 563 | + buy_params = { | |
| 564 | + 'inf-rsi': 13, | |
| 565 | + 'inf-stake-rmi': 69, | |
| 566 | + 'mp': 40, | |
| 567 | + 'rmi-fast': 42, | |
| 568 | + 'rmi-slow': 17, | |
| 569 | + 'tf-fiat-rsi': 15, | |
| 570 | + 'tf-stake-rsi': 92 | |
| 571 | + } | |
| 572 | + | |
| 573 | + minimal_roi = { | |
| 574 | + "0": 0.05, | |
| 575 | + "240": 0.025, | |
| 576 | + "1440": 0.01, | |
| 577 | + "4320": 0 | |
| 578 | + } | |
| 579 | + | |
| 580 | + stoploss = -0.30 | |
| 581 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v2.5.py +514 −0
| @@ -0,0 +1,514 @@ | ||
| 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 | |
| 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 | +class Solipsis5(IStrategy): | |
| 26 | + | |
| 27 | + # Recommended for USD/USDT/etc. | |
| 28 | + timeframe = '5m' | |
| 29 | + inf_timeframe = '1h' | |
| 30 | + | |
| 31 | + # Buy hyperspace params: | |
| 32 | + buy_params = { | |
| 33 | + 'base-yolo': 5, | |
| 34 | + 'inf-guard': 'both', | |
| 35 | + 'inf-pct-adr-bot': 0.01874, | |
| 36 | + 'inf-pct-adr-top': 0.79384, | |
| 37 | + 'xbtc-base-rmi': 70, | |
| 38 | + 'xbtc-inf-rmi': 24, | |
| 39 | + 'xtra-base-fiat-rmi': 57, | |
| 40 | + 'xtra-base-stake-rmi': 11, | |
| 41 | + 'xtra-inf-stake-rmi': 33 | |
| 42 | + } | |
| 43 | + | |
| 44 | + sell_params = {} | |
| 45 | + | |
| 46 | + # Custom buy/sell parameters per pair | |
| 47 | + custom_pair_params = [] | |
| 48 | + | |
| 49 | + # Recommended on 5m timeframe | |
| 50 | + minimal_roi = { | |
| 51 | + "0": 0.01, | |
| 52 | + "360": 0.005, | |
| 53 | + "720": 0 | |
| 54 | + } | |
| 55 | + | |
| 56 | + dynamic_roi = { | |
| 57 | + 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 58 | + 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 59 | + 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 60 | + 'rmi-end': 70, # ending value | |
| 61 | + 'grow-delay': 180, # delay on growth | |
| 62 | + 'grow-time': 720, # finish time of growth | |
| 63 | + 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 64 | + 'min-roc-atr': 0 # minimum roi value to return in roc or atr mode | |
| 65 | + } | |
| 66 | + | |
| 67 | + stoploss = -0.30 | |
| 68 | + | |
| 69 | + use_custom_stoploss = True | |
| 70 | + custom_stop = { | |
| 71 | + # Linear Decay Parameters | |
| 72 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 73 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 74 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 75 | + 'decay-end': -0.01, # ending value | |
| 76 | + # Profit and TA | |
| 77 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 78 | + 'cur-threshold': -0.01, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 79 | + 'roc-bail': -0.04, # value for roc to use for dynamic bailout | |
| 80 | + 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 81 | + 'bail-how': 'atr', # set the stoploss to the atr offset below current price, or immediate | |
| 82 | + # Positive Trailing | |
| 83 | + 'pos-trail': True, # enable trailing once positive | |
| 84 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 85 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 86 | + } | |
| 87 | + | |
| 88 | + # Recommended | |
| 89 | + use_sell_signal = False | |
| 90 | + sell_profit_only = False | |
| 91 | + ignore_roi_if_buy_signal = False | |
| 92 | + | |
| 93 | + # Required | |
| 94 | + startup_candle_count: int = 72 | |
| 95 | + process_only_new_candles = False | |
| 96 | + | |
| 97 | + # Strategy Specific Variable Storage | |
| 98 | + custom_trade_info = {} | |
| 99 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 100 | + | |
| 101 | + """ | |
| 102 | + Informative Pair Definitions | |
| 103 | + """ | |
| 104 | + def informative_pairs(self): | |
| 105 | + # add all whitelisted pairs on informative timeframe | |
| 106 | + pairs = self.dp.current_whitelist() | |
| 107 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 108 | + | |
| 109 | + # add extra informative pairs if the stake is BTC or ETH | |
| 110 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 111 | + for pair in pairs: | |
| 112 | + coin, stake = pair.split('/') | |
| 113 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 114 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 115 | + | |
| 116 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 117 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 118 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 119 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 120 | + else: | |
| 121 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 122 | + if not btc_stake in pairs: | |
| 123 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 124 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 125 | + | |
| 126 | + return informative_pairs | |
| 127 | + | |
| 128 | + """ | |
| 129 | + Indicator Definitions | |
| 130 | + """ | |
| 131 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 132 | + if not metadata['pair'] in self.custom_trade_info: | |
| 133 | + self.custom_trade_info[metadata['pair']] = {} | |
| 134 | + | |
| 135 | + # Base timeframe indicators | |
| 136 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 137 | + | |
| 138 | + # Indicators for ROI and Custom Stoploss | |
| 139 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 140 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 141 | + | |
| 142 | + # Trends, Peaks and Crosses | |
| 143 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 144 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 145 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 146 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 147 | + | |
| 148 | + dataframe['green'] = np.where(dataframe['close'] > dataframe['open'], 1,0) | |
| 149 | + dataframe['green-count'] = dataframe['green'].rolling(10).sum() | |
| 150 | + dataframe['rand'] = np.random.randint(1, 10, dataframe.shape[0]) | |
| 151 | + dataframe['yolo'] = dataframe['rand'] + dataframe['green-count'] | |
| 152 | + | |
| 153 | + # Base pair informative timeframe indicators | |
| 154 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 155 | + | |
| 156 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 157 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 158 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 159 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 160 | + | |
| 161 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 162 | + | |
| 163 | + # Other stake specific informative indicators | |
| 164 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 165 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 166 | + coin, stake = metadata['pair'].split('/') | |
| 167 | + fiat = self.custom_fiat | |
| 168 | + coin_fiat = f"{coin}/{fiat}" | |
| 169 | + stake_fiat = f"{stake}/{fiat}" | |
| 170 | + | |
| 171 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 172 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 173 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 174 | + | |
| 175 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 176 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 177 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 178 | + | |
| 179 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 180 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 181 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 182 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 183 | + | |
| 184 | + # Informatives for BTC/STAKE if not in whitelist | |
| 185 | + else: | |
| 186 | + pairs = self.dp.current_whitelist() | |
| 187 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 188 | + if not btc_stake in pairs: | |
| 189 | + # BTC/STAKE - Base Timeframe | |
| 190 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 191 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 192 | + | |
| 193 | + # BTC/STAKE - Informative Timeframe | |
| 194 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 195 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 196 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 197 | + | |
| 198 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 199 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 200 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 201 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 202 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 203 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 204 | + | |
| 205 | + return dataframe | |
| 206 | + | |
| 207 | + """ | |
| 208 | + Buy Signal | |
| 209 | + """ | |
| 210 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 211 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 212 | + conditions = [] | |
| 213 | + | |
| 214 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 215 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 216 | + conditions.append( | |
| 217 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 218 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 219 | + ) | |
| 220 | + | |
| 221 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 222 | + conditions.append( | |
| 223 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 224 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 225 | + ) | |
| 226 | + | |
| 227 | + # YOLO ON THE BASE | |
| 228 | + conditions.append(dataframe['yolo'] > params['base-yolo']) | |
| 229 | + | |
| 230 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 231 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 232 | + conditions.append( | |
| 233 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 234 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 235 | + ) | |
| 236 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 237 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 238 | + else: | |
| 239 | + pairs = self.dp.current_whitelist() | |
| 240 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 241 | + if not btc_stake in pairs: | |
| 242 | + conditions.append( | |
| 243 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 244 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 245 | + ) | |
| 246 | + | |
| 247 | + conditions.append(dataframe['volume'].gt(0)) | |
| 248 | + | |
| 249 | + if conditions: | |
| 250 | + dataframe.loc[ | |
| 251 | + reduce(lambda x, y: x & y, conditions), | |
| 252 | + 'buy'] = 1 | |
| 253 | + | |
| 254 | + return dataframe | |
| 255 | + | |
| 256 | + """ | |
| 257 | + Sell Signal | |
| 258 | + """ | |
| 259 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 260 | + # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 261 | + | |
| 262 | + dataframe['sell'] = 0 | |
| 263 | + | |
| 264 | + return dataframe | |
| 265 | + | |
| 266 | + """ | |
| 267 | + Custom Stoploss | |
| 268 | + """ | |
| 269 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 270 | + cs = self.get_pair_params(pair, 'custom_stop') | |
| 271 | + | |
| 272 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 273 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 274 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 275 | + profit_diff = current_profit - min_profit | |
| 276 | + | |
| 277 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], trade_dur) | |
| 278 | + | |
| 279 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 280 | + if cs['pos-trail'] == True: | |
| 281 | + if current_profit > cs['pos-threshold']: | |
| 282 | + return current_profit - cs['pos-trail-dist'] | |
| 283 | + | |
| 284 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 285 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 286 | + roc = dataframe['roc'].iat[-1] | |
| 287 | + atr = dataframe['atr'].iat[-1] | |
| 288 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 289 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 290 | + else: | |
| 291 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 292 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 293 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 294 | + | |
| 295 | + if current_profit < cs['cur-threshold']: | |
| 296 | + # Dynamic bailout based on rate of change | |
| 297 | + if (roc/100) <= cs['roc-bail']: | |
| 298 | + if cs['bail-how'] == 'atr': | |
| 299 | + return ((current_rate - atr)/current_rate) - 1 | |
| 300 | + elif cs['bail-how'] == 'immediate': | |
| 301 | + return current_rate | |
| 302 | + else: | |
| 303 | + return decay_stoploss | |
| 304 | + | |
| 305 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 306 | + if (current_profit > min_profit) or roc > 0 or rmi_slow >= cs['rmi-trend']: | |
| 307 | + if profit_diff > cs['cur-min-diff']: | |
| 308 | + return min_profit | |
| 309 | + return -1 | |
| 310 | + | |
| 311 | + return decay_stoploss | |
| 312 | + | |
| 313 | + """ | |
| 314 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 315 | + """ | |
| 316 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 317 | + | |
| 318 | + dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 319 | + minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 320 | + | |
| 321 | + if not dynamic_roi or not minimal_roi: | |
| 322 | + return None, None | |
| 323 | + | |
| 324 | + _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 325 | + | |
| 326 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 327 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 328 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 329 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 330 | + roc = dataframe['roc'].iat[-1] | |
| 331 | + atr = dataframe['atr'].iat[-1] | |
| 332 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 333 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 334 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 335 | + else: | |
| 336 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 337 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 338 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 339 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 340 | + | |
| 341 | + d = dynamic_roi | |
| 342 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 343 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 344 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 345 | + open_rate = trade.open_rate | |
| 346 | + | |
| 347 | + atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 348 | + roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 349 | + | |
| 350 | + # atr as the fallback (if > min-roc-atr) | |
| 351 | + if d['fallback'] == 'atr': | |
| 352 | + min_roi = atr_roi | |
| 353 | + # roc as the fallback (if > min-roc-atr) | |
| 354 | + elif d['fallback'] == 'roc': | |
| 355 | + min_roi = roc_roi | |
| 356 | + # atr or table as the fallback (whichever is larger) | |
| 357 | + elif d['fallback'] == 'atr-table': | |
| 358 | + min_roi = max(table_roi, atr_roi) | |
| 359 | + # roc or table as the fallback (whichever is larger) | |
| 360 | + elif d['fallback'] == 'roc-table': | |
| 361 | + min_roi = max(table_roi, roc_roi) | |
| 362 | + # default to table | |
| 363 | + else: | |
| 364 | + min_roi = table_roi | |
| 365 | + | |
| 366 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 367 | + if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 368 | + if current_profit > min_roi and (current_profit < (max_profit * profit_factor)): | |
| 369 | + min_roi = min_roi | |
| 370 | + else: | |
| 371 | + min_roi = 100 | |
| 372 | + | |
| 373 | + else: | |
| 374 | + min_roi = table_roi | |
| 375 | + | |
| 376 | + return trade_dur, min_roi | |
| 377 | + | |
| 378 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 379 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 380 | + | |
| 381 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 382 | + if not roi_list: | |
| 383 | + return None, None | |
| 384 | + roi_entry = max(roi_list) | |
| 385 | + min_roi = minimal_roi[roi_entry] | |
| 386 | + | |
| 387 | + return roi_entry, min_roi | |
| 388 | + | |
| 389 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 390 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 391 | + | |
| 392 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 393 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 394 | + else: | |
| 395 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 396 | + if roi is None: | |
| 397 | + return False | |
| 398 | + else: | |
| 399 | + return current_profit > roi | |
| 400 | + | |
| 401 | + """ | |
| 402 | + Trade Timeout Overloads | |
| 403 | + """ | |
| 404 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 405 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 406 | + ob = self.dp.orderbook(pair, 1) | |
| 407 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 408 | + if current_price > order['price'] * 1.01: | |
| 409 | + return True | |
| 410 | + return False | |
| 411 | + | |
| 412 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 413 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 414 | + ob = self.dp.orderbook(pair, 1) | |
| 415 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 416 | + if current_price < order['price'] * 0.99: | |
| 417 | + return True | |
| 418 | + return False | |
| 419 | + | |
| 420 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 421 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 422 | + ob = self.dp.orderbook(pair, 1) | |
| 423 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 424 | + if current_price > rate * 1.01: | |
| 425 | + return False | |
| 426 | + return True | |
| 427 | + | |
| 428 | + """ | |
| 429 | + Custom Methods | |
| 430 | + """ | |
| 431 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 432 | + buy_params = self.buy_params | |
| 433 | + sell_params = self.sell_params | |
| 434 | + minimal_roi = self.minimal_roi | |
| 435 | + custom_stop = self.custom_stop | |
| 436 | + dynamic_roi = self.dynamic_roi | |
| 437 | + | |
| 438 | + if self.custom_pair_params: | |
| 439 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 440 | + if custom_params['buy_params']: | |
| 441 | + buy_params = custom_params['buy_params'] | |
| 442 | + if custom_params['sell_params']: | |
| 443 | + sell_params = custom_params['sell_params'] | |
| 444 | + if custom_params['minimal_roi']: | |
| 445 | + custom_stop = custom_params['minimal_roi'] | |
| 446 | + if custom_params['custom_stop']: | |
| 447 | + custom_stop = custom_params['custom_stop'] | |
| 448 | + if custom_params['dynamic_roi']: | |
| 449 | + dynamic_roi = custom_params['dynamic_roi'] | |
| 450 | + | |
| 451 | + if params == 'buy': | |
| 452 | + return buy_params | |
| 453 | + if params == 'sell': | |
| 454 | + return sell_params | |
| 455 | + if params == 'minimal_roi': | |
| 456 | + return minimal_roi | |
| 457 | + if params == 'custom_stop': | |
| 458 | + return custom_stop | |
| 459 | + if params == 'dynamic_roi': | |
| 460 | + return dynamic_roi | |
| 461 | + | |
| 462 | + return False | |
| 463 | + | |
| 464 | +# Sub-strategy with parameters specific to BTC stake | |
| 465 | +class Solipsis5_BTC(Solipsis5): | |
| 466 | + | |
| 467 | + timeframe = '1h' | |
| 468 | + inf_timeframe = '4h' | |
| 469 | + | |
| 470 | + buy_params = { | |
| 471 | + 'inf-rsi': 64, | |
| 472 | + 'mp': 55, | |
| 473 | + 'rmi-fast': 31, | |
| 474 | + 'rmi-slow': 16, | |
| 475 | + 'xinf-stake-rmi': 67, | |
| 476 | + 'xtf-fiat-rsi': 17, | |
| 477 | + 'xtf-stake-rsi': 57 | |
| 478 | + } | |
| 479 | + | |
| 480 | + minimal_roi = { | |
| 481 | + "0": 0.05, | |
| 482 | + "240": 0.025, | |
| 483 | + "1440": 0.01, | |
| 484 | + "4320": 0 | |
| 485 | + } | |
| 486 | + | |
| 487 | + stoploss = -0.30 | |
| 488 | + use_custom_stoploss = False | |
| 489 | + | |
| 490 | +# Sub-strategy with parameters specific to ETH stake | |
| 491 | +class Solipsis5_ETH(Solipsis5): | |
| 492 | + | |
| 493 | + timeframe = '1h' | |
| 494 | + inf_timeframe = '4h' | |
| 495 | + | |
| 496 | + buy_params = { | |
| 497 | + 'inf-rsi': 13, | |
| 498 | + 'inf-stake-rmi': 69, | |
| 499 | + 'mp': 40, | |
| 500 | + 'rmi-fast': 42, | |
| 501 | + 'rmi-slow': 17, | |
| 502 | + 'tf-fiat-rsi': 15, | |
| 503 | + 'tf-stake-rsi': 92 | |
| 504 | + } | |
| 505 | + | |
| 506 | + minimal_roi = { | |
| 507 | + "0": 0.05, | |
| 508 | + "240": 0.025, | |
| 509 | + "1440": 0.01, | |
| 510 | + "4320": 0 | |
| 511 | + } | |
| 512 | + | |
| 513 | + stoploss = -0.30 | |
| 514 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v2.6.py +580 −0
| @@ -0,0 +1,580 @@ | ||
| 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 | |
| 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 | +class Solipsis6(IStrategy): | |
| 27 | + | |
| 28 | + # Recommended for USD/USDT/etc. | |
| 29 | + timeframe = '5m' | |
| 30 | + inf_timeframe = '1h' | |
| 31 | + | |
| 32 | + buy_params = { | |
| 33 | + 'base-mp': 47, | |
| 34 | + 'base-rmi-fast': 34, | |
| 35 | + 'base-rmi-slow': 20, | |
| 36 | + 'inf-guard': 'upper', | |
| 37 | + 'inf-pct-adr-bot': 0.03689, | |
| 38 | + 'inf-pct-adr-top': 0.91524, | |
| 39 | + 'xbtc-base-rmi': 70, | |
| 40 | + 'xbtc-inf-rmi': 27, | |
| 41 | + 'xtra-base-fiat-rmi': 10, | |
| 42 | + 'xtra-base-stake-rmi': 37, | |
| 43 | + 'xtra-inf-stake-rmi': 15 | |
| 44 | + } | |
| 45 | + | |
| 46 | + sell_params = {} | |
| 47 | + | |
| 48 | + # Custom buy/sell parameters per pair | |
| 49 | + custom_pair_params = [] | |
| 50 | + | |
| 51 | + # Recommended on 5m timeframe | |
| 52 | + minimal_roi = { | |
| 53 | + "0": 0.01, | |
| 54 | + "360": 0.005, | |
| 55 | + "720": 0 | |
| 56 | + } | |
| 57 | + | |
| 58 | + dynamic_roi = { | |
| 59 | + 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 60 | + 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 61 | + 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 62 | + 'rmi-end': 70, # ending value | |
| 63 | + 'grow-delay': 180, # delay on growth | |
| 64 | + 'grow-time': 720, # finish time of growth | |
| 65 | + 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 66 | + 'min-roc-atr': 0 # minimum roi value to return in roc or atr mode | |
| 67 | + } | |
| 68 | + | |
| 69 | + use_custom_stoploss = True | |
| 70 | + custom_stop = { | |
| 71 | + # Linear Decay Parameters | |
| 72 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 73 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 74 | + 'decay-start': -0.30, # starting value: should be the same or smaller than initial stoploss | |
| 75 | + 'decay-end': -0.01, # ending value | |
| 76 | + # Profit and TA | |
| 77 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 78 | + 'cur-threshold': -0.01, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 79 | + 'roc-bail': -0.04, # value for roc to use for dynamic bailout | |
| 80 | + 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 81 | + 'bail-how': 'atr', # set the stoploss to the atr offset below current price, or immediate | |
| 82 | + # Positive Trailing | |
| 83 | + 'pos-trail': False, # enable trailing once positive | |
| 84 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 85 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 86 | + } | |
| 87 | + | |
| 88 | + stoploss = custom_stop['decay-start'] | |
| 89 | + | |
| 90 | + # Recommended | |
| 91 | + use_sell_signal = False | |
| 92 | + sell_profit_only = False | |
| 93 | + ignore_roi_if_buy_signal = False | |
| 94 | + | |
| 95 | + # Required | |
| 96 | + startup_candle_count: int = 72 | |
| 97 | + process_only_new_candles = False | |
| 98 | + | |
| 99 | + # Strategy Specific Variable Storage | |
| 100 | + custom_trade_info = {} | |
| 101 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 102 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 103 | + | |
| 104 | + """ | |
| 105 | + Informative Pair Definitions | |
| 106 | + """ | |
| 107 | + def informative_pairs(self): | |
| 108 | + # add all whitelisted pairs on informative timeframe | |
| 109 | + pairs = self.dp.current_whitelist() | |
| 110 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 111 | + | |
| 112 | + # add extra informative pairs if the stake is BTC or ETH | |
| 113 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 114 | + for pair in pairs: | |
| 115 | + coin, stake = pair.split('/') | |
| 116 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 117 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 118 | + | |
| 119 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 120 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 121 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 122 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 123 | + else: | |
| 124 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 125 | + if not btc_stake in pairs: | |
| 126 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 127 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 128 | + | |
| 129 | + return informative_pairs | |
| 130 | + | |
| 131 | + """ | |
| 132 | + Indicator Definitions | |
| 133 | + """ | |
| 134 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 135 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 136 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 137 | + | |
| 138 | + # Indicators for ROI and Custom Stoploss | |
| 139 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 140 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 141 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 142 | + | |
| 143 | + # Trends, Peaks and Crosses | |
| 144 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 145 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 146 | + | |
| 147 | + # strategy BinHV45 | |
| 148 | + mid, lower = cta.bollinger_bands(dataframe['close'], window_size=40, num_of_std=2) | |
| 149 | + dataframe['lower'] = lower | |
| 150 | + dataframe['bbdelta'] = (mid - dataframe['lower']).abs() | |
| 151 | + dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() | |
| 152 | + dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() | |
| 153 | + # strategy ClucMay72018 | |
| 154 | + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) | |
| 155 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 156 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 157 | + dataframe['ema_slow'] = ta.EMA(dataframe, timeperiod=50) | |
| 158 | + dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=30).mean() | |
| 159 | + | |
| 160 | + # Base pair informative timeframe indicators | |
| 161 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 162 | + | |
| 163 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 164 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 165 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 166 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 167 | + | |
| 168 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 169 | + | |
| 170 | + # Other stake specific informative indicators | |
| 171 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 172 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 173 | + coin, stake = metadata['pair'].split('/') | |
| 174 | + fiat = self.custom_fiat | |
| 175 | + coin_fiat = f"{coin}/{fiat}" | |
| 176 | + stake_fiat = f"{stake}/{fiat}" | |
| 177 | + | |
| 178 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 179 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 180 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 181 | + | |
| 182 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 183 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 184 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 185 | + | |
| 186 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 187 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 188 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 189 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 190 | + | |
| 191 | + # Informatives for BTC/STAKE if not in whitelist | |
| 192 | + else: | |
| 193 | + pairs = self.dp.current_whitelist() | |
| 194 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 195 | + if not btc_stake in pairs: | |
| 196 | + # BTC/STAKE - Base Timeframe | |
| 197 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 198 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 199 | + | |
| 200 | + # BTC/STAKE - Informative Timeframe | |
| 201 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 202 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 203 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 204 | + | |
| 205 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 206 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 207 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 208 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 209 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 210 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 211 | + | |
| 212 | + return dataframe | |
| 213 | + | |
| 214 | + """ | |
| 215 | + Buy Signal | |
| 216 | + """ | |
| 217 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 218 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 219 | + conditions = [] | |
| 220 | + | |
| 221 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 222 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 223 | + conditions.append( | |
| 224 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 225 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 226 | + ) | |
| 227 | + | |
| 228 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 229 | + conditions.append( | |
| 230 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 231 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 232 | + ) | |
| 233 | + | |
| 234 | + conditions.append( | |
| 235 | + ( # strategy BinHV45 | |
| 236 | + dataframe['lower'].shift().gt(0) & | |
| 237 | + dataframe['bbdelta'].gt(dataframe['close'] * params['base-bbdelta']) & #0.008 | |
| 238 | + dataframe['closedelta'].gt(dataframe['close'] * params['base-closedelta']) & #0.0175 | |
| 239 | + dataframe['tail'].lt(dataframe['bbdelta'] * params['base-tail']) & # 0.25 | |
| 240 | + dataframe['close'].lt(dataframe['lower'].shift()) & | |
| 241 | + dataframe['close'].le(dataframe['close'].shift()) | |
| 242 | + ) | | |
| 243 | + ( # strategy ClucMay72018 | |
| 244 | + (dataframe['close'] < dataframe['ema_slow']) & | |
| 245 | + (dataframe['close'] < (params['base-bblower'] * dataframe['bb_lowerband'])) & #0.985 | |
| 246 | + (dataframe['volume'] < (dataframe['volume_mean_slow'].shift(1) * params['base-vms'])) # 20 | |
| 247 | + ) | |
| 248 | + ) | |
| 249 | + | |
| 250 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 251 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 252 | + conditions.append( | |
| 253 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 254 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 255 | + ) | |
| 256 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 257 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 258 | + else: | |
| 259 | + pairs = self.dp.current_whitelist() | |
| 260 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 261 | + if not btc_stake in pairs: | |
| 262 | + conditions.append( | |
| 263 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 264 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 265 | + ) | |
| 266 | + | |
| 267 | + conditions.append(dataframe['volume'].gt(0)) | |
| 268 | + | |
| 269 | + if conditions: | |
| 270 | + dataframe.loc[ | |
| 271 | + reduce(lambda x, y: x & y, conditions), | |
| 272 | + 'buy'] = 1 | |
| 273 | + | |
| 274 | + return dataframe | |
| 275 | + | |
| 276 | + """ | |
| 277 | + Sell Signal | |
| 278 | + """ | |
| 279 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 280 | + # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 281 | + | |
| 282 | + dataframe['sell'] = 0 | |
| 283 | + | |
| 284 | + return dataframe | |
| 285 | + | |
| 286 | + """ | |
| 287 | + Custom Stoploss | |
| 288 | + """ | |
| 289 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 290 | + cs = self.get_pair_params(pair, 'custom_stop') | |
| 291 | + | |
| 292 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 293 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 294 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 295 | + profit_diff = current_profit - min_profit | |
| 296 | + | |
| 297 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], trade_dur) | |
| 298 | + | |
| 299 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 300 | + if cs['pos-trail'] == True: | |
| 301 | + if current_profit > cs['pos-threshold']: | |
| 302 | + return current_profit - cs['pos-trail-dist'] | |
| 303 | + | |
| 304 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 305 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 306 | + roc = dataframe['roc'].iat[-1] | |
| 307 | + atr = dataframe['atr'].iat[-1] | |
| 308 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 309 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 310 | + else: | |
| 311 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 312 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 313 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 314 | + | |
| 315 | + if current_profit < cs['cur-threshold']: | |
| 316 | + # Dynamic bailout based on rate of change | |
| 317 | + if (roc/100) <= cs['roc-bail']: | |
| 318 | + if cs['bail-how'] == 'atr': | |
| 319 | + return ((current_rate - atr)/current_rate) - 1 | |
| 320 | + elif cs['bail-how'] == 'immediate': | |
| 321 | + return current_rate | |
| 322 | + else: | |
| 323 | + return decay_stoploss | |
| 324 | + | |
| 325 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 326 | + if (current_profit > min_profit) or roc > 0 or rmi_slow >= cs['rmi-trend']: | |
| 327 | + if profit_diff > cs['cur-min-diff']: | |
| 328 | + return min_profit | |
| 329 | + return -1 | |
| 330 | + | |
| 331 | + return decay_stoploss | |
| 332 | + | |
| 333 | + """ | |
| 334 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 335 | + """ | |
| 336 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 337 | + | |
| 338 | + dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 339 | + minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 340 | + | |
| 341 | + if not dynamic_roi or not minimal_roi: | |
| 342 | + return None, None | |
| 343 | + | |
| 344 | + _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 345 | + | |
| 346 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 347 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 348 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 349 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 350 | + roc = dataframe['roc'].iat[-1] | |
| 351 | + atr = dataframe['atr'].iat[-1] | |
| 352 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 353 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 354 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 355 | + else: | |
| 356 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 357 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 358 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 359 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 360 | + | |
| 361 | + d = dynamic_roi | |
| 362 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 363 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 364 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 365 | + open_rate = trade.open_rate | |
| 366 | + | |
| 367 | + atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 368 | + roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 369 | + | |
| 370 | + # atr as the fallback (if > min-roc-atr) | |
| 371 | + if d['fallback'] == 'atr': | |
| 372 | + min_roi = atr_roi | |
| 373 | + # roc as the fallback (if > min-roc-atr) | |
| 374 | + elif d['fallback'] == 'roc': | |
| 375 | + min_roi = roc_roi | |
| 376 | + # atr or table as the fallback (whichever is larger) | |
| 377 | + elif d['fallback'] == 'atr-table': | |
| 378 | + min_roi = max(table_roi, atr_roi) | |
| 379 | + # roc or table as the fallback (whichever is larger) | |
| 380 | + elif d['fallback'] == 'roc-table': | |
| 381 | + min_roi = max(table_roi, roc_roi) | |
| 382 | + # default to table | |
| 383 | + else: | |
| 384 | + min_roi = table_roi | |
| 385 | + | |
| 386 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 387 | + if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 388 | + if current_profit > min_roi and (current_profit < (max_profit * profit_factor)): | |
| 389 | + min_roi = min_roi | |
| 390 | + else: | |
| 391 | + min_roi = 100 | |
| 392 | + | |
| 393 | + else: | |
| 394 | + min_roi = table_roi | |
| 395 | + | |
| 396 | + return trade_dur, min_roi | |
| 397 | + | |
| 398 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 399 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 400 | + | |
| 401 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 402 | + if not roi_list: | |
| 403 | + return None, None | |
| 404 | + roi_entry = max(roi_list) | |
| 405 | + min_roi = minimal_roi[roi_entry] | |
| 406 | + | |
| 407 | + return roi_entry, min_roi | |
| 408 | + | |
| 409 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 410 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 411 | + | |
| 412 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 413 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 414 | + else: | |
| 415 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 416 | + if roi is None: | |
| 417 | + return False | |
| 418 | + else: | |
| 419 | + return current_profit > roi | |
| 420 | + | |
| 421 | + """ | |
| 422 | + Trade Timeout Overloads | |
| 423 | + """ | |
| 424 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 425 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 426 | + ob = self.dp.orderbook(pair, 1) | |
| 427 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 428 | + if current_price > order['price'] * 1.01: | |
| 429 | + return True | |
| 430 | + return False | |
| 431 | + | |
| 432 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 433 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 434 | + ob = self.dp.orderbook(pair, 1) | |
| 435 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 436 | + if current_price < order['price'] * 0.99: | |
| 437 | + return True | |
| 438 | + return False | |
| 439 | + | |
| 440 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 441 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 442 | + ob = self.dp.orderbook(pair, 1) | |
| 443 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 444 | + if current_price > rate * 1.01: | |
| 445 | + return False | |
| 446 | + return True | |
| 447 | + | |
| 448 | + """ | |
| 449 | + Custom Methods | |
| 450 | + """ | |
| 451 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 452 | + buy_params = self.buy_params | |
| 453 | + sell_params = self.sell_params | |
| 454 | + minimal_roi = self.minimal_roi | |
| 455 | + custom_stop = self.custom_stop | |
| 456 | + dynamic_roi = self.dynamic_roi | |
| 457 | + | |
| 458 | + if self.custom_pair_params: | |
| 459 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 460 | + if custom_params['buy_params']: | |
| 461 | + buy_params = custom_params['buy_params'] | |
| 462 | + if custom_params['sell_params']: | |
| 463 | + sell_params = custom_params['sell_params'] | |
| 464 | + if custom_params['minimal_roi']: | |
| 465 | + custom_stop = custom_params['minimal_roi'] | |
| 466 | + if custom_params['custom_stop']: | |
| 467 | + custom_stop = custom_params['custom_stop'] | |
| 468 | + if custom_params['dynamic_roi']: | |
| 469 | + dynamic_roi = custom_params['dynamic_roi'] | |
| 470 | + | |
| 471 | + if params == 'buy': | |
| 472 | + return buy_params | |
| 473 | + if params == 'sell': | |
| 474 | + return sell_params | |
| 475 | + if params == 'minimal_roi': | |
| 476 | + return minimal_roi | |
| 477 | + if params == 'custom_stop': | |
| 478 | + return custom_stop | |
| 479 | + if params == 'dynamic_roi': | |
| 480 | + return dynamic_roi | |
| 481 | + | |
| 482 | + return False | |
| 483 | + | |
| 484 | + # Get the current price from the exchange (or cache) | |
| 485 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 486 | + if not refresh: | |
| 487 | + rate = self.custom_current_price_cache.get(pair) | |
| 488 | + # Check if cache has been invalidated | |
| 489 | + if rate: | |
| 490 | + return rate | |
| 491 | + | |
| 492 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 493 | + if ask_strategy.get('use_order_book', False): | |
| 494 | + ob = self.dp.orderbook(pair, 1) | |
| 495 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 496 | + else: | |
| 497 | + ticker = self.dp.ticker(pair) | |
| 498 | + rate = ticker['last'] | |
| 499 | + | |
| 500 | + self.custom_current_price_cache[pair] = rate | |
| 501 | + return rate | |
| 502 | + | |
| 503 | + """ | |
| 504 | + Stripped down version from Schism, meant only to update the price data a bit | |
| 505 | + more frequently than the default instead of getting all sorts of trade information | |
| 506 | + """ | |
| 507 | + def populate_trades(self, pair: str) -> dict: | |
| 508 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 509 | + if not pair in self.custom_trade_info: | |
| 510 | + self.custom_trade_info[pair] = {} | |
| 511 | + | |
| 512 | + # init the temp dicts and set the trade stuff to false | |
| 513 | + trade_data = {} | |
| 514 | + trade_data['active_trade'] = False | |
| 515 | + | |
| 516 | + # active trade stuff only works in live and dry, not backtest | |
| 517 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 518 | + | |
| 519 | + # find out if we have an open trade for this pair | |
| 520 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 521 | + | |
| 522 | + # if so, get some information | |
| 523 | + if active_trade: | |
| 524 | + # get current price and update the min/max rate | |
| 525 | + current_rate = self.get_current_price(pair, True) | |
| 526 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 527 | + | |
| 528 | + return trade_data | |
| 529 | + | |
| 530 | +# Sub-strategy with parameters specific to BTC stake | |
| 531 | +class Solipsis6_BTC(Solipsis6): | |
| 532 | + | |
| 533 | + timeframe = '1h' | |
| 534 | + inf_timeframe = '4h' | |
| 535 | + | |
| 536 | + buy_params = { | |
| 537 | + 'inf-rsi': 64, | |
| 538 | + 'mp': 55, | |
| 539 | + 'rmi-fast': 31, | |
| 540 | + 'rmi-slow': 16, | |
| 541 | + 'xinf-stake-rmi': 67, | |
| 542 | + 'xtf-fiat-rsi': 17, | |
| 543 | + 'xtf-stake-rsi': 57 | |
| 544 | + } | |
| 545 | + | |
| 546 | + minimal_roi = { | |
| 547 | + "0": 0.05, | |
| 548 | + "240": 0.025, | |
| 549 | + "1440": 0.01, | |
| 550 | + "4320": 0 | |
| 551 | + } | |
| 552 | + | |
| 553 | + stoploss = -0.30 | |
| 554 | + use_custom_stoploss = False | |
| 555 | + | |
| 556 | +# Sub-strategy with parameters specific to ETH stake | |
| 557 | +class Solipsis6_ETH(Solipsis6): | |
| 558 | + | |
| 559 | + timeframe = '1h' | |
| 560 | + inf_timeframe = '4h' | |
| 561 | + | |
| 562 | + buy_params = { | |
| 563 | + 'inf-rsi': 13, | |
| 564 | + 'inf-stake-rmi': 69, | |
| 565 | + 'mp': 40, | |
| 566 | + 'rmi-fast': 42, | |
| 567 | + 'rmi-slow': 17, | |
| 568 | + 'tf-fiat-rsi': 15, | |
| 569 | + 'tf-stake-rsi': 92 | |
| 570 | + } | |
| 571 | + | |
| 572 | + minimal_roi = { | |
| 573 | + "0": 0.05, | |
| 574 | + "240": 0.025, | |
| 575 | + "1440": 0.01, | |
| 576 | + "4320": 0 | |
| 577 | + } | |
| 578 | + | |
| 579 | + stoploss = -0.30 | |
| 580 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v2.py +626 −0
| @@ -0,0 +1,626 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +import array as arr | |
| 6 | + | |
| 7 | +from freqtrade.strategy.interface import IStrategy | |
| 8 | +from freqtrade.strategy import merge_informative_pair | |
| 9 | +from typing import Dict, List, Optional, Tuple | |
| 10 | +from pandas import DataFrame, Series | |
| 11 | +from functools import reduce | |
| 12 | +from datetime import datetime, timedelta | |
| 13 | +from freqtrade.persistence import Trade | |
| 14 | +from statistics import mean | |
| 15 | +from cachetools import TTLCache | |
| 16 | + | |
| 17 | +# Get rid of pandas warnings during backtesting | |
| 18 | +import pandas as pd | |
| 19 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 20 | + | |
| 21 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 22 | +import sys | |
| 23 | +from pathlib import Path | |
| 24 | +sys.path.append(str(Path(__file__).parent)) | |
| 25 | + | |
| 26 | +import custom_indicators as cta | |
| 27 | + | |
| 28 | +""" | |
| 29 | +FEATURES: | |
| 30 | + - ROI override, extending use of ignore_roi_if_buy_signal = True by stimulating a sticking buy signal for active trades | |
| 31 | + which are in an upward trend. This ensures we extract maximum profit from trades rather than relying on static ROI points. | |
| 32 | + - Custom Stoploss with several modes and options (review the code). | |
| 33 | + - Dynamic ROI table with several modes and options (review the code). | |
| 34 | + - Custom sell which takes profit as well as other trade performance into consideration when selling. | |
| 35 | + - Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 36 | + - Ability to provide custom buy/sell parameters on a per-pair or group of pairs basis (may extend this to ROI and/or stoploss settings) | |
| 37 | + - Custom indicator file to keep primary strategy clean(ish). | |
| 38 | + - Child strategies for stake specific settings. | |
| 39 | + - Several methods to aid in using active trade data and realtime price data as part of the strategy. | |
| 40 | + | |
| 41 | +STRATEGY NOTES: | |
| 42 | + - If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) is *highly recommended* that you remove BTC/STAKE | |
| 43 | + from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC | |
| 44 | + itself. | |
| 45 | + - If trading on a different stake, such as BTC or ETH, this strategy has additional informative indicators it uses, if you use a stake | |
| 46 | + other than BTC/ETH (outside the standard fiat/stablecoin stakes) you may want to look at the code to include that stake in the list. | |
| 47 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 48 | + "--enable-protections" as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 49 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 50 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 51 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 52 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 53 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 54 | + - If running backtest/hyperopt around the portion of the sell signal that is testable, keep in mind in live/dry | |
| 55 | + it will not sell nearly as frequently due to the profit guard and other_profit / free_slot guards. | |
| 56 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 57 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 58 | + ROI based sells will be higher than the backtest shows. | |
| 59 | + - It is *not* worthwhile to hyperopt for roi as it does not take into account the roi trend ride we are doing and | |
| 60 | + having ROI points that are too high will sort of be counter-productive to how this strategy works even if it seems | |
| 61 | + to produce better results in backtesting. | |
| 62 | + - It *might be* worthwhile to hyperopt the stoploss but we can't hyperopt any of the parameters in the custom stoploss | |
| 63 | + so hyperopting the stoploss is only changing the initial position relative to the other settings. | |
| 64 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 65 | + - The custom stoploss has settings to emulate the same functionality, however. | |
| 66 | + - Might be worthwhile to disable the trailing stop in solipsis, hyperopt the trailing, and use those settings with the | |
| 67 | + Solipsis implementation, *if* you want a positive trailing stop, but the ROI ride should be preferred over the positive stoploss. | |
| 68 | + - It is *highly* recommended to backtest with use_sell_signal = False because it will not behave remotely the same in dry/live | |
| 69 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only or 'buy sell' and at least 1000 total epochs several times. There are | |
| 70 | + a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 71 | + | |
| 72 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 73 | + | |
| 74 | + custom_pair_params = [ | |
| 75 | + { | |
| 76 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 77 | + 'buy_params': {}, | |
| 78 | + 'sell_params': {} | |
| 79 | + } | |
| 80 | + ] | |
| 81 | + | |
| 82 | +TODO: | |
| 83 | + - Continue to hunt for a better all around buy signal. | |
| 84 | + - Completely eliminate any trades from hitting the initial stoploss (default: -30%) | |
| 85 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 86 | + - Need to reduce drawdown. | |
| 87 | + - Tweak ROI Trend Ride | |
| 88 | + - Maybe further exploit the ROI table itself using trade data? | |
| 89 | + - Per-pair automatic ROI points based on ADR/ATR or something similar? | |
| 90 | + - Tweak sell signal | |
| 91 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 92 | + - Further enchance and optimize custom stop loss | |
| 93 | +""" | |
| 94 | + | |
| 95 | +class Solipsis(IStrategy): | |
| 96 | + | |
| 97 | + # Recommended for USD/USDT/etc. | |
| 98 | + timeframe = '5m' | |
| 99 | + inf_timeframe = '1h' | |
| 100 | + | |
| 101 | + buy_params = { | |
| 102 | + 'base-mp': 48, | |
| 103 | + 'base-rmi-fast': 44, | |
| 104 | + 'base-rmi-slow': 21, | |
| 105 | + 'inf-guard': 'both', | |
| 106 | + 'inf-pct-adr-bot': 0.17436, | |
| 107 | + 'inf-pct-adr-top': 0.84712, | |
| 108 | + 'xbtc-base-rmi': 70, | |
| 109 | + 'xbtc-inf-rmi': 14, | |
| 110 | + 'xtra-base-fiat-rmi': 14, | |
| 111 | + 'xtra-base-stake-rmi': 50, | |
| 112 | + 'xtra-inf-stake-rmi': 31 | |
| 113 | + } | |
| 114 | + | |
| 115 | + sell_params = { | |
| 116 | + 'sell-rmi-drop': 0.82934 | |
| 117 | + } | |
| 118 | + | |
| 119 | + # Custom buy/sell parameters per pair | |
| 120 | + custom_pair_params = [] | |
| 121 | + | |
| 122 | + # Recommended on 5m timeframe | |
| 123 | + minimal_roi = { | |
| 124 | + "0": 0.05, | |
| 125 | + "30": 0.025, | |
| 126 | + "120": 0.01, | |
| 127 | + "360": 0.01, | |
| 128 | + "720": 0.005, | |
| 129 | + "1440": 0 | |
| 130 | + } | |
| 131 | + | |
| 132 | + # Optional | |
| 133 | + dynamic_roi = { | |
| 134 | + 'enabled': True, | |
| 135 | + 'profit-factor': 400, | |
| 136 | + 'rmi-start': 30, | |
| 137 | + 'rmi-end': 70, | |
| 138 | + 'grow-delay': 180, | |
| 139 | + 'grow-time': 720 | |
| 140 | + } | |
| 141 | + | |
| 142 | + stoploss = -0.30 | |
| 143 | + | |
| 144 | + # Optional | |
| 145 | + use_custom_stoploss = False | |
| 146 | + custom_stop = { | |
| 147 | + # Linear Decay Parameters | |
| 148 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 149 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 150 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 151 | + 'decay-end': -0.03, # ending value | |
| 152 | + # Current vs Min Profit | |
| 153 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 154 | + 'cur-threshold': 0, # how far negative should current profit be before we consider moving it up based on cur/min | |
| 155 | + # Positive Trailing | |
| 156 | + 'pos-trail': False, # enable trailing once positive | |
| 157 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 158 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 159 | + } | |
| 160 | + | |
| 161 | + # Recommended | |
| 162 | + use_sell_signal = True | |
| 163 | + sell_profit_only = False | |
| 164 | + ignore_roi_if_buy_signal = True | |
| 165 | + | |
| 166 | + # Required | |
| 167 | + startup_candle_count: int = 72 | |
| 168 | + process_only_new_candles = False | |
| 169 | + | |
| 170 | + # Strategy Specific Variable Storage | |
| 171 | + custom_trade_info = {} | |
| 172 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 173 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 174 | + | |
| 175 | + """ | |
| 176 | + Informative Pair Definitions | |
| 177 | + """ | |
| 178 | + def informative_pairs(self): | |
| 179 | + # add all whitelisted pairs on informative timeframe | |
| 180 | + pairs = self.dp.current_whitelist() | |
| 181 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 182 | + | |
| 183 | + # add extra informative pairs if the stake is BTC or ETH | |
| 184 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 185 | + for pair in pairs: | |
| 186 | + coin, stake = pair.split('/') | |
| 187 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 188 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 189 | + | |
| 190 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 191 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 192 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 193 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 194 | + else: | |
| 195 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 196 | + if not btc_stake in pairs: | |
| 197 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 198 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 199 | + | |
| 200 | + return informative_pairs | |
| 201 | + | |
| 202 | + """ | |
| 203 | + Indicator Definitions | |
| 204 | + """ | |
| 205 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 206 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 207 | + | |
| 208 | + # Base timeframe indicators | |
| 209 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 210 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 211 | + | |
| 212 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 213 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 214 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 215 | + | |
| 216 | + # Trends, Peaks and Crosses | |
| 217 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 218 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 219 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 220 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 221 | + dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max() | |
| 222 | + | |
| 223 | + # Base pair informative timeframe indicators | |
| 224 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 225 | + | |
| 226 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 227 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 228 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 229 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 230 | + | |
| 231 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 232 | + | |
| 233 | + # Other stake specific informative indicators | |
| 234 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 235 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 236 | + coin, stake = metadata['pair'].split('/') | |
| 237 | + fiat = self.custom_fiat | |
| 238 | + coin_fiat = f"{coin}/{fiat}" | |
| 239 | + stake_fiat = f"{stake}/{fiat}" | |
| 240 | + | |
| 241 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 242 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 243 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 244 | + | |
| 245 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 246 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 247 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 248 | + | |
| 249 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 250 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 251 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 252 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 253 | + | |
| 254 | + # Informatives for BTC/STAKE if not in whitelist | |
| 255 | + else: | |
| 256 | + pairs = self.dp.current_whitelist() | |
| 257 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 258 | + if not btc_stake in pairs: | |
| 259 | + # BTC/STAKE - Base Timeframe | |
| 260 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 261 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 262 | + | |
| 263 | + # BTC/STAKE - Informative Timeframe | |
| 264 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 265 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 266 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 267 | + | |
| 268 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 269 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 270 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 271 | + | |
| 272 | + return dataframe | |
| 273 | + | |
| 274 | + """ | |
| 275 | + Buy Signal | |
| 276 | + """ | |
| 277 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 278 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 279 | + # trade_data = self.custom_trade_info[metadata['pair']] | |
| 280 | + conditions = [] | |
| 281 | + | |
| 282 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 283 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 284 | + conditions.append( | |
| 285 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 286 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 287 | + ) | |
| 288 | + | |
| 289 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 290 | + conditions.append( | |
| 291 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 292 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 293 | + ) | |
| 294 | + | |
| 295 | + # Base Timeframe | |
| 296 | + conditions.append( | |
| 297 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 298 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 299 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 300 | + (dataframe['mp'] <= params['base-mp']) | |
| 301 | + ) | |
| 302 | + | |
| 303 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 304 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 305 | + conditions.append( | |
| 306 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 307 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 308 | + ) | |
| 309 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 310 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 311 | + else: | |
| 312 | + pairs = self.dp.current_whitelist() | |
| 313 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 314 | + if not btc_stake in pairs: | |
| 315 | + conditions.append( | |
| 316 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 317 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 318 | + ) | |
| 319 | + | |
| 320 | + conditions.append(dataframe['volume'].gt(0)) | |
| 321 | + | |
| 322 | + if conditions: | |
| 323 | + dataframe.loc[ | |
| 324 | + reduce(lambda x, y: x & y, conditions), | |
| 325 | + 'buy'] = 1 | |
| 326 | + | |
| 327 | + return dataframe | |
| 328 | + | |
| 329 | + """ | |
| 330 | + Sell Signal | |
| 331 | + """ | |
| 332 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 333 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 334 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 335 | + conditions = [] | |
| 336 | + | |
| 337 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 338 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 339 | + if trade_data['active_trade']: | |
| 340 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 341 | + # a trade to go into the negative a little bit before we react to sell. | |
| 342 | + loss_cutoff = cta.linear_growth(-0.03, 0, 0, 240, trade_data['open_minutes']) | |
| 343 | + | |
| 344 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 345 | + | |
| 346 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 347 | + if trade_data['other_trades']: | |
| 348 | + if trade_data['free_slots'] > 0: | |
| 349 | + # If the average of all our other trades is below a certain threshold based | |
| 350 | + # on free slots available, hold and wait for market recovery. | |
| 351 | + hold_pct = (1/trade_data['free_slots']) * -0.04 | |
| 352 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 353 | + else: | |
| 354 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 355 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 356 | + | |
| 357 | + # Primary sell trigger | |
| 358 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 359 | + conditions.append( | |
| 360 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 361 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 362 | + (dataframe['volume'].gt(0)) | |
| 363 | + ) | |
| 364 | + | |
| 365 | + if conditions: | |
| 366 | + dataframe.loc[ | |
| 367 | + reduce(lambda x, y: x & y, conditions), | |
| 368 | + 'sell'] = 1 | |
| 369 | + | |
| 370 | + return dataframe | |
| 371 | + | |
| 372 | + """ | |
| 373 | + Custom Stoploss | |
| 374 | + """ | |
| 375 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 376 | + cs = self.custom_stop | |
| 377 | + | |
| 378 | + trade_dur: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 379 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 380 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 381 | + profit_diff = current_profit - min_profit | |
| 382 | + | |
| 383 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 384 | + if cs['pos-trail'] == True: | |
| 385 | + if current_profit > cs['pos-threshold']: | |
| 386 | + return current_profit - cs['pos-trail-dist'] | |
| 387 | + | |
| 388 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], trade_dur) | |
| 389 | + | |
| 390 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 391 | + if (current_profit > min_profit) and current_profit < cs['cur-threshold']: | |
| 392 | + if profit_diff > cs['cur-min-diff']: | |
| 393 | + return min_profit | |
| 394 | + return -1 | |
| 395 | + | |
| 396 | + return decay_stoploss | |
| 397 | + | |
| 398 | + """ | |
| 399 | + Trade Timeout Overloads | |
| 400 | + """ | |
| 401 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 402 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 403 | + ob = self.dp.orderbook(pair, 1) | |
| 404 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 405 | + if current_price > order['price'] * 1.01: | |
| 406 | + return True | |
| 407 | + return False | |
| 408 | + | |
| 409 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 410 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 411 | + ob = self.dp.orderbook(pair, 1) | |
| 412 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 413 | + if current_price < order['price'] * 0.99: | |
| 414 | + return True | |
| 415 | + return False | |
| 416 | + | |
| 417 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 418 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 419 | + ob = self.dp.orderbook(pair, 1) | |
| 420 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 421 | + if current_price > rate * 1.01: | |
| 422 | + return False | |
| 423 | + return True | |
| 424 | + | |
| 425 | + """ | |
| 426 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 427 | + """ | |
| 428 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 429 | + | |
| 430 | + dynamic_roi = self.dynamic_roi | |
| 431 | + minimal_roi = self.minimal_roi | |
| 432 | + | |
| 433 | + if not dynamic_roi or not minimal_roi: | |
| 434 | + return None, None | |
| 435 | + | |
| 436 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 437 | + if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 438 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 439 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 440 | + else: | |
| 441 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 442 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 443 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 444 | + | |
| 445 | + d = dynamic_roi | |
| 446 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 447 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 448 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 449 | + | |
| 450 | + print(f"RMI Slow: {rmi_slow}") | |
| 451 | + print(f"RMI Threshold: {rmi_grow}") | |
| 452 | + print(f"RMI Trend: {rmi_trend}") | |
| 453 | + print(f"Current Profit: {current_profit}") | |
| 454 | + print(f"Profit Cutoff: {max_profit * profit_factor}") | |
| 455 | + | |
| 456 | + if (current_profit > (max_profit * profit_factor)) and (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 457 | + # force the roi to be high to prevent sell | |
| 458 | + print(f"########################### Uptrend Detected, hold ROI") | |
| 459 | + min_roi = 100 | |
| 460 | + # return standard roi table value | |
| 461 | + else: | |
| 462 | + print(f"No Trend, Release ROI to table") | |
| 463 | + _, min_roi = self.min_roi_reached_entry(trade_dur) | |
| 464 | + else: | |
| 465 | + return self.min_roi_reached_entry(trade_dur) | |
| 466 | + | |
| 467 | + return trade_dur, min_roi | |
| 468 | + | |
| 469 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 470 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 471 | + | |
| 472 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 473 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 474 | + else: | |
| 475 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 476 | + if roi is None: | |
| 477 | + return False | |
| 478 | + else: | |
| 479 | + return current_profit > roi | |
| 480 | + | |
| 481 | + """ | |
| 482 | + Custom Methods for Strategy Parameters, Trade, and Price Data | |
| 483 | + Consider splitting this out into a helper file. | |
| 484 | + """ | |
| 485 | + def populate_trades(self, pair: str, **kwargs) -> dict: | |
| 486 | + """ | |
| 487 | + Query the database and populate the custom_trade_info dict. | |
| 488 | + """ | |
| 489 | + if not pair in self.custom_trade_info: | |
| 490 | + self.custom_trade_info[pair] = {} | |
| 491 | + | |
| 492 | + trade_data = {} | |
| 493 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 494 | + | |
| 495 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 496 | + | |
| 497 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 498 | + | |
| 499 | + if active_trade: | |
| 500 | + current_rate = self.get_current_price(pair, True) | |
| 501 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 502 | + | |
| 503 | + present = arrow.utcnow() | |
| 504 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 505 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 506 | + | |
| 507 | + trade_data['active_trade'] = True | |
| 508 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 509 | + trade_data['max_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) # if above 0 | |
| 510 | + trade_data['min_profit'] = active_trade[0].calc_profit_ratio(active_trade[0].min_rate) | |
| 511 | + trade_data['open_minutes'] : int = open_minutes | |
| 512 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 513 | + else: | |
| 514 | + trade_data['current_profit'] = trade_data['max_profit'] = trade_data['min_profit'] = 0.0 | |
| 515 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 516 | + | |
| 517 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 518 | + | |
| 519 | + if other_trades: | |
| 520 | + trade_data['other_trades'] = True | |
| 521 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 522 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 523 | + if trade_data['current_profit'] < min(other_profit): | |
| 524 | + trade_data['biggest_loser'] = True | |
| 525 | + else: | |
| 526 | + trade_data['avg_other_profit'] = 0 | |
| 527 | + | |
| 528 | + open_trades = len(Trade.get_open_trades()) | |
| 529 | + # this was lazy. | |
| 530 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 531 | + | |
| 532 | + return trade_data | |
| 533 | + | |
| 534 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 535 | + """ | |
| 536 | + Query the exchange for current price information, used in profit calculations. | |
| 537 | + Implements a cache to prevent excessive api calls. | |
| 538 | + """ | |
| 539 | + if not refresh: | |
| 540 | + rate = self.custom_current_price_cache.get(pair) | |
| 541 | + if rate: | |
| 542 | + return rate | |
| 543 | + | |
| 544 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 545 | + if ask_strategy.get('use_order_book', False): | |
| 546 | + ob = self.dp.orderbook(pair, 1) | |
| 547 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 548 | + else: | |
| 549 | + ticker = self.dp.ticker(pair) | |
| 550 | + rate = ticker['last'] | |
| 551 | + | |
| 552 | + self.custom_current_price_cache[pair] = rate | |
| 553 | + return rate | |
| 554 | + | |
| 555 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 556 | + """ | |
| 557 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 558 | + TODO: | |
| 559 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 560 | + """ | |
| 561 | + buy_params = self.buy_params | |
| 562 | + sell_params = self.sell_params | |
| 563 | + | |
| 564 | + if self.custom_pair_params: | |
| 565 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 566 | + if custom_params['buy_params']: | |
| 567 | + buy_params = custom_params['buy_params'] | |
| 568 | + if custom_params['sell_params']: | |
| 569 | + sell_params = custom_params['sell_params'] | |
| 570 | + | |
| 571 | + if side == 'sell': | |
| 572 | + return sell_params | |
| 573 | + | |
| 574 | + return buy_params | |
| 575 | + | |
| 576 | +# Sub-strategy with parameters specific to BTC stake | |
| 577 | +class Solipsis_BTC(Solipsis): | |
| 578 | + | |
| 579 | + timeframe = '1h' | |
| 580 | + inf_timeframe = '4h' | |
| 581 | + | |
| 582 | + buy_params = { | |
| 583 | + 'inf-rsi': 64, | |
| 584 | + 'mp': 55, | |
| 585 | + 'rmi-fast': 31, | |
| 586 | + 'rmi-slow': 16, | |
| 587 | + 'xinf-stake-rmi': 67, | |
| 588 | + 'xtf-fiat-rsi': 17, | |
| 589 | + 'xtf-stake-rsi': 57 | |
| 590 | + } | |
| 591 | + | |
| 592 | + minimal_roi = { | |
| 593 | + "0": 0.05, | |
| 594 | + "240": 0.025, | |
| 595 | + "1440": 0.01, | |
| 596 | + "4320": 0 | |
| 597 | + } | |
| 598 | + | |
| 599 | + stoploss = -0.30 | |
| 600 | + use_custom_stoploss = False | |
| 601 | + | |
| 602 | +# Sub-strategy with parameters specific to ETH stake | |
| 603 | +class Solipsis_ETH(Solipsis): | |
| 604 | + | |
| 605 | + timeframe = '1h' | |
| 606 | + inf_timeframe = '4h' | |
| 607 | + | |
| 608 | + buy_params = { | |
| 609 | + 'inf-rsi': 13, | |
| 610 | + 'inf-stake-rmi': 69, | |
| 611 | + 'mp': 40, | |
| 612 | + 'rmi-fast': 42, | |
| 613 | + 'rmi-slow': 17, | |
| 614 | + 'tf-fiat-rsi': 15, | |
| 615 | + 'tf-stake-rsi': 92 | |
| 616 | + } | |
| 617 | + | |
| 618 | + minimal_roi = { | |
| 619 | + "0": 0.05, | |
| 620 | + "240": 0.025, | |
| 621 | + "1440": 0.01, | |
| 622 | + "4320": 0 | |
| 623 | + } | |
| 624 | + | |
| 625 | + stoploss = -0.30 | |
| 626 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v3-fuck.py +530 −0
| @@ -0,0 +1,530 @@ | ||
| 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 | |
| 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 statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | +# Get rid of pandas warnings during backtesting | |
| 17 | +import pandas as pd | |
| 18 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 19 | + | |
| 20 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 21 | +import sys | |
| 22 | +from pathlib import Path | |
| 23 | +sys.path.append(str(Path(__file__).parent)) | |
| 24 | + | |
| 25 | +import custom_indicators as cta | |
| 26 | + | |
| 27 | +""" | |
| 28 | +FEATURES: | |
| 29 | + - Dynamic ROI which looks at an upward trend and positive profit cutoff to extend roi table and hold on longer during trends. | |
| 30 | + - Now fully working in backtest! | |
| 31 | + - Custom Stoploss | |
| 32 | + - Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 33 | + - Ability to provide custom buy/sell parameters on a per-pair or group of pairs basis (may extend this to ROI and/or stoploss settings) | |
| 34 | + - Custom indicator file to keep primary strategy clean(ish). | |
| 35 | + - Child strategies for stake specific settings. | |
| 36 | + | |
| 37 | +STRATEGY NOTES: | |
| 38 | + - If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) is *highly recommended* that you remove BTC/STAKE | |
| 39 | + from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC | |
| 40 | + itself. | |
| 41 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 42 | + "--enable-protections" as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 43 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 44 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 45 | + - It *might be* worthwhile to hyperopt the stoploss but we can't hyperopt any of the parameters in the custom stoploss | |
| 46 | + so hyperopting the stoploss is only changing the initial position relative to the other settings. | |
| 47 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 48 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only and at least 1000 total epochs several times. There are | |
| 49 | + a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 50 | + | |
| 51 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 52 | + | |
| 53 | + custom_pair_params = [ | |
| 54 | + { | |
| 55 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 56 | + 'buy_params': {}, | |
| 57 | + 'sell_params': {} | |
| 58 | + } | |
| 59 | + ] | |
| 60 | + | |
| 61 | +TODO: | |
| 62 | + - Continue to hunt for a better all around buy signal. | |
| 63 | + - Completely eliminate any trades from hitting the initial stoploss (default: -30%) | |
| 64 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 65 | + - Need to reduce drawdown. | |
| 66 | + - Tweak ROI Trend Ride | |
| 67 | + - Further enchance and optimize custom stop loss | |
| 68 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 69 | + - Develop a PR to fully support trades database so we can go back to previous Schism methodology for buy/sell and trade data? | |
| 70 | + - Develop a PR to fully support hyperopting the custom_stoploss space? | |
| 71 | +""" | |
| 72 | + | |
| 73 | +class Solipsis3(IStrategy): | |
| 74 | + | |
| 75 | + # Recommended for USD/USDT/etc. | |
| 76 | + timeframe = '5m' | |
| 77 | + inf_timeframe = '1h' | |
| 78 | + | |
| 79 | + buy_params = { | |
| 80 | + 'base-mp': 48, | |
| 81 | + 'base-rmi-fast': 44, | |
| 82 | + 'base-rmi-slow': 21, | |
| 83 | + 'inf-guard': 'both', | |
| 84 | + 'inf-pct-adr-bot': 0.17436, | |
| 85 | + 'inf-pct-adr-top': 0.84712, | |
| 86 | + 'xbtc-base-rmi': 70, | |
| 87 | + 'xbtc-inf-rmi': 14, | |
| 88 | + 'xtra-base-fiat-rmi': 14, | |
| 89 | + 'xtra-base-stake-rmi': 50, | |
| 90 | + 'xtra-inf-stake-rmi': 31 | |
| 91 | + } | |
| 92 | + | |
| 93 | + sell_params = {} | |
| 94 | + | |
| 95 | + # Custom buy/sell parameters per pair | |
| 96 | + custom_pair_params = [] | |
| 97 | + | |
| 98 | + # Recommended on 5m timeframe | |
| 99 | + minimal_roi = { | |
| 100 | + "0": 0.05, | |
| 101 | + "30": 0.025, | |
| 102 | + "120": 0.01, | |
| 103 | + "360": 0.01, | |
| 104 | + "720": 0.005, | |
| 105 | + "1440": 0 | |
| 106 | + } | |
| 107 | + | |
| 108 | + dynamic_roi = { | |
| 109 | + 'enabled': False, | |
| 110 | + 'profit-factor': 400, | |
| 111 | + 'rmi-start': 30, | |
| 112 | + 'rmi-end': 70, | |
| 113 | + 'grow-delay': 180, | |
| 114 | + 'grow-time': 720, | |
| 115 | + 'fallback': 'table' | |
| 116 | + } | |
| 117 | + | |
| 118 | + stoploss = -0.30 | |
| 119 | + | |
| 120 | + use_custom_stoploss = False | |
| 121 | + custom_stop = { | |
| 122 | + # Linear Decay Parameters | |
| 123 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 124 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 125 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 126 | + 'decay-end': -0.03, # ending value | |
| 127 | + # Profit and TA | |
| 128 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 129 | + 'cur-threshold': 0, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 130 | + 'cur-roc': -0.04, # value for roc to use for dynamic bailout | |
| 131 | + # Positive Trailing | |
| 132 | + 'pos-trail': False, # enable trailing once positive | |
| 133 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 134 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 135 | + } | |
| 136 | + | |
| 137 | + # Recommended | |
| 138 | + use_sell_signal = False | |
| 139 | + sell_profit_only = False | |
| 140 | + ignore_roi_if_buy_signal = False | |
| 141 | + | |
| 142 | + # Required | |
| 143 | + startup_candle_count: int = 72 | |
| 144 | + process_only_new_candles = False | |
| 145 | + | |
| 146 | + # Strategy Specific Variable Storage | |
| 147 | + custom_trade_info = {} | |
| 148 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 149 | + | |
| 150 | + """ | |
| 151 | + Informative Pair Definitions | |
| 152 | + """ | |
| 153 | + def informative_pairs(self): | |
| 154 | + # add all whitelisted pairs on informative timeframe | |
| 155 | + pairs = self.dp.current_whitelist() | |
| 156 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 157 | + | |
| 158 | + # add extra informative pairs if the stake is BTC or ETH | |
| 159 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 160 | + for pair in pairs: | |
| 161 | + coin, stake = pair.split('/') | |
| 162 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 163 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 164 | + | |
| 165 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 166 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 167 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 168 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 169 | + else: | |
| 170 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 171 | + if not btc_stake in pairs: | |
| 172 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 173 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 174 | + | |
| 175 | + return informative_pairs | |
| 176 | + | |
| 177 | + """ | |
| 178 | + Indicator Definitions | |
| 179 | + """ | |
| 180 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 181 | + if not metadata['pair'] in self.custom_trade_info: | |
| 182 | + self.custom_trade_info[metadata['pair']] = {} | |
| 183 | + | |
| 184 | + # Base timeframe indicators | |
| 185 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 186 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 187 | + | |
| 188 | + # Indicators for ROI and Custom Stoploss | |
| 189 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 190 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 191 | + | |
| 192 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 193 | + dataframe['roc-mp'] = ta.ROC(dataframe, timeperiod=6) | |
| 194 | + dataframe['mp'] = ta.RSI(dataframe['roc-mp'], timeperiod=6) | |
| 195 | + | |
| 196 | + # Trends, Peaks and Crosses | |
| 197 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 198 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 199 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 200 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 201 | + dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max() | |
| 202 | + | |
| 203 | + # Base pair informative timeframe indicators | |
| 204 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 205 | + | |
| 206 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 207 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 208 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 209 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 210 | + | |
| 211 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 212 | + | |
| 213 | + # Other stake specific informative indicators | |
| 214 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 215 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 216 | + coin, stake = metadata['pair'].split('/') | |
| 217 | + fiat = self.custom_fiat | |
| 218 | + coin_fiat = f"{coin}/{fiat}" | |
| 219 | + stake_fiat = f"{stake}/{fiat}" | |
| 220 | + | |
| 221 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 222 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 223 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 224 | + | |
| 225 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 226 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 227 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 228 | + | |
| 229 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 230 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 231 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 232 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 233 | + | |
| 234 | + # Informatives for BTC/STAKE if not in whitelist | |
| 235 | + else: | |
| 236 | + pairs = self.dp.current_whitelist() | |
| 237 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 238 | + if not btc_stake in pairs: | |
| 239 | + # BTC/STAKE - Base Timeframe | |
| 240 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 241 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 242 | + | |
| 243 | + # BTC/STAKE - Informative Timeframe | |
| 244 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 245 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 246 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 247 | + | |
| 248 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 249 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 250 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 251 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 252 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 253 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 254 | + | |
| 255 | + return dataframe | |
| 256 | + | |
| 257 | + """ | |
| 258 | + Buy Signal | |
| 259 | + """ | |
| 260 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 261 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 262 | + conditions = [] | |
| 263 | + | |
| 264 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 265 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 266 | + conditions.append( | |
| 267 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 268 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 269 | + ) | |
| 270 | + | |
| 271 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 272 | + conditions.append( | |
| 273 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 274 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 275 | + ) | |
| 276 | + | |
| 277 | + # Base Timeframe | |
| 278 | + conditions.append( | |
| 279 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 280 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 281 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 282 | + (dataframe['mp'] <= params['base-mp']) | |
| 283 | + ) | |
| 284 | + | |
| 285 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 286 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 287 | + conditions.append( | |
| 288 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 289 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 290 | + ) | |
| 291 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 292 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 293 | + else: | |
| 294 | + pairs = self.dp.current_whitelist() | |
| 295 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 296 | + if not btc_stake in pairs: | |
| 297 | + conditions.append( | |
| 298 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 299 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 300 | + ) | |
| 301 | + | |
| 302 | + conditions.append(dataframe['volume'].gt(0)) | |
| 303 | + | |
| 304 | + if conditions: | |
| 305 | + dataframe.loc[ | |
| 306 | + reduce(lambda x, y: x & y, conditions), | |
| 307 | + 'buy'] = 1 | |
| 308 | + | |
| 309 | + return dataframe | |
| 310 | + | |
| 311 | + """ | |
| 312 | + Sell Signal | |
| 313 | + """ | |
| 314 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 315 | + | |
| 316 | + dataframe['sell'] = 0 | |
| 317 | + | |
| 318 | + return dataframe | |
| 319 | + | |
| 320 | + """ | |
| 321 | + Custom Stoploss | |
| 322 | + """ | |
| 323 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 324 | + cs = self.custom_stop | |
| 325 | + | |
| 326 | + trade_dur: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 327 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 328 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 329 | + profit_diff = current_profit - min_profit | |
| 330 | + | |
| 331 | + decay_stoploss = cta.linear_growth(cs['decay-start'], cs['decay-end'], cs['decay-delay'], cs['decay-time'], trade_dur) | |
| 332 | + | |
| 333 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 334 | + if cs['pos-trail'] == True: | |
| 335 | + if current_profit > cs['pos-threshold']: | |
| 336 | + return current_profit - cs['pos-trail-dist'] | |
| 337 | + | |
| 338 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 339 | + if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 340 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 341 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 342 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 343 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 344 | + # Otherwise get it out of the dataframe | |
| 345 | + else: | |
| 346 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 347 | + roc = dataframe['roc'].iat[-1] | |
| 348 | + atr = dataframe['atr'].iat[-1] | |
| 349 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 350 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 351 | + | |
| 352 | + if current_profit < cs['cur-threshold']: | |
| 353 | + # Dynamic bailout based on rate of change | |
| 354 | + if (roc/100) < cs['cur-roc']: | |
| 355 | + stoploss = (current_rate - atr)/current_rate | |
| 356 | + return stoploss - 1 | |
| 357 | + | |
| 358 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 359 | + if (current_profit > min_profit) or roc > 0: | |
| 360 | + if profit_diff > cs['cur-min-diff']: | |
| 361 | + return min_profit | |
| 362 | + return -1 | |
| 363 | + | |
| 364 | + return decay_stoploss | |
| 365 | + | |
| 366 | + | |
| 367 | + """ | |
| 368 | + Freqtrade ROI Overload for dynamic trend based ROI functionality | |
| 369 | + """ | |
| 370 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 371 | + | |
| 372 | + dynamic_roi = self.dynamic_roi | |
| 373 | + minimal_roi = self.minimal_roi | |
| 374 | + | |
| 375 | + print(f"In the ROI place for pair: {trade.pair}") | |
| 376 | + | |
| 377 | + if not dynamic_roi or not minimal_roi: | |
| 378 | + return None, None | |
| 379 | + | |
| 380 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 381 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 382 | + if self.dp and self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 383 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 384 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 385 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 386 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 387 | + # Otherwise get it out of the dataframe | |
| 388 | + else: | |
| 389 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 390 | + roc = dataframe['roc'].iat[-1] | |
| 391 | + atr = dataframe['atr'].iat[-1] | |
| 392 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 393 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 394 | + | |
| 395 | + d = dynamic_roi | |
| 396 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 397 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 398 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 399 | + open_rate = trade.open_rate | |
| 400 | + | |
| 401 | + atr_roi = max(0, ((open_rate + atr) / open_rate) - 1) | |
| 402 | + roc_roi = max(0, (roc/100)) | |
| 403 | + | |
| 404 | + # If we observe a strong upward trend and our current profit is above the max (multiplied by a factor), hold | |
| 405 | + if (current_profit > (max_profit * profit_factor)) and (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 406 | + min_roi = 100 | |
| 407 | + # Otherwise fallback something else as specified | |
| 408 | + else: | |
| 409 | + if d['fallback'] == 'atr': | |
| 410 | + min_roi = atr_roi | |
| 411 | + if d['fallback'] == 'roc': | |
| 412 | + min_roi = roc_roi | |
| 413 | + else: | |
| 414 | + _, min_roi = self.min_roi_reached_entry(trade_dur) | |
| 415 | + else: | |
| 416 | + return self.min_roi_reached_entry(trade_dur) | |
| 417 | + | |
| 418 | + return trade_dur, min_roi | |
| 419 | + | |
| 420 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 421 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 422 | + | |
| 423 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 424 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 425 | + else: | |
| 426 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 427 | + if roi is None: | |
| 428 | + return False | |
| 429 | + else: | |
| 430 | + return current_profit > roi | |
| 431 | + | |
| 432 | + """ | |
| 433 | + Trade Timeout Overloads | |
| 434 | + """ | |
| 435 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 436 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 437 | + ob = self.dp.orderbook(pair, 1) | |
| 438 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 439 | + if current_price > order['price'] * 1.01: | |
| 440 | + return True | |
| 441 | + return False | |
| 442 | + | |
| 443 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 444 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 445 | + ob = self.dp.orderbook(pair, 1) | |
| 446 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 447 | + if current_price < order['price'] * 0.99: | |
| 448 | + return True | |
| 449 | + return False | |
| 450 | + | |
| 451 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 452 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 453 | + ob = self.dp.orderbook(pair, 1) | |
| 454 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 455 | + if current_price > rate * 1.01: | |
| 456 | + return False | |
| 457 | + return True | |
| 458 | + | |
| 459 | + | |
| 460 | + """ | |
| 461 | + Custom Methods | |
| 462 | + Stripped the active_trade and current_price stuff out of here when we moved to dynamic_roi and custom_stoploss | |
| 463 | + """ | |
| 464 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 465 | + buy_params = self.buy_params | |
| 466 | + sell_params = self.sell_params | |
| 467 | + | |
| 468 | + if self.custom_pair_params: | |
| 469 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 470 | + if custom_params['buy_params']: | |
| 471 | + buy_params = custom_params['buy_params'] | |
| 472 | + if custom_params['sell_params']: | |
| 473 | + sell_params = custom_params['sell_params'] | |
| 474 | + | |
| 475 | + if side == 'sell': | |
| 476 | + return sell_params | |
| 477 | + | |
| 478 | + return buy_params | |
| 479 | + | |
| 480 | +# Sub-strategy with parameters specific to BTC stake | |
| 481 | +class Solipsis_BTC(Solipsis3): | |
| 482 | + | |
| 483 | + timeframe = '1h' | |
| 484 | + inf_timeframe = '4h' | |
| 485 | + | |
| 486 | + buy_params = { | |
| 487 | + 'inf-rsi': 64, | |
| 488 | + 'mp': 55, | |
| 489 | + 'rmi-fast': 31, | |
| 490 | + 'rmi-slow': 16, | |
| 491 | + 'xinf-stake-rmi': 67, | |
| 492 | + 'xtf-fiat-rsi': 17, | |
| 493 | + 'xtf-stake-rsi': 57 | |
| 494 | + } | |
| 495 | + | |
| 496 | + minimal_roi = { | |
| 497 | + "0": 0.05, | |
| 498 | + "240": 0.025, | |
| 499 | + "1440": 0.01, | |
| 500 | + "4320": 0 | |
| 501 | + } | |
| 502 | + | |
| 503 | + stoploss = -0.30 | |
| 504 | + use_custom_stoploss = False | |
| 505 | + | |
| 506 | +# Sub-strategy with parameters specific to ETH stake | |
| 507 | +class Solipsis_ETH(Solipsis3): | |
| 508 | + | |
| 509 | + timeframe = '1h' | |
| 510 | + inf_timeframe = '4h' | |
| 511 | + | |
| 512 | + buy_params = { | |
| 513 | + 'inf-rsi': 13, | |
| 514 | + 'inf-stake-rmi': 69, | |
| 515 | + 'mp': 40, | |
| 516 | + 'rmi-fast': 42, | |
| 517 | + 'rmi-slow': 17, | |
| 518 | + 'tf-fiat-rsi': 15, | |
| 519 | + 'tf-stake-rsi': 92 | |
| 520 | + } | |
| 521 | + | |
| 522 | + minimal_roi = { | |
| 523 | + "0": 0.05, | |
| 524 | + "240": 0.025, | |
| 525 | + "1440": 0.01, | |
| 526 | + "4320": 0 | |
| 527 | + } | |
| 528 | + | |
| 529 | + stoploss = -0.30 | |
| 530 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Solipsis-v3.py +596 −0
| @@ -0,0 +1,596 @@ | ||
| 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 | |
| 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 and @JimmyNixx | |
| 27 | +This strategy is an evolution of our previous framework "Schism" which we are happy to share by request. | |
| 28 | + | |
| 29 | +FEATURES: | |
| 30 | + - Dynamic ROI | |
| 31 | + - Several options, initial idea was to ride trends past ROI in a similar way to trailing stoploss but using indicators. | |
| 32 | + - Fallback choices includes table, roc, atr, and others. Has the ability to set ROI table values dynamically based on indicator math. | |
| 33 | + - Custom Stoploss | |
| 34 | + - Generally a vanilla implementation of Freqtrade custom stoploss but tries to do some clever things. Uses indicator data. (Thanks @JoeSchr!) | |
| 35 | + - Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 36 | + - If BTC/STAKE is not in whitelist, make sure to use that for an informative. | |
| 37 | + - If your stake is BTC or ETH, use COIN/FIAT and BTC/FIAT as informatives. | |
| 38 | + - 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. | |
| 39 | + - Custom indicator file to keep primary strategy clean(ish). | |
| 40 | + - Most (but not all) of what is in here is taken from freqtrade/technical with some slight modification, removes dependenacy on that import and allows | |
| 41 | + for some customization without having to edit those files directly. | |
| 42 | + - Stub Child strategies for stake specific settings and different settings for different instances. | |
| 43 | + | |
| 44 | +STRATEGY NOTES: | |
| 45 | + - If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) is *highly recommended* that you remove BTC/STAKE | |
| 46 | + from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC | |
| 47 | + itself. | |
| 48 | + - It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with | |
| 49 | + "--enable-protections" as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 50 | + to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this | |
| 51 | + option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 52 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 53 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only and at least 1000 total epochs several times. There are | |
| 54 | + a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 55 | + | |
| 56 | + - Example of unique buy/sell params per pair/group of pairs: | |
| 57 | + | |
| 58 | + custom_pair_params = [ | |
| 59 | + { | |
| 60 | + 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 61 | + 'buy_params': {}, | |
| 62 | + 'sell_params': {}, | |
| 63 | + 'minimal_roi': {} | |
| 64 | + } | |
| 65 | + ] | |
| 66 | + | |
| 67 | +TODO: | |
| 68 | + - Continue to hunt for a better all around buy signal. | |
| 69 | + - Tweak ROI Trend Ride | |
| 70 | + - Verify ROI trend ride correctly reports profit during backtest. | |
| 71 | + - Further enchance and optimize custom stop loss | |
| 72 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 73 | + - Develop a PR to fully support trades database in backtest so we can go back to previous Schism methodology for buy/sell | |
| 74 | + rather than hacking the crap out of the ROI methods? | |
| 75 | + - Develop a PR to fully support hyperopting the custom_stoploss and dynamic_roi spaces? | |
| 76 | +""" | |
| 77 | + | |
| 78 | +class Solipsis3(IStrategy): | |
| 79 | + | |
| 80 | + # Recommended for USD/USDT/etc. | |
| 81 | + timeframe = '5m' | |
| 82 | + inf_timeframe = '1h' | |
| 83 | + | |
| 84 | + buy_params = { | |
| 85 | + 'base-mp': 61, | |
| 86 | + 'base-rmi-fast': 65, | |
| 87 | + 'base-rmi-slow': 27, | |
| 88 | + 'inf-guard': 'lower', | |
| 89 | + 'inf-pct-adr-bot': 0.14002, | |
| 90 | + 'inf-pct-adr-top': 0.98205, | |
| 91 | + 'xbtc-base-rmi': 56, | |
| 92 | + 'xbtc-inf-rmi': 17, | |
| 93 | + 'xtra-base-fiat-rmi': 45, | |
| 94 | + 'xtra-base-stake-rmi': 69, | |
| 95 | + 'xtra-inf-stake-rmi': 27 | |
| 96 | + } | |
| 97 | + | |
| 98 | + sell_params = {} | |
| 99 | + | |
| 100 | + # Custom buy/sell parameters per pair | |
| 101 | + custom_pair_params = [] | |
| 102 | + | |
| 103 | + # Recommended on 5m timeframe | |
| 104 | + minimal_roi = { | |
| 105 | + "0": 0.01, | |
| 106 | + "360": 0.005, | |
| 107 | + "720": 0 | |
| 108 | + } | |
| 109 | + | |
| 110 | + dynamic_roi = { | |
| 111 | + 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 112 | + 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 113 | + 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 114 | + 'rmi-end': 70, # ending value | |
| 115 | + 'grow-delay': 180, # delay on growth | |
| 116 | + 'grow-time': 720, # finish time of growth | |
| 117 | + 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 118 | + 'min-roc-atr': 0 # minimum roi value to return in roc or atr mode | |
| 119 | + } | |
| 120 | + | |
| 121 | + use_custom_stoploss = True | |
| 122 | + custom_stop = { | |
| 123 | + # Linear Decay Parameters | |
| 124 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 125 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 126 | + 'decay-start': -0.30, # starting value: should be the same or smaller than initial stoploss | |
| 127 | + 'decay-end': -0.01, # ending value | |
| 128 | + # Profit and TA | |
| 129 | + 'cur-min-diff': 0.02, # diff between current and minimum profit to move stoploss up to min profit point | |
| 130 | + 'cur-threshold': -0.01, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 131 | + 'roc-bail': -0.04, # value for roc to use for dynamic bailout | |
| 132 | + 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 133 | + 'bail-how': 'atr', # set the stoploss to the atr offset below current price, or immediate | |
| 134 | + # Positive Trailing | |
| 135 | + 'pos-trail': False, # enable trailing once positive | |
| 136 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 137 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 138 | + } | |
| 139 | + | |
| 140 | + stoploss = custom_stop['decay-start'] | |
| 141 | + | |
| 142 | + # Recommended | |
| 143 | + use_sell_signal = False | |
| 144 | + sell_profit_only = False | |
| 145 | + ignore_roi_if_buy_signal = False | |
| 146 | + | |
| 147 | + # Required | |
| 148 | + startup_candle_count: int = 72 | |
| 149 | + process_only_new_candles = False | |
| 150 | + | |
| 151 | + # Strategy Specific Variable Storage | |
| 152 | + custom_trade_info = {} | |
| 153 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 154 | + | |
| 155 | + """ | |
| 156 | + Informative Pair Definitions | |
| 157 | + """ | |
| 158 | + def informative_pairs(self): | |
| 159 | + # add all whitelisted pairs on informative timeframe | |
| 160 | + pairs = self.dp.current_whitelist() | |
| 161 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 162 | + | |
| 163 | + # add extra informative pairs if the stake is BTC or ETH | |
| 164 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 165 | + for pair in pairs: | |
| 166 | + coin, stake = pair.split('/') | |
| 167 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 168 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 169 | + | |
| 170 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 171 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 172 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 173 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 174 | + else: | |
| 175 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 176 | + if not btc_stake in pairs: | |
| 177 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 178 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 179 | + | |
| 180 | + return informative_pairs | |
| 181 | + | |
| 182 | + """ | |
| 183 | + Indicator Definitions | |
| 184 | + """ | |
| 185 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 186 | + if not metadata['pair'] in self.custom_trade_info: | |
| 187 | + self.custom_trade_info[metadata['pair']] = {} | |
| 188 | + | |
| 189 | + # Base timeframe indicators | |
| 190 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 191 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 192 | + | |
| 193 | + # Indicators for ROI and Custom Stoploss | |
| 194 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 195 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 196 | + | |
| 197 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 198 | + dataframe['roc-mp'] = ta.ROC(dataframe, timeperiod=6) | |
| 199 | + dataframe['mp'] = ta.RSI(dataframe['roc-mp'], timeperiod=6) | |
| 200 | + | |
| 201 | + # Trends, Peaks and Crosses | |
| 202 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 203 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 204 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 205 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 206 | + | |
| 207 | + # Base pair informative timeframe indicators | |
| 208 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 209 | + | |
| 210 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 211 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 212 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 213 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 214 | + | |
| 215 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 216 | + | |
| 217 | + # Other stake specific informative indicators | |
| 218 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 219 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 220 | + coin, stake = metadata['pair'].split('/') | |
| 221 | + fiat = self.custom_fiat | |
| 222 | + coin_fiat = f"{coin}/{fiat}" | |
| 223 | + stake_fiat = f"{stake}/{fiat}" | |
| 224 | + | |
| 225 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 226 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 227 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 228 | + | |
| 229 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 230 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 231 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 232 | + | |
| 233 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 234 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 235 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 236 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 237 | + | |
| 238 | + # Informatives for BTC/STAKE if not in whitelist | |
| 239 | + else: | |
| 240 | + pairs = self.dp.current_whitelist() | |
| 241 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 242 | + if not btc_stake in pairs: | |
| 243 | + # BTC/STAKE - Base Timeframe | |
| 244 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 245 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 246 | + | |
| 247 | + # BTC/STAKE - Informative Timeframe | |
| 248 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 249 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 250 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 251 | + | |
| 252 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 253 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 254 | + """ | |
| 255 | + # Attempting to use a temporary holding place for dynamic roi backtest return value... | |
| 256 | + if not 'backtest' in self.custom_trade_info: | |
| 257 | + self.custom_trade_info['backtest'] = {} | |
| 258 | + """ | |
| 259 | + | |
| 260 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 261 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 262 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 263 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 264 | + | |
| 265 | + return dataframe | |
| 266 | + | |
| 267 | + """ | |
| 268 | + Buy Signal | |
| 269 | + """ | |
| 270 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 271 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 272 | + conditions = [] | |
| 273 | + | |
| 274 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 275 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 276 | + conditions.append( | |
| 277 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 278 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 279 | + ) | |
| 280 | + | |
| 281 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 282 | + conditions.append( | |
| 283 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 284 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 285 | + ) | |
| 286 | + | |
| 287 | + # Base Timeframe | |
| 288 | + conditions.append( | |
| 289 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 290 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 291 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 292 | + (dataframe['mp'] <= params['base-mp']) | |
| 293 | + ) | |
| 294 | + | |
| 295 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 296 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 297 | + conditions.append( | |
| 298 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 299 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 300 | + ) | |
| 301 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] > params['xtra-inf-stake-rmi']) | |
| 302 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 303 | + else: | |
| 304 | + pairs = self.dp.current_whitelist() | |
| 305 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 306 | + if not btc_stake in pairs: | |
| 307 | + conditions.append( | |
| 308 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 309 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 310 | + ) | |
| 311 | + | |
| 312 | + conditions.append(dataframe['volume'].gt(0)) | |
| 313 | + | |
| 314 | + if conditions: | |
| 315 | + dataframe.loc[ | |
| 316 | + reduce(lambda x, y: x & y, conditions), | |
| 317 | + 'buy'] = 1 | |
| 318 | + | |
| 319 | + return dataframe | |
| 320 | + | |
| 321 | + """ | |
| 322 | + Sell Signal | |
| 323 | + """ | |
| 324 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 325 | + # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 326 | + | |
| 327 | + dataframe['sell'] = 0 | |
| 328 | + | |
| 329 | + return dataframe | |
| 330 | + | |
| 331 | + """ | |
| 332 | + Custom Stoploss | |
| 333 | + """ | |
| 334 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 335 | + params = self.get_pair_params(pair, 'custom_stop') | |
| 336 | + | |
| 337 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 338 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 339 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 340 | + profit_diff = current_profit - min_profit | |
| 341 | + | |
| 342 | + decay_stoploss = cta.linear_growth(params['decay-start'], params['decay-end'], params['decay-delay'], params['decay-time'], trade_dur) | |
| 343 | + | |
| 344 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 345 | + if params['pos-trail'] == True: | |
| 346 | + if current_profit > params['pos-threshold']: | |
| 347 | + return current_profit - params['pos-trail-dist'] | |
| 348 | + | |
| 349 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 350 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 351 | + roc = dataframe['roc'].iat[-1] | |
| 352 | + atr = dataframe['atr'].iat[-1] | |
| 353 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 354 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 355 | + else: | |
| 356 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 357 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 358 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 359 | + | |
| 360 | + if current_profit < params['cur-threshold']: | |
| 361 | + # Dynamic bailout based on rate of change | |
| 362 | + if (roc/100) <= params['roc-bail']: | |
| 363 | + if params['bail-how'] == 'atr': | |
| 364 | + return ((current_rate - atr)/current_rate) - 1 | |
| 365 | + elif params['bail-how'] == 'immediate': | |
| 366 | + return current_rate | |
| 367 | + else: | |
| 368 | + return decay_stoploss | |
| 369 | + | |
| 370 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 371 | + if (current_profit > min_profit) or roc > 0 or rmi_slow >= params['rmi-trend']: | |
| 372 | + if profit_diff > params['cur-min-diff']: | |
| 373 | + return min_profit | |
| 374 | + return -1 | |
| 375 | + | |
| 376 | + return decay_stoploss | |
| 377 | + | |
| 378 | + """ | |
| 379 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 380 | + """ | |
| 381 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 382 | + | |
| 383 | + dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 384 | + minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 385 | + | |
| 386 | + if not dynamic_roi or not minimal_roi: | |
| 387 | + return None, None | |
| 388 | + | |
| 389 | + _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 390 | + | |
| 391 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 392 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 393 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 394 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 395 | + roc = dataframe['roc'].iat[-1] | |
| 396 | + atr = dataframe['atr'].iat[-1] | |
| 397 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 398 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 399 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 400 | + else: | |
| 401 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 402 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 403 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 404 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 405 | + | |
| 406 | + d = dynamic_roi | |
| 407 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 408 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 409 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 410 | + open_rate = trade.open_rate | |
| 411 | + | |
| 412 | + atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 413 | + roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 414 | + | |
| 415 | + # atr as the fallback (if > min-roc-atr) | |
| 416 | + if d['fallback'] == 'atr': | |
| 417 | + min_roi = atr_roi | |
| 418 | + # roc as the fallback (if > min-roc-atr) | |
| 419 | + elif d['fallback'] == 'roc': | |
| 420 | + min_roi = roc_roi | |
| 421 | + # atr or table as the fallback (whichever is larger) | |
| 422 | + elif d['fallback'] == 'atr-table': | |
| 423 | + min_roi = max(table_roi, atr_roi) | |
| 424 | + # roc or table as the fallback (whichever is larger) | |
| 425 | + elif d['fallback'] == 'roc-table': | |
| 426 | + min_roi = max(table_roi, roc_roi) | |
| 427 | + # default to table | |
| 428 | + else: | |
| 429 | + min_roi = table_roi | |
| 430 | + | |
| 431 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 432 | + if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 433 | + if current_profit > min_roi and (current_profit < (max_profit * profit_factor)): | |
| 434 | + min_roi = min_roi | |
| 435 | + else: | |
| 436 | + min_roi = 100 | |
| 437 | + | |
| 438 | + else: | |
| 439 | + min_roi = table_roi | |
| 440 | + | |
| 441 | + """ | |
| 442 | + # Attempting to wedge the dynamic roi value into a thing so we can trick backtesting... | |
| 443 | + if self.config['runmode'].value not in ('live', 'dry_run'): | |
| 444 | + # Theoretically, if backtesting uses this value, ROI was triggered so we need to trick it with a sell | |
| 445 | + # rate other than what is on the standard ROI table... | |
| 446 | + self.custom_trade_info['backtest']['roi'] = max(min_roi, current_profit) | |
| 447 | + """ | |
| 448 | + | |
| 449 | + return trade_dur, min_roi | |
| 450 | + | |
| 451 | + # Minor change to the usual method here to allow feeding the pair for per-pair settings | |
| 452 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 453 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 454 | + | |
| 455 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 456 | + if not roi_list: | |
| 457 | + return None, None | |
| 458 | + roi_entry = max(roi_list) | |
| 459 | + min_roi = minimal_roi[roi_entry] | |
| 460 | + | |
| 461 | + """ | |
| 462 | + # Attempting to take the dynamic roi value out of a thing so we can trick backtesting... | |
| 463 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 464 | + if pair == 'backtest': | |
| 465 | + min_roi = self.custom_trade_info['backtest']['roi'] | |
| 466 | + """ | |
| 467 | + | |
| 468 | + return roi_entry, min_roi | |
| 469 | + | |
| 470 | + # Change here to allow loading of the dynamic_roi settings | |
| 471 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 472 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 473 | + | |
| 474 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 475 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 476 | + else: | |
| 477 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 478 | + if roi is None: | |
| 479 | + return False | |
| 480 | + else: | |
| 481 | + return current_profit > roi | |
| 482 | + | |
| 483 | + """ | |
| 484 | + Trade Timeout Overloads | |
| 485 | + """ | |
| 486 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 487 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 488 | + ob = self.dp.orderbook(pair, 1) | |
| 489 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 490 | + if current_price > order['price'] * 1.01: | |
| 491 | + return True | |
| 492 | + return False | |
| 493 | + | |
| 494 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 495 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 496 | + ob = self.dp.orderbook(pair, 1) | |
| 497 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 498 | + if current_price < order['price'] * 0.99: | |
| 499 | + return True | |
| 500 | + return False | |
| 501 | + | |
| 502 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 503 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 504 | + ob = self.dp.orderbook(pair, 1) | |
| 505 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 506 | + if current_price > rate * 1.01: | |
| 507 | + return False | |
| 508 | + return True | |
| 509 | + | |
| 510 | + """ | |
| 511 | + Custom Methods | |
| 512 | + """ | |
| 513 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 514 | + buy_params = self.buy_params | |
| 515 | + sell_params = self.sell_params | |
| 516 | + minimal_roi = self.minimal_roi | |
| 517 | + custom_stop = self.custom_stop | |
| 518 | + dynamic_roi = self.dynamic_roi | |
| 519 | + | |
| 520 | + if self.custom_pair_params: | |
| 521 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 522 | + if custom_params['buy_params']: | |
| 523 | + buy_params = custom_params['buy_params'] | |
| 524 | + if custom_params['sell_params']: | |
| 525 | + sell_params = custom_params['sell_params'] | |
| 526 | + if custom_params['minimal_roi']: | |
| 527 | + custom_stop = custom_params['minimal_roi'] | |
| 528 | + if custom_params['custom_stop']: | |
| 529 | + custom_stop = custom_params['custom_stop'] | |
| 530 | + if custom_params['dynamic_roi']: | |
| 531 | + dynamic_roi = custom_params['dynamic_roi'] | |
| 532 | + | |
| 533 | + if params == 'buy': | |
| 534 | + return buy_params | |
| 535 | + if params == 'sell': | |
| 536 | + return sell_params | |
| 537 | + if params == 'minimal_roi': | |
| 538 | + return minimal_roi | |
| 539 | + if params == 'custom_stop': | |
| 540 | + return custom_stop | |
| 541 | + if params == 'dynamic_roi': | |
| 542 | + return dynamic_roi | |
| 543 | + | |
| 544 | + return False | |
| 545 | + | |
| 546 | +# Sub-strategy with parameters specific to BTC stake | |
| 547 | +class Solipsis3_BTC(Solipsis3): | |
| 548 | + | |
| 549 | + timeframe = '1h' | |
| 550 | + inf_timeframe = '4h' | |
| 551 | + | |
| 552 | + buy_params = { | |
| 553 | + 'inf-rsi': 64, | |
| 554 | + 'mp': 55, | |
| 555 | + 'rmi-fast': 31, | |
| 556 | + 'rmi-slow': 16, | |
| 557 | + 'xinf-stake-rmi': 67, | |
| 558 | + 'xtf-fiat-rsi': 17, | |
| 559 | + 'xtf-stake-rsi': 57 | |
| 560 | + } | |
| 561 | + | |
| 562 | + minimal_roi = { | |
| 563 | + "0": 0.05, | |
| 564 | + "240": 0.025, | |
| 565 | + "1440": 0.01, | |
| 566 | + "4320": 0 | |
| 567 | + } | |
| 568 | + | |
| 569 | + stoploss = -0.30 | |
| 570 | + use_custom_stoploss = False | |
| 571 | + | |
| 572 | +# Sub-strategy with parameters specific to ETH stake | |
| 573 | +class Solipsis3_ETH(Solipsis3): | |
| 574 | + | |
| 575 | + timeframe = '1h' | |
| 576 | + inf_timeframe = '4h' | |
| 577 | + | |
| 578 | + buy_params = { | |
| 579 | + 'inf-rsi': 13, | |
| 580 | + 'inf-stake-rmi': 69, | |
| 581 | + 'mp': 40, | |
| 582 | + 'rmi-fast': 42, | |
| 583 | + 'rmi-slow': 17, | |
| 584 | + 'tf-fiat-rsi': 15, | |
| 585 | + 'tf-stake-rsi': 92 | |
| 586 | + } | |
| 587 | + | |
| 588 | + minimal_roi = { | |
| 589 | + "0": 0.05, | |
| 590 | + "240": 0.025, | |
| 591 | + "1440": 0.01, | |
| 592 | + "4320": 0 | |
| 593 | + } | |
| 594 | + | |
| 595 | + stoploss = -0.30 | |
| 596 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/SolipsisMM.py +720 −0
| @@ -0,0 +1,720 @@ | ||
| 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 | |
| 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 statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | +from scipy.signal import argrelextrema | |
| 16 | + | |
| 17 | +# Get rid of pandas warnings during backtesting | |
| 18 | +import pandas as pd | |
| 19 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 20 | + | |
| 21 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 22 | +import sys | |
| 23 | +from pathlib import Path | |
| 24 | +sys.path.append(str(Path(__file__).parent)) | |
| 25 | + | |
| 26 | +import custom_indicators as cta | |
| 27 | + | |
| 28 | +""" | |
| 29 | +TODO: | |
| 30 | + - Continue to hunt for a better all around buy signal. | |
| 31 | + - Prevent buys when potential for strong downward trend and not just a dip? | |
| 32 | + - ADR guards are helping but need to reduce losing trade counts. | |
| 33 | + - Need to reduce drawdown. | |
| 34 | + - Tweak ROI Trend Ride | |
| 35 | + - Maybe use free_slots as a factor in how eager we are to sell? | |
| 36 | + - Maybe further exploit the ROI table itself using trade data? | |
| 37 | + - Per-pair automatic ROI points based on ADR/ATR or something similar? | |
| 38 | + - Tweak sell signal | |
| 39 | + - Continue to evaluate good circumstances to bail and sell vs hold on for recovery | |
| 40 | + - Further enchance and optimize custom stop loss | |
| 41 | + - Figure out a way to directly feed a daily hyperopt output into a running strategy and reload it? | |
| 42 | + | |
| 43 | +STRATEGY NOTES: | |
| 44 | + - It is recommended to configure protections *if/as* you will use them in live and run hyperopt/backtest with | |
| 45 | + --enable-protections as this strategy will hit a lot of stoplosses so the stoploss protection is helpful | |
| 46 | + to test. | |
| 47 | + - Keep in mind the sell signal (dynamic bailout) does not function in backtest and this strategy should be | |
| 48 | + validated and tested in dry-run before live. If you do not want to use the sell and only rely on the bits | |
| 49 | + of the strategy that can be backtested be sure to turn use_sell_signal = False. | |
| 50 | + - If running backtest/hyperopt around the portion of the sell signal that is testable, keep in mind in live/dry | |
| 51 | + it will not sell nearly as frequently due to the profit guard and other_profit / free_slot guards. | |
| 52 | + - Keep in mind that due to the dynamic ROI trend ride this strategy implements that most sells for ROI will | |
| 53 | + actually sell for more profit than the ROI table dictates and you can assume that your average profit from | |
| 54 | + ROI based sells will be higher than the backtest shows. | |
| 55 | + - It is *not* worthwhile to hyperopt for roi as it does not take into account the roi trend ride we are doing and | |
| 56 | + having ROI points that are too high will sort of be counter-productive to how this strategy works even if it seems | |
| 57 | + to produce better results in backtesting. | |
| 58 | + - It is *probably not* worthwhile to hyperopt the stoploss as we can't hyperopt any of the parameters in the custom stoploss | |
| 59 | + so hyperopting the stoploss is only looking at one aspect of it. | |
| 60 | + - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. | |
| 61 | + - It is *highly* recommended to backtest with use_sell_signal = False because it will not behave remotely the same in dry/live | |
| 62 | + - It is *highly* recommended to hyperopt this with '--spaces buy' only or 'buy sell' and at least 5000 total epochs, but a preliminary | |
| 63 | + set of sane defaults is: | |
| 64 | + | |
| 65 | + buy_params = { | |
| 66 | + 'base-fib-level': 0.618, | |
| 67 | + 'base-mp': 30, | |
| 68 | + 'base-pmax': 'up', | |
| 69 | + 'base-pmax-enable': False, | |
| 70 | + 'base-rmi-fast': 50, | |
| 71 | + 'base-rmi-slow': 20, | |
| 72 | + 'base-trend': 'down', | |
| 73 | + 'inf-fib-level': 0.236, | |
| 74 | + 'inf-guard': 'upper', | |
| 75 | + 'inf-pct-adr-bot': 0.05, | |
| 76 | + 'inf-pct-adr-top': 0.80, | |
| 77 | + 'inf-rsi': 20, | |
| 78 | + 'xtra-base-fiat-rsi': 30, | |
| 79 | + 'xtra-base-stake-rsi': 60, | |
| 80 | + 'xtra-inf-stake-rmi': 20 | |
| 81 | + } | |
| 82 | + | |
| 83 | + sell_params = { | |
| 84 | + 'sell-rmi-drop': 0.50, | |
| 85 | + 'sell-pmax-enable': False | |
| 86 | + } | |
| 87 | +""" | |
| 88 | + | |
| 89 | +class SolipsisMM(IStrategy): | |
| 90 | + | |
| 91 | + # Recommended for USD/USDT/etc. | |
| 92 | + timeframe = '5m' | |
| 93 | + inf_timeframe = '1h' | |
| 94 | + | |
| 95 | + buy_params = { | |
| 96 | + 'base-fib-level': 0.618, | |
| 97 | + 'base-mp': 84, | |
| 98 | + 'base-pmax': 'up', | |
| 99 | + 'base-pmax-enable': True, | |
| 100 | + 'base-rmi-fast': 44, | |
| 101 | + 'base-rmi-slow': 27, | |
| 102 | + 'base-trend': 'down', | |
| 103 | + 'inf-fib-level': 0.0, | |
| 104 | + 'inf-guard': 'both', | |
| 105 | + 'inf-pct-adr-bot': 0.05725, | |
| 106 | + 'inf-pct-adr-top': 0.98309, | |
| 107 | + 'inf-rsi': 22, | |
| 108 | + 'xtra-base-fiat-rsi': 70, | |
| 109 | + 'xtra-base-stake-rsi': 50, | |
| 110 | + 'xtra-inf-stake-rmi': 47 | |
| 111 | + } | |
| 112 | + | |
| 113 | + # Sell hyperspace params: | |
| 114 | + sell_params = { | |
| 115 | + 'sell-pmax-enable': True, | |
| 116 | + 'sell-rmi-drop': 0.89661 | |
| 117 | + } | |
| 118 | + | |
| 119 | + # Custom buy/sell parameters per pair | |
| 120 | + custom_pair_params = [] | |
| 121 | + | |
| 122 | + # Recommended on 5m timeframe | |
| 123 | + minimal_roi = { | |
| 124 | + "0": 0.05, | |
| 125 | + "30": 0.025, | |
| 126 | + "120": 0.01, | |
| 127 | + "360": 0.01, | |
| 128 | + "720": 0.005, | |
| 129 | + "1440": 0 | |
| 130 | + } | |
| 131 | + | |
| 132 | + # Optional | |
| 133 | + dynamic_roi = { | |
| 134 | + 'dynamic_roi_enabled': True, | |
| 135 | + 'dynamic_roi_type': 'connect' | |
| 136 | + } | |
| 137 | + | |
| 138 | + stoploss = -0.30 | |
| 139 | + | |
| 140 | + # Optional | |
| 141 | + use_custom_stoploss = True | |
| 142 | + custom_stop = { | |
| 143 | + 'decay-time': 1080, # minutes to reach end | |
| 144 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 145 | + 'decay-start': -0.30, # starting value: should be the same as initial stoploss | |
| 146 | + 'decay-end': -0.03, # ending value | |
| 147 | + 'pos-trail': False, # enable trailing once positive | |
| 148 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 149 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 150 | + } | |
| 151 | + | |
| 152 | + # Recommended | |
| 153 | + use_sell_signal = True | |
| 154 | + sell_profit_only = False | |
| 155 | + ignore_roi_if_buy_signal = True | |
| 156 | + | |
| 157 | + # Required | |
| 158 | + startup_candle_count: int = 72 | |
| 159 | + process_only_new_candles = False | |
| 160 | + | |
| 161 | + # Strategy Specific Variable Storage | |
| 162 | + custom_trade_info = {} | |
| 163 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 164 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) | |
| 165 | + | |
| 166 | + # Parameters dealing with the ROI ride the sell signal behind active_trade | |
| 167 | + custom_active_trade = { | |
| 168 | + # linear decay on RMI trend threshold | |
| 169 | + 'roi-pft-factor': 400, | |
| 170 | + 'roi-rmi-start': 30, | |
| 171 | + 'roi-rmi-end': 70, | |
| 172 | + 'roi-delay': 180, | |
| 173 | + 'roi-time': 720, | |
| 174 | + # loss thresholds | |
| 175 | + 'sell-mkt-down': -0.04, | |
| 176 | + 'loss-start': -0.03, | |
| 177 | + 'loss-end': 0, | |
| 178 | + 'loss-delay': 0, | |
| 179 | + 'loss-time': 240 | |
| 180 | + } | |
| 181 | + | |
| 182 | + """ | |
| 183 | + Informative Pair Definitions | |
| 184 | + """ | |
| 185 | + def informative_pairs(self): | |
| 186 | + pairs = self.dp.current_whitelist() | |
| 187 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 188 | + | |
| 189 | + # add extra informative pairs if the stake is BTC or ETH | |
| 190 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 191 | + for pair in pairs: | |
| 192 | + coin, stake = pair.split('/') | |
| 193 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 194 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 195 | + | |
| 196 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 197 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 198 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 199 | + | |
| 200 | + return informative_pairs | |
| 201 | + | |
| 202 | + """ | |
| 203 | + Indicator Definitions | |
| 204 | + """ | |
| 205 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 206 | + buy_params = self.get_pair_params(metadata['pair'], 'buy') | |
| 207 | + sell_params = self.get_pair_params(metadata['pair'], 'sell') | |
| 208 | + | |
| 209 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 210 | + | |
| 211 | + # Base timeframe indicators | |
| 212 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 213 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 214 | + | |
| 215 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 216 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=6) | |
| 217 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6) | |
| 218 | + | |
| 219 | + # RMI Trends and Peaks | |
| 220 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 221 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 222 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 223 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 224 | + dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max() | |
| 225 | + | |
| 226 | + # Fibonacci Retracements | |
| 227 | + dataframe['fib-ret'] = cta.fib_ret(dataframe) | |
| 228 | + | |
| 229 | + # PMAX | |
| 230 | + # matype = ema, src = hl2 | |
| 231 | + # pmax is really slow, only enable it if its actually being used. | |
| 232 | + if buy_params['base-pmax-enable'] == True or sell_params['sell-pmax-enable'] == True: | |
| 233 | + atr, ma, pmax, pm_loc = cta.PMAX(dataframe, period=10, multiplier=3, length=12, MAtype=1, src=2) | |
| 234 | + dataframe['pmax-trend'] = pm_loc | |
| 235 | + else: | |
| 236 | + dataframe['pmax-trend'] = False | |
| 237 | + | |
| 238 | + # Other stake specific informative indicators | |
| 239 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 240 | + # TODO: Re-evaluate the value of these informative indicators | |
| 241 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 242 | + coin, stake = metadata['pair'].split('/') | |
| 243 | + fiat = self.custom_fiat | |
| 244 | + coin_fiat = f"{coin}/{fiat}" | |
| 245 | + stake_fiat = f"{stake}/{fiat}" | |
| 246 | + | |
| 247 | + # Informative COIN/FIAT e.g. XLM/USD | |
| 248 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 249 | + dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14) | |
| 250 | + | |
| 251 | + # Informative STAKE/FIAT e.g. BTC/USD | |
| 252 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 253 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 254 | + | |
| 255 | + dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14) | |
| 256 | + dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = cta.RMI(stake_fiat_inf_tf, length=21, mom=5) | |
| 257 | + | |
| 258 | + # Base pair informative timeframe indicators | |
| 259 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 260 | + informative['rsi'] = ta.RSI(informative, timeperiod=14) | |
| 261 | + | |
| 262 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 263 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 264 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 265 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 266 | + | |
| 267 | + informative['fib-ret'] = cta.fib_ret(informative) | |
| 268 | + | |
| 269 | + min_peaks = argrelextrema(dataframe['close'].values, np.less, order=100) | |
| 270 | + | |
| 271 | + for mp in min_peaks[0]: | |
| 272 | + dataframe.at[mp, 'buy_signal'] = True | |
| 273 | + | |
| 274 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 275 | + | |
| 276 | + return dataframe | |
| 277 | + | |
| 278 | + """ | |
| 279 | + Buy Signal | |
| 280 | + """ | |
| 281 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 282 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 283 | + at = self.custom_active_trade | |
| 284 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 285 | + conditions = [] | |
| 286 | + | |
| 287 | + """ | |
| 288 | + The primary "secret sauce" of Solipsis is to take advantage of the ignore_roi_if_buy_signal setting. | |
| 289 | + Ideally, the ROI table is very tight and aggressive allowing for quick exits on ROI without reliance | |
| 290 | + on a sell signal. However, if certain criteria are met for an open trade, we stimulate a sticking buy | |
| 291 | + signal on purpose to prevent the bot from selling to the ROI in the midst of an upward trend. | |
| 292 | + | |
| 293 | + This is not currently able to be backtested or hyperopted so all settings here must be tested and validated | |
| 294 | + in dry-run or live. It is safe to assume that when backtesting, all sells for reason roi will have likely been | |
| 295 | + for higher profits in live trading than in backtest. | |
| 296 | + """ | |
| 297 | + | |
| 298 | + # If active trade, look at trend to persist a buy signal for ignore_roi_if_buy_signal | |
| 299 | + if trade_data['active_trade']: | |
| 300 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / at['roi-pft-factor'])) | |
| 301 | + rmi_grow = cta.linear_growth(at['roi-rmi-start'], at['roi-rmi-end'], | |
| 302 | + at['roi-delay'], at['roi-time'], trade_data['open_minutes']) | |
| 303 | + | |
| 304 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 305 | + # TODO: Experiment with replacing or augmenting this with PMAX | |
| 306 | + conditions.append( | |
| 307 | + ( | |
| 308 | + (params['base-pmax-enable'] == True) & | |
| 309 | + (dataframe['pmax-trend'] == 'up') | |
| 310 | + ) | ( | |
| 311 | + (dataframe['rmi-up-trend'] == 1) & | |
| 312 | + (dataframe['rmi-slow'] >= rmi_grow) | |
| 313 | + ) | |
| 314 | + ) | |
| 315 | + | |
| 316 | + # Standard signals for entering new trades | |
| 317 | + else: | |
| 318 | + | |
| 319 | + # Guards on informative timeframe | |
| 320 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 321 | + conditions.append( | |
| 322 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 323 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 324 | + ) | |
| 325 | + | |
| 326 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 327 | + conditions.append( | |
| 328 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 329 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 330 | + ) | |
| 331 | + | |
| 332 | + # Informative Timeframe | |
| 333 | + conditions.append( | |
| 334 | + (dataframe[f"rsi_{self.inf_timeframe}"] >= params['inf-rsi']) & | |
| 335 | + (dataframe[f"fib-ret_{self.inf_timeframe}"] >= params['inf-fib-level']) | |
| 336 | + ) | |
| 337 | + | |
| 338 | + if params['base-pmax-enable'] == True: | |
| 339 | + conditions.append((dataframe['pmax-trend'] == params['base-pmax'])) | |
| 340 | + | |
| 341 | + # # Base Timeframe | |
| 342 | + # Look for bottom of downward trend and expect bounce | |
| 343 | + if params['base-trend'] == 'down': | |
| 344 | + conditions.append( | |
| 345 | + (dataframe['fib-ret'] <= params['base-fib-level']) & | |
| 346 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 347 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 348 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 349 | + (dataframe['mp'] <= params['base-mp']) | |
| 350 | + ) | |
| 351 | + | |
| 352 | + # Look for upward trend | |
| 353 | + elif params['base-trend'] == 'up': | |
| 354 | + conditions.append( | |
| 355 | + (dataframe['fib-ret'] >= params['base-fib-level']) & | |
| 356 | + (dataframe['rmi-up-trend'] == 1) & | |
| 357 | + (dataframe['rmi-slow'] <= params['base-rmi-slow']) & | |
| 358 | + (dataframe['rmi-fast'] >= params['base-rmi-fast']) & | |
| 359 | + (dataframe['mp'] >= params['base-mp']) | |
| 360 | + ) | |
| 361 | + | |
| 362 | + # Extra conditions for BTC/ETH stakes on additional informative pairs | |
| 363 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 364 | + conditions.append( | |
| 365 | + (dataframe[f"{self.config['stake_currency']}_rsi"] < params['xtra-base-stake-rsi']) | | |
| 366 | + (dataframe[f"{self.custom_fiat}_rsi"] > params['xtra-base-fiat-rsi']) | |
| 367 | + ) | |
| 368 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 369 | + | |
| 370 | + # Applies to active or new trades | |
| 371 | + conditions.append(dataframe['buy_signal']) | |
| 372 | + conditions.append(dataframe['volume'].gt(0)) | |
| 373 | + | |
| 374 | + if conditions: | |
| 375 | + dataframe.loc[ | |
| 376 | + reduce(lambda x, y: x & y, conditions), | |
| 377 | + 'buy'] = 1 | |
| 378 | + | |
| 379 | + return dataframe | |
| 380 | + | |
| 381 | + """ | |
| 382 | + Sell Signal | |
| 383 | + """ | |
| 384 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 385 | + params = self.get_pair_params(metadata['pair'], 'sell') | |
| 386 | + at = self.custom_active_trade | |
| 387 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 388 | + conditions = [] | |
| 389 | + | |
| 390 | + """ | |
| 391 | + Previous Schism sell implementation has been *partially* replaced by custom_stoploss. | |
| 392 | + Doing it there makes it able to be backtested more realistically but some of the functionality | |
| 393 | + such as the ability to use other trades or the # of slots in our decision need to remain here. | |
| 394 | + | |
| 395 | + The current sell is meant to be a pre-stoploss bailout but most sells at a loss | |
| 396 | + should happen due to the stoploss in live/dry. | |
| 397 | + | |
| 398 | + ** Only part of this signal functions in backtest/hyperopt. Can only be optimized in live/dry. | |
| 399 | + ** Results in backtest/hyperopts will sell far more readily than in live due to the profit guards. | |
| 400 | + """ | |
| 401 | + | |
| 402 | + # If we are in an active trade (which is the only way a sell can occur...) | |
| 403 | + # This is needed to block backtest/hyperopt from hitting the profit stuff and erroring out. | |
| 404 | + if trade_data['active_trade']: | |
| 405 | + # Decay a loss cutoff point where we allow a sell to occur idea is this allows | |
| 406 | + # a trade to go into the negative a little bit before we react to sell. | |
| 407 | + loss_cutoff = cta.linear_growth(at['loss-start'], at['loss-end'], | |
| 408 | + at['loss-delay'], at['loss-time'], trade_data['open_minutes']) | |
| 409 | + | |
| 410 | + conditions.append((trade_data['current_profit'] < loss_cutoff)) | |
| 411 | + | |
| 412 | + # Examine the state of our other trades and free_slots to inform the decision | |
| 413 | + if trade_data['other_trades']: | |
| 414 | + if trade_data['free_slots'] > 0: | |
| 415 | + # If the average of all our other trades is below a certain threshold based | |
| 416 | + # on free slots available, hold and wait for market recovery. | |
| 417 | + hold_pct = (1/trade_data['free_slots']) * at['sell-mkt-down'] | |
| 418 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 419 | + else: | |
| 420 | + # If we are out of free slots disregard the above and allow the biggest loser to sell. | |
| 421 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 422 | + | |
| 423 | + # Primary sell trigger | |
| 424 | + rmi_drop = dataframe['rmi-max'] - (dataframe['rmi-max'] * params['sell-rmi-drop']) | |
| 425 | + conditions.append( | |
| 426 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 427 | + (qtpylib.crossed_below(dataframe['rmi-slow'], rmi_drop)) & | |
| 428 | + (dataframe['volume'].gt(0)) | |
| 429 | + ) | |
| 430 | + | |
| 431 | + if params['sell-pmax-enable'] == True: | |
| 432 | + conditions.append((dataframe['pmax-trend'] == 'down')) | |
| 433 | + | |
| 434 | + if conditions: | |
| 435 | + dataframe.loc[ | |
| 436 | + reduce(lambda x, y: x & y, conditions), | |
| 437 | + 'sell'] = 1 | |
| 438 | + | |
| 439 | + return dataframe | |
| 440 | + | |
| 441 | + """ | |
| 442 | + Custom Stoploss | |
| 443 | + """ | |
| 444 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 445 | + start = self.custom_stop['decay-start'] | |
| 446 | + end = self.custom_stop['decay-end'] | |
| 447 | + time = self.custom_stop['decay-time'] | |
| 448 | + delay = self.custom_stop['decay-delay'] | |
| 449 | + pos_trail = self.custom_stop['pos-trail'] | |
| 450 | + pos_threshold = self.custom_stop['pos-threshold'] | |
| 451 | + pos_trail_dist = self.custom_stop['pos-trail-dist'] | |
| 452 | + | |
| 453 | + open_minutes: int = (current_time - trade.open_date).total_seconds() // 60 | |
| 454 | + | |
| 455 | + decay_stoploss = cta.linear_growth(start, end, delay, time, open_minutes) | |
| 456 | + | |
| 457 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 458 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 459 | + profit_diff = current_profit - min_profit | |
| 460 | + | |
| 461 | + if pos_trail == True: | |
| 462 | + # if trade is positive above threshold, immediately move the stoploss up to x% behind it | |
| 463 | + if current_profit > pos_threshold: | |
| 464 | + return current_profit - pos_trail_dist | |
| 465 | + | |
| 466 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 467 | + if current_profit > min_profit: | |
| 468 | + if profit_diff > 0.015: | |
| 469 | + return min_profit | |
| 470 | + return -1 | |
| 471 | + | |
| 472 | + # otherwise return the time decaying stoploss | |
| 473 | + return decay_stoploss | |
| 474 | + | |
| 475 | + """ | |
| 476 | + Trade Timeout Overloads | |
| 477 | + """ | |
| 478 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 479 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 480 | + ob = self.dp.orderbook(pair, 1) | |
| 481 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 482 | + if current_price > order['price'] * 1.01: | |
| 483 | + return True | |
| 484 | + return False | |
| 485 | + | |
| 486 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 487 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 488 | + ob = self.dp.orderbook(pair, 1) | |
| 489 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 490 | + if current_price < order['price'] * 0.99: | |
| 491 | + return True | |
| 492 | + return False | |
| 493 | + | |
| 494 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 495 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 496 | + ob = self.dp.orderbook(pair, 1) | |
| 497 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 498 | + if current_price > rate * 1.01: | |
| 499 | + return False | |
| 500 | + return True | |
| 501 | + | |
| 502 | + """ | |
| 503 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 504 | + """ | |
| 505 | + def min_roi_reached_dynamic(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 506 | + | |
| 507 | + dynamic_roi = self.dynamic_roi | |
| 508 | + minimal_roi = self.minimal_roi | |
| 509 | + | |
| 510 | + if not dynamic_roi: | |
| 511 | + return None, None | |
| 512 | + | |
| 513 | + if 'dynamic_roi_type' in dynamic_roi and dynamic_roi['dynamic_roi_type'] \ | |
| 514 | + in ['linear', 'exponential', 'connect']: | |
| 515 | + roi_type = dynamic_roi['dynamic_roi_type'] | |
| 516 | + # linear decay: f(t) = start - (rate * t) | |
| 517 | + if roi_type == 'linear': | |
| 518 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 519 | + 'dynamic_roi_time' in dynamic_roi: | |
| 520 | + start = dynamic_roi['dynamic_roi_start'] | |
| 521 | + end = dynamic_roi['dynamic_roi_end'] | |
| 522 | + time = dynamic_roi['dynamic_roi_time'] | |
| 523 | + rate = (start - end) / time | |
| 524 | + min_roi = max(end, start - (rate * trade_dur)) | |
| 525 | + else: | |
| 526 | + return None, None | |
| 527 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 528 | + elif roi_type == 'exponential': | |
| 529 | + if 'dynamic_roi_start' in dynamic_roi and 'dynamic_roi_end' in dynamic_roi and \ | |
| 530 | + 'dynamic_roi_rate' in dynamic_roi: | |
| 531 | + start = dynamic_roi['dynamic_roi_start'] | |
| 532 | + end = dynamic_roi['dynamic_roi_end'] | |
| 533 | + rate = dynamic_roi['dynamic_roi_rate'] | |
| 534 | + min_roi = max(end, start * np.exp(-rate*trade_dur)) | |
| 535 | + else: | |
| 536 | + return None, None | |
| 537 | + # "connect the dots" between the points on the minima_roi table | |
| 538 | + elif roi_type == 'connect': | |
| 539 | + if not minimal_roi: | |
| 540 | + return None, None | |
| 541 | + # figure out where we are in the defined roi table | |
| 542 | + past_roi = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 543 | + next_roi = list(filter(lambda x: x > trade_dur, minimal_roi.keys())) | |
| 544 | + # if we are past the final point in the table, use that key/vaule pair | |
| 545 | + if not past_roi: | |
| 546 | + return None, None | |
| 547 | + current_entry = max(past_roi) | |
| 548 | + if not next_roi: | |
| 549 | + return current_entry, minimal_roi[current_entry] | |
| 550 | + next_entry = min(next_roi) | |
| 551 | + # use the slope-intercept formula between the two points | |
| 552 | + # y = mx + b | |
| 553 | + x1, y1 = current_entry, minimal_roi[current_entry] | |
| 554 | + x2, y2 = next_entry, minimal_roi[next_entry] | |
| 555 | + m = (y1-y2)/(x1-x2) | |
| 556 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 557 | + min_roi = (m * trade_dur) + b | |
| 558 | + else: | |
| 559 | + return None, None | |
| 560 | + | |
| 561 | + return trade_dur, min_roi | |
| 562 | + | |
| 563 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 564 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 565 | + | |
| 566 | + if self.dynamic_roi and 'dynamic_roi_enabled' in self.dynamic_roi \ | |
| 567 | + and self.dynamic_roi['dynamic_roi_enabled']: | |
| 568 | + _, roi = self.min_roi_reached_dynamic(trade_dur) | |
| 569 | + else: | |
| 570 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 571 | + if roi is None: | |
| 572 | + return False | |
| 573 | + else: | |
| 574 | + return current_profit > roi | |
| 575 | + | |
| 576 | + """ | |
| 577 | + Custom Methods for Strategy Parameters, Trade, and Price Data | |
| 578 | + Consider splitting this out into a helper file. | |
| 579 | + """ | |
| 580 | + def populate_trades(self, pair: str) -> dict: | |
| 581 | + """ | |
| 582 | + Query the database and populate the custom_trade_info dict. | |
| 583 | + """ | |
| 584 | + if not pair in self.custom_trade_info: | |
| 585 | + self.custom_trade_info[pair] = {} | |
| 586 | + | |
| 587 | + trade_data = {} | |
| 588 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 589 | + | |
| 590 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 591 | + | |
| 592 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 593 | + | |
| 594 | + if active_trade: | |
| 595 | + current_rate = self.get_current_price(pair, True) | |
| 596 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 597 | + | |
| 598 | + present = arrow.utcnow() | |
| 599 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 600 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 601 | + | |
| 602 | + trade_data['active_trade'] = True | |
| 603 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 604 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 605 | + trade_data['open_minutes'] : int = open_minutes | |
| 606 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) # floor | |
| 607 | + else: | |
| 608 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 609 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 610 | + | |
| 611 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 612 | + | |
| 613 | + if other_trades: | |
| 614 | + trade_data['other_trades'] = True | |
| 615 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 616 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 617 | + if trade_data['current_profit'] < min(other_profit): | |
| 618 | + trade_data['biggest_loser'] = True | |
| 619 | + else: | |
| 620 | + trade_data['avg_other_profit'] = 0 | |
| 621 | + | |
| 622 | + open_trades = len(Trade.get_open_trades()) | |
| 623 | + # this was lazy. | |
| 624 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 625 | + | |
| 626 | + return trade_data | |
| 627 | + | |
| 628 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 629 | + """ | |
| 630 | + Query the exchange for current price information, used in profit calculations. | |
| 631 | + Implements a cache to prevent excessive api calls. | |
| 632 | + """ | |
| 633 | + if not refresh: | |
| 634 | + rate = self.custom_current_price_cache.get(pair) | |
| 635 | + if rate: | |
| 636 | + return rate | |
| 637 | + | |
| 638 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 639 | + if ask_strategy.get('use_order_book', False): | |
| 640 | + ob = self.dp.orderbook(pair, 1) | |
| 641 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 642 | + else: | |
| 643 | + ticker = self.dp.ticker(pair) | |
| 644 | + rate = ticker['last'] | |
| 645 | + | |
| 646 | + self.custom_current_price_cache[pair] = rate | |
| 647 | + return rate | |
| 648 | + | |
| 649 | + def get_pair_params(self, pair: str, side: str) -> Dict: | |
| 650 | + """ | |
| 651 | + Returns buy/sell params that are specific to pairs or groups of pairs if desired. | |
| 652 | + TODO: | |
| 653 | + - Consider adding stoploss and/or ROI tables to the pair/group specific options | |
| 654 | + """ | |
| 655 | + buy_params = self.buy_params | |
| 656 | + sell_params = self.sell_params | |
| 657 | + | |
| 658 | + if self.custom_pair_params: | |
| 659 | + custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 660 | + if custom_params['buy_params']: | |
| 661 | + buy_params = custom_params['buy_params'] | |
| 662 | + if custom_params['sell_params']: | |
| 663 | + sell_params = custom_params['sell_params'] | |
| 664 | + | |
| 665 | + if side == 'sell': | |
| 666 | + return sell_params | |
| 667 | + | |
| 668 | + return buy_params | |
| 669 | + | |
| 670 | +# Sub-strategy with parameters specific to BTC stake | |
| 671 | +class SolipsisMM_BTC(SolipsisMM): | |
| 672 | + | |
| 673 | + timeframe = '1h' | |
| 674 | + inf_timeframe = '4h' | |
| 675 | + | |
| 676 | + buy_params = { | |
| 677 | + 'inf-rsi': 64, | |
| 678 | + 'mp': 55, | |
| 679 | + 'rmi-fast': 31, | |
| 680 | + 'rmi-slow': 16, | |
| 681 | + 'xinf-stake-rmi': 67, | |
| 682 | + 'xtf-fiat-rsi': 17, | |
| 683 | + 'xtf-stake-rsi': 57 | |
| 684 | + } | |
| 685 | + | |
| 686 | + minimal_roi = { | |
| 687 | + "0": 0.05, | |
| 688 | + "240": 0.025, | |
| 689 | + "1440": 0.01, | |
| 690 | + "4320": 0 | |
| 691 | + } | |
| 692 | + | |
| 693 | + stoploss = -0.30 | |
| 694 | + use_custom_stoploss = False | |
| 695 | + | |
| 696 | +# Sub-strategy with parameters specific to ETH stake | |
| 697 | +class SolipsisMM_ETH(SolipsisMM): | |
| 698 | + | |
| 699 | + timeframe = '1h' | |
| 700 | + inf_timeframe = '4h' | |
| 701 | + | |
| 702 | + buy_params = { | |
| 703 | + 'inf-rsi': 13, | |
| 704 | + 'inf-stake-rmi': 69, | |
| 705 | + 'mp': 40, | |
| 706 | + 'rmi-fast': 42, | |
| 707 | + 'rmi-slow': 17, | |
| 708 | + 'tf-fiat-rsi': 15, | |
| 709 | + 'tf-stake-rsi': 92 | |
| 710 | + } | |
| 711 | + | |
| 712 | + minimal_roi = { | |
| 713 | + "0": 0.05, | |
| 714 | + "240": 0.025, | |
| 715 | + "1440": 0.01, | |
| 716 | + "4320": 0 | |
| 717 | + } | |
| 718 | + | |
| 719 | + stoploss = -0.30 | |
| 720 | + use_custom_stoploss = False | |
| No newline at the end of the file |
added strategies/old/Stinkfist.py +414 −0
| @@ -0,0 +1,414 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import technical.indicators as ti | |
| 4 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 5 | +import arrow | |
| 6 | +from freqtrade.strategy.interface import IStrategy | |
| 7 | +from freqtrade.strategy import merge_informative_pair | |
| 8 | +from typing import Dict, List, Optional, Tuple | |
| 9 | +from pandas import DataFrame, Series | |
| 10 | +from functools import reduce | |
| 11 | +from datetime import datetime | |
| 12 | +from freqtrade.persistence import Trade | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | +from collections import namedtuple | |
| 16 | + | |
| 17 | + | |
| 18 | +""" | |
| 19 | +Loosely based on: | |
| 20 | +https://github.com/nicolay-zlobin/jesse-indicators/blob/main/strategies/BadStreak/__init__.py | |
| 21 | + | |
| 22 | +TODO: | |
| 23 | + - Move custom indicators out to helper file or freqtrade/technical? | |
| 24 | + | |
| 25 | +""" | |
| 26 | + | |
| 27 | +class Stinkfist(IStrategy): | |
| 28 | + """ | |
| 29 | + Strategy Configuration Items | |
| 30 | + """ | |
| 31 | + timeframe = '5m' | |
| 32 | + inf_timeframe = '1h' | |
| 33 | + | |
| 34 | + buy_params = { | |
| 35 | + 'inf-pct-adr': 0.80, | |
| 36 | + 'mp': 30 | |
| 37 | + } | |
| 38 | + | |
| 39 | + sell_params = {} | |
| 40 | + | |
| 41 | + minimal_roi = { | |
| 42 | + "0": 0.05, | |
| 43 | + "10": 0.025, | |
| 44 | + "20": 0.015, | |
| 45 | + "30": 0.01, | |
| 46 | + "720": 0.005, | |
| 47 | + "1440": 0 | |
| 48 | + } | |
| 49 | + | |
| 50 | + stoploss = -0.40 | |
| 51 | + | |
| 52 | + # Probably don't change these | |
| 53 | + use_sell_signal = True | |
| 54 | + sell_profit_only = False | |
| 55 | + ignore_roi_if_buy_signal = True | |
| 56 | + | |
| 57 | + startup_candle_count: int = 72 | |
| 58 | + | |
| 59 | + # Custom Dicts for storing trade data and other custom things this strategy does | |
| 60 | + custom_trade_info = {} | |
| 61 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 62 | + | |
| 63 | + """ | |
| 64 | + Informative Pair Definitions | |
| 65 | + """ | |
| 66 | + def informative_pairs(self): | |
| 67 | + pairs = self.dp.current_whitelist() | |
| 68 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 69 | + | |
| 70 | + return informative_pairs | |
| 71 | + | |
| 72 | + """ | |
| 73 | + Indicator Definitions | |
| 74 | + """ | |
| 75 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 76 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 77 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 78 | + | |
| 79 | + # Set up primary indicators | |
| 80 | + dataframe['rmi-slow'] = ti.RMI(dataframe, length=21, mom=5) | |
| 81 | + dataframe['rmi-fast'] = ti.RMI(dataframe, length=8, mom=4) | |
| 82 | + | |
| 83 | + # MA Streak | |
| 84 | + dataframe['mac'] = self.mac(dataframe, 20, 50) | |
| 85 | + dataframe['streak'] = self.ma_streak(dataframe, period=4) | |
| 86 | + | |
| 87 | + streak = abs(int(dataframe['streak'].iloc[-1])) | |
| 88 | + streak_back_close = dataframe['close'].shift(streak + 1) | |
| 89 | + | |
| 90 | + dataframe['streak-roc'] = 100 * (dataframe['close'] - streak_back_close) / streak_back_close | |
| 91 | + | |
| 92 | + # Percent Change Channel | |
| 93 | + pcc = self.pcc(dataframe, period=20, mult=2) | |
| 94 | + dataframe['pcc-lowerband'] = pcc.lowerband | |
| 95 | + | |
| 96 | + # Momentum Pinball | |
| 97 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=1) | |
| 98 | + dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=3) | |
| 99 | + | |
| 100 | + # Trend Calculations | |
| 101 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 102 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 103 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 104 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 105 | + | |
| 106 | + # Informative indicators for current pair on inf_timeframe | |
| 107 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 108 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 109 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 110 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 111 | + | |
| 112 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 113 | + | |
| 114 | + return dataframe | |
| 115 | + | |
| 116 | + """ | |
| 117 | + Buy Trigger Signals | |
| 118 | + """ | |
| 119 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 120 | + params = self.buy_params | |
| 121 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 122 | + conditions = [] | |
| 123 | + | |
| 124 | + if trade_data['active_trade']: | |
| 125 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 126 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 300)) | |
| 127 | + | |
| 128 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 129 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 130 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 131 | + | |
| 132 | + else: | |
| 133 | + # Primary buy triggers | |
| 134 | + conditions.append( | |
| 135 | + # informative timeframe conditions | |
| 136 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + (params['inf-pct-adr'] * dataframe[f"adr_{self.inf_timeframe}"])) & | |
| 137 | + # default timeframe conditions | |
| 138 | + (dataframe['mp'] < params['mp']) & | |
| 139 | + (dataframe['streak-roc'] > dataframe['pcc-lowerband']) & | |
| 140 | + (dataframe['mac'] == 1) | |
| 141 | + ) | |
| 142 | + | |
| 143 | + # Anything below here applies to persisting and new buy signal | |
| 144 | + conditions.append(dataframe['volume'].gt(0)) | |
| 145 | + | |
| 146 | + if conditions: | |
| 147 | + dataframe.loc[ | |
| 148 | + reduce(lambda x, y: x & y, conditions), | |
| 149 | + 'buy'] = 1 | |
| 150 | + | |
| 151 | + return dataframe | |
| 152 | + | |
| 153 | + """ | |
| 154 | + Sell Trigger Signals | |
| 155 | + """ | |
| 156 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 157 | + params = self.sell_params | |
| 158 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 159 | + conditions = [] | |
| 160 | + | |
| 161 | + if trade_data['active_trade']: | |
| 162 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 163 | + | |
| 164 | + conditions.append( | |
| 165 | + (trade_data['current_profit'] < loss_cutoff) & | |
| 166 | + (trade_data['current_profit'] > self.stoploss) & | |
| 167 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 168 | + (dataframe['volume'].gt(0)) | |
| 169 | + ) | |
| 170 | + if trade_data['peak_profit'] > 0: | |
| 171 | + conditions.append(dataframe['rmi-slow'] < 50) | |
| 172 | + else: | |
| 173 | + conditions.append(dataframe['rmi-slow'] < 10) | |
| 174 | + | |
| 175 | + if trade_data['other_trades']: | |
| 176 | + if trade_data['free_slots'] > 0: | |
| 177 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 178 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 179 | + else: | |
| 180 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 181 | + | |
| 182 | + else: | |
| 183 | + conditions.append(dataframe['volume'].lt(0)) | |
| 184 | + | |
| 185 | + if conditions: | |
| 186 | + dataframe.loc[ | |
| 187 | + reduce(lambda x, y: x & y, conditions), | |
| 188 | + 'sell'] = 1 | |
| 189 | + | |
| 190 | + return dataframe | |
| 191 | + | |
| 192 | + """ | |
| 193 | + Super Legit Custom Methods | |
| 194 | + """ | |
| 195 | + def populate_trades(self, pair: str) -> dict: | |
| 196 | + if not pair in self.custom_trade_info: | |
| 197 | + self.custom_trade_info[pair] = {} | |
| 198 | + | |
| 199 | + trade_data = {} | |
| 200 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 201 | + self.custom_trade_info['meta'] = {} | |
| 202 | + | |
| 203 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 204 | + | |
| 205 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 206 | + | |
| 207 | + if active_trade: | |
| 208 | + current_rate = self.get_current_price(pair, True) | |
| 209 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 210 | + | |
| 211 | + present = arrow.utcnow() | |
| 212 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 213 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 214 | + | |
| 215 | + trade_data['active_trade'] = True | |
| 216 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 217 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 218 | + trade_data['open_minutes'] : int = open_minutes | |
| 219 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 220 | + else: | |
| 221 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 222 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 223 | + | |
| 224 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 225 | + | |
| 226 | + if other_trades: | |
| 227 | + trade_data['other_trades'] = True | |
| 228 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 229 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 230 | + if trade_data['current_profit'] < min(other_profit): | |
| 231 | + trade_data['biggest_loser'] = True | |
| 232 | + else: | |
| 233 | + trade_data['avg_other_profit'] = 0 | |
| 234 | + | |
| 235 | + open_trades = len(Trade.get_open_trades()) | |
| 236 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 237 | + | |
| 238 | + return trade_data | |
| 239 | + | |
| 240 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 241 | + if not refresh: | |
| 242 | + rate = self.custom_current_price_cache.get(pair) | |
| 243 | + if rate: | |
| 244 | + return rate | |
| 245 | + | |
| 246 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 247 | + if ask_strategy.get('use_order_book', False): | |
| 248 | + ob = self.dp.orderbook(pair, 1) | |
| 249 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 250 | + else: | |
| 251 | + ticker = self.dp.ticker(pair) | |
| 252 | + rate = ticker['last'] | |
| 253 | + | |
| 254 | + self.custom_current_price_cache[pair] = rate | |
| 255 | + return rate | |
| 256 | + | |
| 257 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 258 | + time = max(0, trade_time - start_time) | |
| 259 | + rate = (end - start) / (end_time - start_time) | |
| 260 | + return min(end, start + (rate * trade_time)) | |
| 261 | + | |
| 262 | + | |
| 263 | + """ | |
| 264 | + Custom Indicators | |
| 265 | + """ | |
| 266 | + | |
| 267 | + """ | |
| 268 | + Moving Average Cross | |
| 269 | + Port of: https://www.tradingview.com/script/PcWAuplI-Moving-Average-Cross/ | |
| 270 | + """ | |
| 271 | + def mac(self, dataframe: DataFrame, fast: int = 20, slow: int = 50) -> Series: | |
| 272 | + | |
| 273 | + dataframe = dataframe.copy() | |
| 274 | + | |
| 275 | + # Fast MAs | |
| 276 | + upper_fast = ta.EMA(dataframe['high'], timeperiod=fast) | |
| 277 | + lower_fast = ta.EMA(dataframe['low'], timeperiod=fast) | |
| 278 | + | |
| 279 | + # Slow MAs | |
| 280 | + upper_slow = ta.EMA(dataframe['high'], timeperiod=slow) | |
| 281 | + lower_slow = ta.EMA(dataframe['low'], timeperiod=slow) | |
| 282 | + | |
| 283 | + # Crosses | |
| 284 | + crosses_lf_us = qtpylib.crossed_above(lower_fast, upper_slow) | qtpylib.crossed_below(lower_fast, upper_slow) | |
| 285 | + crosses_uf_ls = qtpylib.crossed_above(upper_fast, lower_slow) | qtpylib.crossed_below(upper_fast, lower_slow) | |
| 286 | + | |
| 287 | + dir_1 = np.where(crosses_lf_us, 1, np.nan) | |
| 288 | + dir_2 = np.where(crosses_uf_ls, -1, np.nan) | |
| 289 | + | |
| 290 | + dir = np.where(dir_1 == 1, dir_1, np.nan) | |
| 291 | + dir = np.where(dir_2 == -1, dir_2, dir_1) | |
| 292 | + | |
| 293 | + res = Series(dir).fillna(method='ffill').to_numpy() | |
| 294 | + | |
| 295 | + return res | |
| 296 | + | |
| 297 | + """ | |
| 298 | + MA Streak | |
| 299 | + Port of: https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/ | |
| 300 | + """ | |
| 301 | + def ma_streak(self, dataframe: DataFrame, period: int = 4, source_type='close') -> Series: | |
| 302 | + | |
| 303 | + dataframe = dataframe.copy() | |
| 304 | + | |
| 305 | + avgval = self.zlema(dataframe[source_type], period) | |
| 306 | + | |
| 307 | + arr = np.diff(avgval) | |
| 308 | + pos = np.clip(arr, 0, 1).astype(bool).cumsum() | |
| 309 | + neg = np.clip(arr, -1, 0).astype(bool).cumsum() | |
| 310 | + streak = np.where(arr >= 0, pos - np.maximum.accumulate(np.where(arr <= 0, pos, 0)), | |
| 311 | + -neg + np.maximum.accumulate(np.where(arr >= 0, neg, 0))) | |
| 312 | + | |
| 313 | + res = np.concatenate((np.full((dataframe.shape[0] - streak.shape[0]), np.nan), streak)) | |
| 314 | + | |
| 315 | + return res | |
| 316 | + | |
| 317 | + """ | |
| 318 | + Percent Change Channel | |
| 319 | + PCC is like KC unless it uses percentage changes in price to set channel distance. | |
| 320 | + https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/ | |
| 321 | + """ | |
| 322 | + def pcc(self, dataframe: DataFrame, period: int = 20, mult: int = 2): | |
| 323 | + | |
| 324 | + PercentChangeChannel = namedtuple('PercentChangeChannel', ['upperband', 'middleband', 'lowerband']) | |
| 325 | + | |
| 326 | + dataframe = dataframe.copy() | |
| 327 | + | |
| 328 | + close = dataframe['close'] | |
| 329 | + previous_close = close.shift() | |
| 330 | + low = dataframe['low'] | |
| 331 | + high = dataframe['high'] | |
| 332 | + | |
| 333 | + close_change = (close - previous_close) / previous_close * 100 | |
| 334 | + high_change = (high - close) / close * 100 | |
| 335 | + low_change = (low - close) / close * 100 | |
| 336 | + | |
| 337 | + mid = self.zlema(close_change, period) | |
| 338 | + rangema = self.zlema(high_change - low_change, period) | |
| 339 | + | |
| 340 | + upper = mid + rangema * mult | |
| 341 | + lower = mid - rangema * mult | |
| 342 | + | |
| 343 | + return PercentChangeChannel(upper, rangema, lower) | |
| 344 | + | |
| 345 | + def zlema(self, series: Series, period): | |
| 346 | + ema1 = ta.EMA(series, period) | |
| 347 | + ema2 = ta.EMA(ema1, period) | |
| 348 | + d = ema1 - ema2 | |
| 349 | + zlema = ema1 + d | |
| 350 | + return zlema | |
| 351 | + | |
| 352 | + """ | |
| 353 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 354 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 355 | + """ | |
| 356 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 357 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 358 | + ob = self.dp.orderbook(pair, 1) | |
| 359 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 360 | + if current_price > order['price'] * 1.01: | |
| 361 | + return True | |
| 362 | + return False | |
| 363 | + | |
| 364 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 365 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 366 | + ob = self.dp.orderbook(pair, 1) | |
| 367 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 368 | + if current_price < order['price'] * 0.99: | |
| 369 | + return True | |
| 370 | + return False | |
| 371 | + | |
| 372 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 373 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 374 | + ob = self.dp.orderbook(pair, 1) | |
| 375 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 376 | + if current_price > rate * 1.01: | |
| 377 | + return False | |
| 378 | + return True | |
| 379 | + | |
| 380 | + | |
| 381 | +""" | |
| 382 | +Sub-strategy overrides | |
| 383 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 384 | +""" | |
| 385 | +# Sub-strategy with parameters specific to BTC stake | |
| 386 | +class Stinkfist_BTC(Stinkfist): | |
| 387 | + | |
| 388 | + timeframe = '5m' | |
| 389 | + inf_timeframe = '1h' | |
| 390 | + | |
| 391 | + buy_params = { | |
| 392 | + 'inf-pct-adr': 0.91556, | |
| 393 | + 'mp': 66, | |
| 394 | + } | |
| 395 | + | |
| 396 | + use_sell_signal = False | |
| 397 | + | |
| 398 | +# Sub-strategy with parameters specific to ETH stake | |
| 399 | +class Stinkfist_ETH(Stinkfist): | |
| 400 | + | |
| 401 | + timeframe = '5m' | |
| 402 | + inf_timeframe = '1h' | |
| 403 | + | |
| 404 | + buy_params = { | |
| 405 | + 'inf-pct-adr': 0.81628, | |
| 406 | + 'mp': 40, | |
| 407 | + } | |
| 408 | + | |
| 409 | + trailing_stop = True | |
| 410 | + trailing_stop_positive = 0.014 | |
| 411 | + trailing_stop_positive_offset = 0.022 | |
| 412 | + trailing_only_offset_is_reached = False | |
| 413 | + | |
| 414 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/StochRSITEMA.py +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | + | |
| 3 | +# --- Do not remove these libs --- | |
| 4 | +from functools import reduce | |
| 5 | +import numpy as np # noqa | |
| 6 | +import pandas as pd # noqa | |
| 7 | +from pandas import DataFrame | |
| 8 | + | |
| 9 | +from freqtrade.strategy import IStrategy | |
| 10 | + | |
| 11 | +# -------------------------------- | |
| 12 | +# Add your lib to import here | |
| 13 | +import talib.abstract as ta | |
| 14 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 15 | + | |
| 16 | + | |
| 17 | +class StochRSITEMA(IStrategy): | |
| 18 | + """ | |
| 19 | + author@: werkkrew | |
| 20 | + github@: https://github.com/werkkrew/freqtrade-strategies | |
| 21 | + | |
| 22 | + Reference: Strategy #1 @ https://tradingsim.com/blog/5-minute-bar/ | |
| 23 | + | |
| 24 | + Trade entry signals are generated when the stochastic oscillator and relative strength index provide confirming signals. | |
| 25 | + | |
| 26 | + Buy: | |
| 27 | + - Stoch slowd and slowk below lower band and cross above | |
| 28 | + - Stoch slowk above slowd | |
| 29 | + - RSI below lower band and crosses above | |
| 30 | + | |
| 31 | + You should exit the trade once the price closes beyond the TEMA in the opposite direction of the primary trend. | |
| 32 | + There are many cases when candles are move partially beyond the TEMA line. We disregard such exit points and we exit the market when the price fully breaks the TEMA. | |
| 33 | + | |
| 34 | + Sell: | |
| 35 | + - Candle closes below TEMA line (or open+close or average of open/close) | |
| 36 | + - ROI, Stoploss, Trailing Stop | |
| 37 | + """ | |
| 38 | + | |
| 39 | + # Strategy interface version - allow new iterations of the strategy interface. | |
| 40 | + # Check the documentation or the Sample strategy to get the latest version. | |
| 41 | + INTERFACE_VERSION = 2 | |
| 42 | + | |
| 43 | + """ | |
| 44 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 45 | + """ | |
| 46 | + | |
| 47 | + # 47/50: 19 trades. 7/6/6 Wins/Draws/Losses. Avg profit -0.35%. Median profit 0.00%. Total profit -0.00006706 BTC ( -6.69Σ%). Avg duration 80.3 min. Objective: 1.98291 | |
| 48 | + | |
| 49 | + # Buy hyperspace params: | |
| 50 | + buy_params = { | |
| 51 | + 'rsi-lower-band': 36, 'rsi-period': 15, 'stoch-lower-band': 48 | |
| 52 | + } | |
| 53 | + | |
| 54 | + # Sell hyperspace params: | |
| 55 | + sell_params = { | |
| 56 | + 'tema-period': 5, 'tema-trigger': 'close' | |
| 57 | + } | |
| 58 | + | |
| 59 | + # ROI table: | |
| 60 | + minimal_roi = { | |
| 61 | + "0": 0.19503, | |
| 62 | + "13": 0.09149, | |
| 63 | + "36": 0.02891, | |
| 64 | + "64": 0 | |
| 65 | + } | |
| 66 | + | |
| 67 | + # Stoploss: | |
| 68 | + stoploss = -0.02205 | |
| 69 | + | |
| 70 | + # Trailing stop: | |
| 71 | + trailing_stop = True | |
| 72 | + trailing_stop_positive = 0.17251 | |
| 73 | + trailing_stop_positive_offset = 0.2516 | |
| 74 | + trailing_only_offset_is_reached = False | |
| 75 | + | |
| 76 | + | |
| 77 | + """ | |
| 78 | + END HYPEROPT | |
| 79 | + """ | |
| 80 | + | |
| 81 | + # Ranges for dynamic indicator periods | |
| 82 | + rsiStart = 5 | |
| 83 | + rsiEnd = 30 | |
| 84 | + temaStart = 5 | |
| 85 | + temaEnd = 50 | |
| 86 | + | |
| 87 | + # Stochastic Params | |
| 88 | + fastkPeriod = 14 | |
| 89 | + slowkPeriod = 3 | |
| 90 | + slowdPeriod = 3 | |
| 91 | + | |
| 92 | + # Make sure these match or are not overridden in config | |
| 93 | + use_sell_signal = True | |
| 94 | + sell_profit_only = True | |
| 95 | + sell_profit_offset = 0.01 | |
| 96 | + ignore_roi_if_buy_signal = False | |
| 97 | + | |
| 98 | + timeframe = '5m' | |
| 99 | + | |
| 100 | + # Run "populate_indicators()" only for new candle. | |
| 101 | + process_only_new_candles = False | |
| 102 | + | |
| 103 | + # Number of candles the strategy requires before producing valid signals | |
| 104 | + # Set this to the highest period value in the indicator_params dict or highest of the ranges in the hyperopt settings (default: 72) | |
| 105 | + startup_candle_count: int = 50 | |
| 106 | + | |
| 107 | + """ | |
| 108 | + Populate all of the indicators we need (note: indicators are separate for buy/sell) | |
| 109 | + """ | |
| 110 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 111 | + | |
| 112 | + for rsip in range(self.rsiStart, (self.rsiEnd + 1)): | |
| 113 | + dataframe[f'rsi({rsip})'] = ta.RSI(dataframe, timeperiod=rsip) | |
| 114 | + | |
| 115 | + for temap in range(self.temaStart, (self.temaEnd + 1)): | |
| 116 | + dataframe[f'tema({temap})'] = ta.TEMA(dataframe, timeperiod=temap) | |
| 117 | + | |
| 118 | + # Stochastic Slow | |
| 119 | + # fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) | |
| 120 | + stoch_slow = ta.STOCH(dataframe, fastk_period=self.fastkPeriod, | |
| 121 | + slowk_period=self.slowkPeriod, slowd_period=self.slowdPeriod) | |
| 122 | + dataframe['stoch-slowk'] = stoch_slow['slowk'] | |
| 123 | + dataframe['stoch-slowd'] = stoch_slow['slowd'] | |
| 124 | + | |
| 125 | + return dataframe | |
| 126 | + | |
| 127 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 128 | + params = self.buy_params | |
| 129 | + | |
| 130 | + conditions = [] | |
| 131 | + | |
| 132 | + conditions.append( | |
| 133 | + dataframe[f"rsi({params['rsi-period']})"] > params['rsi-lower-band']) | |
| 134 | + conditions.append(qtpylib.crossed_above( | |
| 135 | + dataframe['stoch-slowd'], params['stoch-lower-band'])) | |
| 136 | + conditions.append(qtpylib.crossed_above( | |
| 137 | + dataframe['stoch-slowk'], params['stoch-lower-band'])) | |
| 138 | + conditions.append(qtpylib.crossed_above( | |
| 139 | + dataframe['stoch-slowk'], dataframe['stoch-slowd'])) | |
| 140 | + | |
| 141 | + # Check that the candle had volume | |
| 142 | + conditions.append(dataframe['volume'] > 0) | |
| 143 | + | |
| 144 | + if conditions: | |
| 145 | + dataframe.loc[ | |
| 146 | + reduce(lambda x, y: x & y, conditions), | |
| 147 | + 'buy'] = 1 | |
| 148 | + | |
| 149 | + return dataframe | |
| 150 | + | |
| 151 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 152 | + params = self.sell_params | |
| 153 | + | |
| 154 | + conditions = [] | |
| 155 | + | |
| 156 | + if params.get('tema-trigger') == 'close': | |
| 157 | + conditions.append( | |
| 158 | + dataframe['close'] < dataframe[f"tema({params['tema-period']})"]) | |
| 159 | + if params.get('tema-trigger') == 'both': | |
| 160 | + conditions.append((dataframe['close'] < dataframe[f"tema({params['tema-period']})"]) & ( | |
| 161 | + dataframe['open'] < dataframe[f"tema({params['tema-period']})"])) | |
| 162 | + if params.get('tema-trigger') == 'average': | |
| 163 | + conditions.append( | |
| 164 | + ((dataframe['close'] + dataframe['open']) / 2) < dataframe[f"tema({params['tema-period']})"]) | |
| 165 | + | |
| 166 | + # Check that the candle had volume | |
| 167 | + conditions.append(dataframe['volume'] > 0) | |
| 168 | + | |
| 169 | + if conditions: | |
| 170 | + dataframe.loc[ | |
| 171 | + reduce(lambda x, y: x & y, conditions), | |
| 172 | + 'sell'] = 1 | |
| 173 | + | |
| 174 | + return dataframe |
added strategies/old/SuperHV27.py +408 −0
| @@ -0,0 +1,408 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | +from typing import Dict, List, NamedTuple, Optional, Tuple | |
| 6 | +from freqtrade.strategy.interface import IStrategy | |
| 7 | +from freqtrade.strategy import merge_informative_pair | |
| 8 | +from pandas import DataFrame, Series | |
| 9 | +from functools import reduce | |
| 10 | +from datetime import datetime | |
| 11 | +from freqtrade.persistence import Trade | |
| 12 | +from technical.indicators import RMI | |
| 13 | +from statistics import mean | |
| 14 | +from cachetools import TTLCache | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | +class SuperHV27(IStrategy): | |
| 19 | + | |
| 20 | + timeframe = '5m' | |
| 21 | + | |
| 22 | + # Buy hyperspace params: | |
| 23 | + buy_params = { | |
| 24 | + 'adx1': 49, | |
| 25 | + 'adx2': 36, | |
| 26 | + 'adx3': 32, | |
| 27 | + 'adx4': 24, | |
| 28 | + 'emarsi1': 43, | |
| 29 | + 'emarsi2': 27, | |
| 30 | + 'emarsi3': 26, | |
| 31 | + 'emarsi4': 50 | |
| 32 | + } | |
| 33 | + | |
| 34 | + # Sell hyperspace params: | |
| 35 | + sell_params = { | |
| 36 | + 'adx2': 36, 'emarsi1': 43, 'emarsi2': 27, 'emarsi3': 26 | |
| 37 | + } | |
| 38 | + | |
| 39 | + # ROI table: | |
| 40 | + minimal_roi = { | |
| 41 | + "0": 0.10, | |
| 42 | + "30": 0.05, | |
| 43 | + "40": 0.025, | |
| 44 | + "60": 0.015, | |
| 45 | + "720": 0.01, | |
| 46 | + "1440": 0 | |
| 47 | + } | |
| 48 | + | |
| 49 | + # Stoploss: | |
| 50 | + stoploss = -0.40 | |
| 51 | + | |
| 52 | + # connect will participate in hyperopted tables, other methods will not | |
| 53 | + dynamic_roi = { | |
| 54 | + 'enabled': True, | |
| 55 | + 'type': 'connect', # linear, exponential, or connect | |
| 56 | + 'decay-rate': 0.015, # bigger is faster, recommended to graph f(t) = start-pct * e(-rate*t) | |
| 57 | + 'decay-time': 1440, # amount of time to reach zero, only relevant for linear decay | |
| 58 | + 'start': 0.10, # starting percentage | |
| 59 | + 'end': 0, # ending percentage | |
| 60 | + } | |
| 61 | + | |
| 62 | + # Probably don't change these | |
| 63 | + use_sell_signal = True | |
| 64 | + sell_profit_only = False | |
| 65 | + ignore_roi_if_buy_signal = True | |
| 66 | + | |
| 67 | + # Custom Dicts for storing trade data and other custom things this strategy does | |
| 68 | + custom_trade_info = {} | |
| 69 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 70 | + | |
| 71 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 72 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 73 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 74 | + | |
| 75 | + dataframe['rsi'] = np.nan_to_num(ta.RSI(dataframe, timeperiod=5)) | |
| 76 | + dataframe['emarsi'] = np.nan_to_num(ta.EMA(dataframe['rsi'], timeperiod=5)) | |
| 77 | + | |
| 78 | + dataframe['adx'] = np.nan_to_num(ta.ADX(dataframe)) | |
| 79 | + | |
| 80 | + dataframe['minusdi'] = np.nan_to_num(ta.MINUS_DI(dataframe)) | |
| 81 | + dataframe['minusdiema'] = np.nan_to_num(ta.EMA(dataframe['minusdi'], timeperiod=25)) | |
| 82 | + dataframe['plusdi'] = np.nan_to_num(ta.PLUS_DI(dataframe)) | |
| 83 | + dataframe['plusdiema'] = np.nan_to_num(ta.EMA(dataframe['plusdi'], timeperiod=5)) | |
| 84 | + | |
| 85 | + dataframe['lowsma'] = np.nan_to_num(ta.EMA(dataframe, timeperiod=60)) | |
| 86 | + dataframe['highsma'] = np.nan_to_num(ta.EMA(dataframe, timeperiod=120)) | |
| 87 | + dataframe['fastsma'] = np.nan_to_num(ta.SMA(dataframe, timeperiod=120)) | |
| 88 | + dataframe['slowsma'] = np.nan_to_num(ta.SMA(dataframe, timeperiod=240)) | |
| 89 | + | |
| 90 | + dataframe['bigup'] = dataframe['fastsma'].gt(dataframe['slowsma']) & ((dataframe['fastsma'] - dataframe['slowsma']) > dataframe['close'] / 300) | |
| 91 | + dataframe['bigdown'] = ~dataframe['bigup'] | |
| 92 | + dataframe['trend'] = dataframe['fastsma'] - dataframe['slowsma'] | |
| 93 | + | |
| 94 | + dataframe['preparechangetrend'] = dataframe['trend'].gt(dataframe['trend'].shift()) | |
| 95 | + dataframe['preparechangetrendconfirm'] = dataframe['preparechangetrend'] & dataframe['trend'].shift().gt(dataframe['trend'].shift(2)) | |
| 96 | + dataframe['continueup'] = dataframe['slowsma'].gt(dataframe['slowsma'].shift()) & dataframe['slowsma'].shift().gt(dataframe['slowsma'].shift(2)) | |
| 97 | + | |
| 98 | + dataframe['delta'] = dataframe['fastsma'] - dataframe['fastsma'].shift() | |
| 99 | + dataframe['slowingdown'] = dataframe['delta'].lt(dataframe['delta'].shift()) | |
| 100 | + | |
| 101 | + dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) | |
| 102 | + dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) | |
| 103 | + | |
| 104 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 105 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 106 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 107 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 108 | + | |
| 109 | + return dataframe | |
| 110 | + | |
| 111 | + | |
| 112 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 113 | + params = self.buy_params | |
| 114 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 115 | + conditions = [] | |
| 116 | + | |
| 117 | + if trade_data['active_trade']: | |
| 118 | + profit_factor = (1 - (dataframe['rmi-slow'].iloc[-1] / 400)) | |
| 119 | + rmi_grow = self.linear_growth(30, 70, 180, 720, trade_data['open_minutes']) | |
| 120 | + | |
| 121 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 122 | + conditions.append(trade_data['current_profit'] > (trade_data['peak_profit'] * profit_factor)) | |
| 123 | + conditions.append(dataframe['rmi-slow'] >= rmi_grow) | |
| 124 | + | |
| 125 | + else: | |
| 126 | + # Standard BinHV27 Buy Conditions | |
| 127 | + conditions.append( | |
| 128 | + dataframe['slowsma'].gt(0) & | |
| 129 | + dataframe['close'].lt(dataframe['highsma']) & | |
| 130 | + dataframe['close'].lt(dataframe['lowsma']) & | |
| 131 | + dataframe['minusdi'].gt(dataframe['minusdiema']) & | |
| 132 | + dataframe['rsi'].ge(dataframe['rsi'].shift()) & | |
| 133 | + ( | |
| 134 | + ( | |
| 135 | + ~dataframe['preparechangetrend'] & | |
| 136 | + ~dataframe['continueup'] & | |
| 137 | + dataframe['adx'].gt(params['adx1']) & | |
| 138 | + dataframe['bigdown'] & | |
| 139 | + dataframe['emarsi'].le(params['emarsi1']) | |
| 140 | + ) | | |
| 141 | + ( | |
| 142 | + ~dataframe['preparechangetrend'] & | |
| 143 | + dataframe['continueup'] & | |
| 144 | + dataframe['adx'].gt(params['adx2']) & | |
| 145 | + dataframe['bigdown'] & | |
| 146 | + dataframe['emarsi'].le(params['emarsi2']) | |
| 147 | + ) | | |
| 148 | + ( | |
| 149 | + ~dataframe['continueup'] & | |
| 150 | + dataframe['adx'].gt(params['adx3']) & | |
| 151 | + dataframe['bigup'] & | |
| 152 | + dataframe['emarsi'].le(params['emarsi3']) | |
| 153 | + ) | | |
| 154 | + ( | |
| 155 | + dataframe['continueup'] & | |
| 156 | + dataframe['adx'].gt(params['adx4']) & | |
| 157 | + dataframe['bigup'] & | |
| 158 | + dataframe['emarsi'].le(params['emarsi4']) | |
| 159 | + ) | |
| 160 | + ) | |
| 161 | + ) | |
| 162 | + | |
| 163 | + conditions.append(dataframe['volume'].gt(0)) | |
| 164 | + | |
| 165 | + if conditions: | |
| 166 | + dataframe.loc[ | |
| 167 | + reduce(lambda x, y: x & y, conditions), | |
| 168 | + 'buy'] = 1 | |
| 169 | + | |
| 170 | + return dataframe | |
| 171 | + | |
| 172 | + | |
| 173 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 174 | + params = self.sell_params | |
| 175 | + trade_data = self.custom_trade_info[metadata['pair']] | |
| 176 | + conditions = [] | |
| 177 | + | |
| 178 | + # Standard BinHV27 Sell Conditions | |
| 179 | + conditions.append( | |
| 180 | + ( | |
| 181 | + ( | |
| 182 | + ~dataframe['preparechangetrendconfirm'] & | |
| 183 | + ~dataframe['continueup'] & | |
| 184 | + (dataframe['close'].gt(dataframe['lowsma']) | dataframe['close'].gt(dataframe['highsma'])) & | |
| 185 | + dataframe['highsma'].gt(0) & | |
| 186 | + dataframe['bigdown'] | |
| 187 | + ) | | |
| 188 | + ( | |
| 189 | + ~dataframe['preparechangetrendconfirm'] & | |
| 190 | + ~dataframe['continueup'] & | |
| 191 | + dataframe['close'].gt(dataframe['highsma']) & | |
| 192 | + dataframe['highsma'].gt(0) & | |
| 193 | + (dataframe['emarsi'].ge(params['emarsi1']) | dataframe['close'].gt(dataframe['slowsma'])) & | |
| 194 | + dataframe['bigdown'] | |
| 195 | + ) | | |
| 196 | + ( | |
| 197 | + ~dataframe['preparechangetrendconfirm'] & | |
| 198 | + dataframe['close'].gt(dataframe['highsma']) & | |
| 199 | + dataframe['highsma'].gt(0) & | |
| 200 | + dataframe['adx'].gt(params['adx2']) & | |
| 201 | + dataframe['emarsi'].ge(params['emarsi2']) & | |
| 202 | + dataframe['bigup'] | |
| 203 | + ) | | |
| 204 | + ( | |
| 205 | + dataframe['preparechangetrendconfirm'] & | |
| 206 | + ~dataframe['continueup'] & | |
| 207 | + dataframe['slowingdown'] & | |
| 208 | + dataframe['emarsi'].ge(params['emarsi3']) & | |
| 209 | + dataframe['slowsma'].gt(0) | |
| 210 | + ) | | |
| 211 | + ( | |
| 212 | + dataframe['preparechangetrendconfirm'] & | |
| 213 | + dataframe['minusdi'].lt(dataframe['plusdi']) & | |
| 214 | + dataframe['close'].gt(dataframe['lowsma']) & | |
| 215 | + dataframe['slowsma'].gt(0) | |
| 216 | + ) | |
| 217 | + ) | |
| 218 | + ) | |
| 219 | + | |
| 220 | + if trade_data['active_trade']: | |
| 221 | + loss_cutoff = self.linear_growth(-0.03, 0, 0, 300, trade_data['open_minutes']) | |
| 222 | + | |
| 223 | + conditions.append(trade_data['current_profit'] < loss_cutoff) | |
| 224 | + | |
| 225 | + if trade_data['other_trades']: | |
| 226 | + if trade_data['free_slots'] > 0: | |
| 227 | + hold_pct = (trade_data['free_slots'] / 100) * -1 | |
| 228 | + conditions.append(trade_data['avg_other_profit'] >= hold_pct) | |
| 229 | + else: | |
| 230 | + conditions.append(trade_data['biggest_loser'] == True) | |
| 231 | + | |
| 232 | + if conditions: | |
| 233 | + dataframe.loc[ | |
| 234 | + reduce(lambda x, y: x & y, conditions), | |
| 235 | + 'sell'] = 1 | |
| 236 | + | |
| 237 | + return dataframe | |
| 238 | + | |
| 239 | + """ | |
| 240 | + Override for default Freqtrade ROI table functionality | |
| 241 | + """ | |
| 242 | + def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 243 | + dynamic_roi = self.dynamic_roi | |
| 244 | + | |
| 245 | + # if the dynamic_roi dict is defined and enabled, do it, otherwise fallback to default functionality | |
| 246 | + if dynamic_roi and dynamic_roi['enabled']: | |
| 247 | + # linear decay: f(t) = start - (rate * t) | |
| 248 | + if dynamic_roi['type'] == 'linear': | |
| 249 | + rate = (dynamic_roi['start'] - dynamic_roi['end']) / dynamic_roi['decay-time'] | |
| 250 | + min_roi = max(dynamic_roi['end'], dynamic_roi['start'] - (rate * trade_dur)) | |
| 251 | + # exponential decay: f(t) = start * e^(-rate*t) | |
| 252 | + elif dynamic_roi['type'] == 'exponential': | |
| 253 | + min_roi = max(dynamic_roi['end'], dynamic_roi['start'] * np.exp(-dynamic_roi['decay-rate']*trade_dur)) | |
| 254 | + elif dynamic_roi['type'] == 'connect': | |
| 255 | + # connect the points in the defined table with lines | |
| 256 | + past_roi = list(filter(lambda x: x <= trade_dur, self.minimal_roi.keys())) | |
| 257 | + next_roi = list(filter(lambda x: x > trade_dur, self.minimal_roi.keys())) | |
| 258 | + if not past_roi: | |
| 259 | + return None, None | |
| 260 | + current_entry = max(past_roi) | |
| 261 | + # next entry | |
| 262 | + if not next_roi: | |
| 263 | + return current_entry, self.minimal_roi[current_entry] | |
| 264 | + # use the slope-intercept formula between the two points in the roi table we are between | |
| 265 | + else: | |
| 266 | + next_entry = min(next_roi) | |
| 267 | + # y = mx + b | |
| 268 | + x1 = current_entry | |
| 269 | + x2 = next_entry | |
| 270 | + y1 = self.minimal_roi[current_entry] | |
| 271 | + y2 = self.minimal_roi[next_entry] | |
| 272 | + m = (y1-y2)/(x1-x2) | |
| 273 | + b = (x1*y2 - x2*y1)/(x1-x2) | |
| 274 | + min_roi = (m * trade_dur) + b | |
| 275 | + else: | |
| 276 | + min_roi = 0 | |
| 277 | + | |
| 278 | + return trade_dur, min_roi | |
| 279 | + # use the standard ROI table | |
| 280 | + else: | |
| 281 | + # Get highest entry in ROI dict where key <= trade-duration | |
| 282 | + roi_list = list(filter(lambda x: x <= trade_dur, self.minimal_roi.keys())) | |
| 283 | + if not roi_list: | |
| 284 | + return None, None | |
| 285 | + roi_entry = max(roi_list) | |
| 286 | + return roi_entry, self.minimal_roi[roi_entry] | |
| 287 | + | |
| 288 | + """ | |
| 289 | + Super Legit Custom Methods | |
| 290 | + """ | |
| 291 | + def populate_trades(self, pair: str) -> dict: | |
| 292 | + if not pair in self.custom_trade_info: | |
| 293 | + self.custom_trade_info[pair] = {} | |
| 294 | + | |
| 295 | + trade_data = {} | |
| 296 | + trade_data['active_trade'] = trade_data['other_trades'] = trade_data['biggest_loser'] = False | |
| 297 | + self.custom_trade_info['meta'] = {} | |
| 298 | + | |
| 299 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 300 | + | |
| 301 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 302 | + | |
| 303 | + if active_trade: | |
| 304 | + current_rate = self.get_current_price(pair, True) | |
| 305 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 306 | + | |
| 307 | + present = arrow.utcnow() | |
| 308 | + trade_start = arrow.get(active_trade[0].open_date) | |
| 309 | + open_minutes = (present - trade_start).total_seconds() // 60 | |
| 310 | + | |
| 311 | + trade_data['active_trade'] = True | |
| 312 | + trade_data['current_profit'] = active_trade[0].calc_profit_ratio(current_rate) | |
| 313 | + trade_data['peak_profit'] = max(0, active_trade[0].calc_profit_ratio(active_trade[0].max_rate)) | |
| 314 | + trade_data['open_minutes'] : int = open_minutes | |
| 315 | + trade_data['open_candles'] : int = (open_minutes // active_trade[0].timeframe) | |
| 316 | + else: | |
| 317 | + trade_data['current_profit'] = trade_data['peak_profit'] = 0.0 | |
| 318 | + trade_data['open_minutes'] = trade_data['open_candles'] = 0 | |
| 319 | + | |
| 320 | + other_trades = Trade.get_trades([Trade.pair != pair, Trade.is_open.is_(True),]).all() | |
| 321 | + | |
| 322 | + if other_trades: | |
| 323 | + trade_data['other_trades'] = True | |
| 324 | + other_profit = tuple(trade.calc_profit_ratio(self.get_current_price(trade.pair, False)) for trade in other_trades) | |
| 325 | + trade_data['avg_other_profit'] = mean(other_profit) | |
| 326 | + if trade_data['current_profit'] < min(other_profit): | |
| 327 | + trade_data['biggest_loser'] = True | |
| 328 | + else: | |
| 329 | + trade_data['avg_other_profit'] = 0 | |
| 330 | + | |
| 331 | + open_trades = len(Trade.get_open_trades()) | |
| 332 | + trade_data['free_slots'] = max(0, self.config['max_open_trades'] - open_trades) | |
| 333 | + | |
| 334 | + return trade_data | |
| 335 | + | |
| 336 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 337 | + if not refresh: | |
| 338 | + rate = self.custom_current_price_cache.get(pair) | |
| 339 | + if rate: | |
| 340 | + return rate | |
| 341 | + | |
| 342 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 343 | + if ask_strategy.get('use_order_book', False): | |
| 344 | + ob = self.dp.orderbook(pair, 1) | |
| 345 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 346 | + else: | |
| 347 | + ticker = self.dp.ticker(pair) | |
| 348 | + rate = ticker['last'] | |
| 349 | + | |
| 350 | + self.custom_current_price_cache[pair] = rate | |
| 351 | + return rate | |
| 352 | + | |
| 353 | + def linear_growth(self, start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float: | |
| 354 | + time = max(0, trade_time - start_time) | |
| 355 | + rate = (end - start) / (end_time - start_time) | |
| 356 | + return min(end, start + (rate * trade_time)) | |
| 357 | + | |
| 358 | + | |
| 359 | + """ | |
| 360 | + Price protection on trade entry and timeouts, built-in Freqtrade functionality | |
| 361 | + https://www.freqtrade.io/en/latest/strategy-advanced/ | |
| 362 | + """ | |
| 363 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 364 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 365 | + ob = self.dp.orderbook(pair, 1) | |
| 366 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 367 | + if current_price > order['price'] * 1.01: | |
| 368 | + return True | |
| 369 | + return False | |
| 370 | + | |
| 371 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 372 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 373 | + ob = self.dp.orderbook(pair, 1) | |
| 374 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 375 | + if current_price < order['price'] * 0.99: | |
| 376 | + return True | |
| 377 | + return False | |
| 378 | + | |
| 379 | + def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, **kwargs) -> bool: | |
| 380 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 381 | + ob = self.dp.orderbook(pair, 1) | |
| 382 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 383 | + if current_price > rate * 1.01: | |
| 384 | + return False | |
| 385 | + return True | |
| 386 | + | |
| 387 | + | |
| 388 | +""" | |
| 389 | +Sub-strategy overrides | |
| 390 | +Anything not explicity defined here will follow the settings in the base strategy | |
| 391 | +""" | |
| 392 | +# Sub-strategy with parameters specific to BTC stake | |
| 393 | +class SuperHV27_BTC(SuperHV27): | |
| 394 | + | |
| 395 | + timeframe = '5m' | |
| 396 | + | |
| 397 | + | |
| 398 | + | |
| 399 | + use_sell_signal = False | |
| 400 | + | |
| 401 | +# Sub-strategy with parameters specific to ETH stake | |
| 402 | +class SuperHV27_ETH(SuperHV27): | |
| 403 | + | |
| 404 | + timeframe = '5m' | |
| 405 | + | |
| 406 | + | |
| 407 | + | |
| 408 | + use_sell_signal = False | |
| No newline at the end of the file |
added strategies/old/Supertrend.py +115 −0
| @@ -0,0 +1,115 @@ | ||
| 1 | +# --- Do not remove these libs --- | |
| 2 | +from freqtrade.strategy.interface import IStrategy | |
| 3 | +from typing import Dict, List | |
| 4 | +from functools import reduce | |
| 5 | +from pandas import DataFrame | |
| 6 | +# -------------------------------- | |
| 7 | + | |
| 8 | +import talib.abstract as ta | |
| 9 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 10 | +import pandas as pd | |
| 11 | +import numpy as np | |
| 12 | + | |
| 13 | + | |
| 14 | +def supertrend(dataframe, multiplier=3, period=10): | |
| 15 | + """ | |
| 16 | + Supertrend Indicator | |
| 17 | + adapted for freqtrade | |
| 18 | + from: https://github.com/freqtrade/freqtrade-strategies/issues/30 | |
| 19 | + """ | |
| 20 | + df = dataframe.copy() | |
| 21 | + | |
| 22 | + df['TR'] = ta.TRANGE(df) | |
| 23 | + df['ATR'] = df['TR'].ewm(alpha=1 / period).mean() | |
| 24 | + | |
| 25 | + # atr = 'ATR_' + str(period) | |
| 26 | + st = 'ST_' + str(period) + '_' + str(multiplier) | |
| 27 | + stx = 'STX_' + str(period) + '_' + str(multiplier) | |
| 28 | + | |
| 29 | + # Compute basic upper and lower bands | |
| 30 | + df['basic_ub'] = (df['high'] + df['low']) / 2 + multiplier * df['ATR'] | |
| 31 | + df['basic_lb'] = (df['high'] + df['low']) / 2 - multiplier * df['ATR'] | |
| 32 | + | |
| 33 | + # Compute final upper and lower bands | |
| 34 | + df['final_ub'] = 0.00 | |
| 35 | + df['final_lb'] = 0.00 | |
| 36 | + for i in range(period, len(df)): | |
| 37 | + df['final_ub'].iat[i] = df['basic_ub'].iat[i] if df['basic_ub'].iat[i] < df['final_ub'].iat[i - 1] or df['close'].iat[i - 1] > df['final_ub'].iat[i - 1] else df['final_ub'].iat[i - 1] | |
| 38 | + df['final_lb'].iat[i] = df['basic_lb'].iat[i] if df['basic_lb'].iat[i] > df['final_lb'].iat[i - 1] or df['close'].iat[i - 1] < df['final_lb'].iat[i - 1] else df['final_lb'].iat[i - 1] | |
| 39 | + | |
| 40 | + # Set the Supertrend value | |
| 41 | + df[st] = 0.00 | |
| 42 | + for i in range(period, len(df)): | |
| 43 | + df[st].iat[i] = df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[i] <= df['final_ub'].iat[i] else \ | |
| 44 | + df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[i] > df['final_ub'].iat[i] else \ | |
| 45 | + df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] >= df['final_lb'].iat[i] else \ | |
| 46 | + df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] < df['final_lb'].iat[i] else 0.00 | |
| 47 | + | |
| 48 | + # Mark the trend direction up/down | |
| 49 | + df[stx] = np.where((df[st] > 0.00), np.where((df['close'] < df[st]), 'down', 'up'), np.NaN) | |
| 50 | + | |
| 51 | + # Remove basic and final bands from the columns | |
| 52 | + df.drop(['basic_ub', 'basic_lb', 'final_ub', 'final_lb'], inplace=True, axis=1) | |
| 53 | + | |
| 54 | + df.fillna(0, inplace=True) | |
| 55 | + | |
| 56 | + # df.to_csv('user_data/Supertrend.csv') | |
| 57 | + return DataFrame(index=df.index, data={ | |
| 58 | + 'ST': df[st], | |
| 59 | + 'STX': df[stx] | |
| 60 | + }) | |
| 61 | + | |
| 62 | + | |
| 63 | +class Supertrend(IStrategy): | |
| 64 | + | |
| 65 | + # Minimal ROI designed for the strategy. | |
| 66 | + # This attribute will be overridden if the config file contains "minimal_roi" | |
| 67 | + minimal_roi = { | |
| 68 | + "0": 0.1, | |
| 69 | + "2880": 0.01 | |
| 70 | + } | |
| 71 | + | |
| 72 | + # Optimal stoploss designed for the strategy | |
| 73 | + # This attribute will be overridden if the config file contains "stoploss" | |
| 74 | + stoploss = -0.25 | |
| 75 | + | |
| 76 | + # Optimal timeframe for the strategy | |
| 77 | + timeframe = '5m' | |
| 78 | + | |
| 79 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 80 | + | |
| 81 | + dataframe["supertrend_3_12"] = supertrend(dataframe, 3, 12)["STX"] | |
| 82 | + dataframe["supertrend_1_10"] = supertrend(dataframe, 1, 10)["STX"] | |
| 83 | + dataframe["supertrend_2_11"] = supertrend(dataframe, 2, 11)["STX"] | |
| 84 | + | |
| 85 | + # required for graphing | |
| 86 | + bollinger = qtpylib.bollinger_bands(dataframe['close'], window=20, stds=2) | |
| 87 | + dataframe['bb_lowerband'] = bollinger['lower'] | |
| 88 | + dataframe['bb_middleband'] = bollinger['mid'] | |
| 89 | + dataframe['bb_upperband'] = bollinger['upper'] | |
| 90 | + | |
| 91 | + return dataframe | |
| 92 | + | |
| 93 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 94 | + dataframe.loc[ | |
| 95 | + ( | |
| 96 | + ( | |
| 97 | + (dataframe["supertrend_3_12"] == "up") & | |
| 98 | + (dataframe["supertrend_1_10"] == "up") & | |
| 99 | + (dataframe["supertrend_2_11"] == "up") | |
| 100 | + ) | |
| 101 | + ), | |
| 102 | + 'buy'] = 1 | |
| 103 | + return dataframe | |
| 104 | + | |
| 105 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 106 | + dataframe.loc[ | |
| 107 | + ( | |
| 108 | + ( | |
| 109 | + (dataframe["supertrend_3_12"] == "down") & | |
| 110 | + (dataframe["supertrend_1_10"] == "down") & | |
| 111 | + (dataframe["supertrend_2_11"] == "down") | |
| 112 | + ) | |
| 113 | + ), | |
| 114 | + 'sell'] = 1 | |
| 115 | + return dataframe |
added strategies/old/Supertrend_ORIG.py +170 −0
| @@ -0,0 +1,170 @@ | ||
| 1 | +# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement | |
| 2 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 3 | +import numpy as np | |
| 4 | +import talib.abstract as ta | |
| 5 | +from freqtrade.strategy.interface import IStrategy | |
| 6 | +from freqtrade.strategy import merge_informative_pair | |
| 7 | +from pandas import DataFrame, Series | |
| 8 | +from functools import reduce | |
| 9 | +from datetime import datetime | |
| 10 | +from freqtrade.persistence import Trade | |
| 11 | + | |
| 12 | +# supertrend | |
| 13 | +# ref: https://www.tradingfuel.com/supertrend-indicator-formula-and-calculation/ | |
| 14 | +# manipulates the existing dataframe and this is almost certainly bad | |
| 15 | +def supertrend(dataframe: DataFrame, multiplier=3) -> DataFrame: | |
| 16 | + average_price = (dataframe['high'] + dataframe['low']) / 2 | |
| 17 | + | |
| 18 | + basic_upperband = (average_price + (multiplier * dataframe['atr'])) | |
| 19 | + basic_lowerband = (average_price - (multiplier * dataframe['atr'])) | |
| 20 | + | |
| 21 | + # Final Upper Band | |
| 22 | + if not 'st_final_upperband' in dataframe.columns: | |
| 23 | + dataframe['st_final_upperband'] = 0 | |
| 24 | + else: | |
| 25 | + if (basic_upperband < dataframe['st_final_upperband'].shift(1)) or (dataframe['close'].shift(1) > dataframe['st_final_upperband'].shift(1)): | |
| 26 | + dataframe['st_final_upperband'] = basic_upperband | |
| 27 | + else: | |
| 28 | + dataframe['st_final_upperband'] = dataframe['st_final_upperband'].shift(1) | |
| 29 | + | |
| 30 | + # Final Lower Band | |
| 31 | + if not 'st_final_lowerband' in dataframe.columns: | |
| 32 | + dataframe['st_final_lowerband'] = 0 | |
| 33 | + else: | |
| 34 | + if (basic_lowerband > dataframe['st_final_lowerband'].shift(1)) or (dataframe['close'].shift(1) < dataframe['st_final_lowerband'].shift(1)): | |
| 35 | + dataframe['st_final_lowerband'] = basic_lowerband | |
| 36 | + else: | |
| 37 | + dataframe['st_final_lowerband'] = dataframe['st_final_lowerband'].shift(1) | |
| 38 | + | |
| 39 | + # Supertrend | |
| 40 | + if not 'supertrend' in dataframe.columns: | |
| 41 | + dataframe['supertrend'] = 0 | |
| 42 | + elif (dataframe['supertrend'].shift(1) == dataframe['st_final_upperband'].shift(1)) and (dataframe['close'] <= dataframe['st_final_upperband']): | |
| 43 | + dataframe['supertrend'] = dataframe['st_final_upperband'] | |
| 44 | + | |
| 45 | + elif (dataframe['supertrend'].shift(1) == dataframe['st_final_upperband'].shift(1)) and (dataframe['close'] > dataframe['st_final_upperband']): | |
| 46 | + dataframe['supertrend'] = dataframe['st_final_lowerband'] | |
| 47 | + | |
| 48 | + elif (dataframe['supertrend'].shift(1) == dataframe['st_final_lowerband'].shift(1)) and (dataframe['close'] >= dataframe['st_final_lowerband']): | |
| 49 | + dataframe['supertrend'] = dataframe['st_final_lowerband'] | |
| 50 | + | |
| 51 | + elif (dataframe['supertrend'].shift(1) == dataframe['st_final_lowerband'].shift(1)) and (dataframe['close'] < dataframe['st_final_lowerband']): | |
| 52 | + dataframe['supertrend'] = dataframe['st_final_upperband'] | |
| 53 | + | |
| 54 | + return dataframe | |
| 55 | + | |
| 56 | + | |
| 57 | +class Supertrend(IStrategy): | |
| 58 | + | |
| 59 | + """ | |
| 60 | + PASTE OUTPUT FROM HYPEROPT HERE | |
| 61 | + """ | |
| 62 | + # Buy hyperspace params: | |
| 63 | + buy_params = { | |
| 64 | + 'buy-method': 'both', # sar, supertrend, both | |
| 65 | + 'buy-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 66 | + } | |
| 67 | + | |
| 68 | + # Sell hyperspace params: | |
| 69 | + sell_params = { | |
| 70 | + 'sell-method': 'both', # sar, supertrend, both | |
| 71 | + 'sell-price': 'ohlc4' # open, close, hl2, hlc3, ohlc4 | |
| 72 | + } | |
| 73 | + | |
| 74 | + # ROI table: | |
| 75 | + minimal_roi = { | |
| 76 | + "0": 0.10, | |
| 77 | + "30": 0.05, | |
| 78 | + "60": 0.02, | |
| 79 | + "120": 0 | |
| 80 | + } | |
| 81 | + | |
| 82 | + stoploss = -1 | |
| 83 | + | |
| 84 | + """ | |
| 85 | + END HYPEROPT | |
| 86 | + """ | |
| 87 | + | |
| 88 | + timeframe = '5m' | |
| 89 | + | |
| 90 | + use_sell_signal = True | |
| 91 | + sell_profit_only = False | |
| 92 | + sell_profit_offset = 0.02 | |
| 93 | + ignore_roi_if_buy_signal = True | |
| 94 | + | |
| 95 | + process_only_new_candles = False | |
| 96 | + | |
| 97 | + startup_candle_count: int = 10 | |
| 98 | + | |
| 99 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 100 | + | |
| 101 | + dataframe['ohlc4'] = ta.AVGPRICE(dataframe) | |
| 102 | + dataframe['hlc3'] = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3 | |
| 103 | + dataframe['hl2'] = (dataframe['high'] + dataframe['low']) / 2 | |
| 104 | + | |
| 105 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=10) | |
| 106 | + dataframe['sar'] = ta.SAR(dataframe) | |
| 107 | + | |
| 108 | + dataframe = supertrend(dataframe, multiplier=1) | |
| 109 | + | |
| 110 | + return dataframe | |
| 111 | + | |
| 112 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 113 | + params = self.buy_params | |
| 114 | + | |
| 115 | + conditions = [] | |
| 116 | + | |
| 117 | + if params['buy-method'] == 'supertrend' or params['buy-method'] == 'both': | |
| 118 | + conditions.append(dataframe[params['buy-price']] > dataframe['supertrend']) | |
| 119 | + | |
| 120 | + if params['buy-method'] == 'sar' or params['buy-method'] == 'both': | |
| 121 | + conditions.append(dataframe[params['buy-price']] > dataframe['sar']) | |
| 122 | + | |
| 123 | + conditions.append(dataframe['volume'] > 0) | |
| 124 | + | |
| 125 | + if conditions: | |
| 126 | + dataframe.loc[ | |
| 127 | + reduce(lambda x, y: x & y, conditions), | |
| 128 | + 'buy'] = 1 | |
| 129 | + | |
| 130 | + return dataframe | |
| 131 | + | |
| 132 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 133 | + params = self.sell_params | |
| 134 | + | |
| 135 | + conditions = [] | |
| 136 | + | |
| 137 | + if params['sell-method'] == 'supertrend' or params['sell-method'] == 'both': | |
| 138 | + conditions.append(dataframe[params['sell-price']] < dataframe['supertrend']) | |
| 139 | + | |
| 140 | + if params['sell-method'] == 'sar' or params['sell-method'] == 'both': | |
| 141 | + conditions.append(dataframe[params['sell-price']] < dataframe['sar']) | |
| 142 | + | |
| 143 | + conditions.append(dataframe['volume'] > 0) | |
| 144 | + | |
| 145 | + if conditions: | |
| 146 | + dataframe.loc[ | |
| 147 | + reduce(lambda x, y: x & y, conditions), | |
| 148 | + 'sell'] = 1 | |
| 149 | + | |
| 150 | + return dataframe | |
| 151 | + | |
| 152 | + """ | |
| 153 | + Additional buy/sell timeout override if price drifts | |
| 154 | + """ | |
| 155 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 156 | + ob = self.dp.orderbook(pair, 1) | |
| 157 | + current_price = ob['bids'][0][0] | |
| 158 | + # Cancel buy order if price is more than 1% above the order. | |
| 159 | + if current_price > order['price'] * 1.01: | |
| 160 | + return True | |
| 161 | + return False | |
| 162 | + | |
| 163 | + | |
| 164 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 165 | + ob = self.dp.orderbook(pair, 1) | |
| 166 | + current_price = ob['asks'][0][0] | |
| 167 | + # Cancel sell order if price is more than 1% below the order. | |
| 168 | + if current_price < order['price'] * 0.99: | |
| 169 | + return True | |
| 170 | + return False | |
| No newline at the end of the file |
added strategies/old/YOLO.py +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 2 | +import numpy as np | |
| 3 | +import talib.abstract as ta | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +from pandas import DataFrame, DatetimeIndex, merge, Series | |
| 6 | + | |
| 7 | + | |
| 8 | +class YOLO(IStrategy): | |
| 9 | + | |
| 10 | + # Buy hyperspace params: | |
| 11 | + buy_params = { | |
| 12 | + 'adx': 34, | |
| 13 | + 'aroon-down': 33, | |
| 14 | + 'aroon-up': 98 | |
| 15 | + } | |
| 16 | + | |
| 17 | + # Sell hyperspace params: | |
| 18 | + sell_params = { | |
| 19 | + | |
| 20 | + } | |
| 21 | + | |
| 22 | + # ROI table: | |
| 23 | + minimal_roi = { | |
| 24 | + "0": 0.03, | |
| 25 | + "7": 0.02, | |
| 26 | + "33": 0.01, | |
| 27 | + "71": 0.005 | |
| 28 | + } | |
| 29 | + | |
| 30 | + # Stoploss: | |
| 31 | + stoploss = -0.01 | |
| 32 | + | |
| 33 | + # Trailing stop: | |
| 34 | + trailing_stop = True | |
| 35 | + trailing_stop_positive = 0.03289 | |
| 36 | + trailing_stop_positive_offset = 0.05723 | |
| 37 | + trailing_only_offset_is_reached = False | |
| 38 | + | |
| 39 | + """ | |
| 40 | + END HYPEROPT | |
| 41 | + """ | |
| 42 | + | |
| 43 | + timeframe = '1m' | |
| 44 | + | |
| 45 | + use_sell_signal = False | |
| 46 | + sell_profit_only = False | |
| 47 | + ignore_roi_if_buy_signal = True | |
| 48 | + | |
| 49 | + | |
| 50 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 51 | + | |
| 52 | + dataframe['adx'] = ta.ADX(dataframe, timeperiod=90) #90 | |
| 53 | + aroon = ta.AROON(dataframe, timeperiod=60) #60 | |
| 54 | + | |
| 55 | + dataframe['aroon-down'] = aroon['aroondown'] | |
| 56 | + dataframe['aroon-up'] = aroon['aroonup'] | |
| 57 | + | |
| 58 | + return dataframe | |
| 59 | + | |
| 60 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 61 | + params = self.buy_params | |
| 62 | + | |
| 63 | + dataframe.loc[ | |
| 64 | + ( | |
| 65 | + (dataframe['adx'] > params['adx']) & | |
| 66 | + (dataframe['aroon-up'] > params['aroon-up']) & | |
| 67 | + (dataframe['aroon-down'] < params['aroon-down']) & | |
| 68 | + (dataframe['volume'] > 0) | |
| 69 | + ), | |
| 70 | + 'buy' | |
| 71 | + ] = 1 | |
| 72 | + | |
| 73 | + return dataframe | |
| 74 | + | |
| 75 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 76 | + """ | |
| 77 | + no sell signal | |
| 78 | + """ | |
| 79 | + dataframe['sell'] = 0 | |
| 80 | + return dataframe | |
| No newline at the end of the file |
added strategies/old/consensus_strat.py +84 −0
| @@ -0,0 +1,84 @@ | ||
| 1 | +import numpy as np # noqa | |
| 2 | +import pandas as pd # noqa | |
| 3 | +from pandas import DataFrame | |
| 4 | +from freqtrade.strategy.interface import IStrategy | |
| 5 | +import talib.abstract as ta | |
| 6 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 7 | +from technical.consensus import Consensus | |
| 8 | + | |
| 9 | +class conny(IStrategy): | |
| 10 | + | |
| 11 | + minimal_roi = { | |
| 12 | + "0": 0.025, | |
| 13 | + "10": 0.015, | |
| 14 | + "20": 0.01, | |
| 15 | + "30": 0.005, | |
| 16 | + "120": 0 | |
| 17 | + } | |
| 18 | + | |
| 19 | + stoploss = -0.0203 | |
| 20 | + | |
| 21 | + timeframe = '15m' | |
| 22 | + | |
| 23 | + process_only_new_candles = True | |
| 24 | + | |
| 25 | + use_sell_signal = True | |
| 26 | + sell_profit_only = False | |
| 27 | + ignore_roi_if_buy_signal = True | |
| 28 | + | |
| 29 | + startup_candle_count: int = 30 | |
| 30 | + | |
| 31 | + | |
| 32 | + def informative_pairs(self): | |
| 33 | + return [] | |
| 34 | + | |
| 35 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 36 | + # Consensus strategy | |
| 37 | + # add c.evaluate_indicator bellow to include it in the consensus score (look at | |
| 38 | + # consensus.py in freqtrade technical) | |
| 39 | + # add custom indicator with c.evaluate_consensus(prefix=<indicator name>) | |
| 40 | + c = Consensus(dataframe) | |
| 41 | + c.evaluate_rsi() | |
| 42 | + c.evaluate_stoch() | |
| 43 | + c.evaluate_macd_cross_over() | |
| 44 | + c.evaluate_macd() | |
| 45 | + c.evaluate_hull() | |
| 46 | + c.evaluate_vwma() | |
| 47 | + c.evaluate_tema(period=12) | |
| 48 | + c.evaluate_ema(period=24) | |
| 49 | + c.evaluate_sma(period=12) | |
| 50 | + c.evaluate_laguerre() | |
| 51 | + c.evaluate_osc() | |
| 52 | + c.evaluate_cmf() | |
| 53 | + c.evaluate_cci() | |
| 54 | + c.evaluate_cmo() | |
| 55 | + c.evaluate_ichimoku() | |
| 56 | + c.evaluate_ultimate_oscilator() | |
| 57 | + c.evaluate_williams() | |
| 58 | + c.evaluate_momentum() | |
| 59 | + c.evaluate_adx() | |
| 60 | + dataframe['consensus_buy'] = c.score()['buy'] | |
| 61 | + dataframe['consensus_sell'] = c.score()['sell'] | |
| 62 | + | |
| 63 | + | |
| 64 | + print(dataframe) | |
| 65 | + return dataframe | |
| 66 | + | |
| 67 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 68 | + dataframe.loc[ | |
| 69 | + ( | |
| 70 | + (dataframe['consensus_buy'] > 45) & | |
| 71 | + (dataframe['volume'] > 0) | |
| 72 | + ), | |
| 73 | + 'buy'] = 1 | |
| 74 | + | |
| 75 | + return dataframe | |
| 76 | + | |
| 77 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 78 | + dataframe.loc[ | |
| 79 | + ( | |
| 80 | + (dataframe['consensus_sell'] > 88) & | |
| 81 | + (dataframe['volume'] > 0) | |
| 82 | + ), | |
| 83 | + 'sell'] = 1 | |
| 84 | + return dataframe | |
| No newline at the end of the file |