Elffuss BraidHub

kikocis/freqtrade public

develop · 34.4 KiBRenderedRawPermalink
1# Hyperopt
2
3This page explains how to tune your strategy by finding the optimal
4parameters, a process called hyperparameter optimization. The bot uses algorithms included in the `scikit-optimize` package to accomplish this.
5The search will burn all your CPU cores, make your laptop sound like a fighter jet and still take a long time.
6
7In general, the search for best parameters starts with a few random combinations (see [below](#reproducible-results) for more details) and then uses Bayesian search with a ML regressor algorithm (currently ExtraTreesRegressor) to quickly find a combination of parameters in the search hyperspace that minimizes the value of the [loss function](#loss-functions).
8
9Hyperopt requires historic data to be available, just as backtesting does (hyperopt runs backtesting many times with different parameters).
10To learn how to get data for the pairs and exchange you're interested in, head over to the [Data Downloading](data-download.md) section of the documentation.
11
12!!! Bug
13 Hyperopt can crash when used with only 1 CPU Core as found out in [Issue #1133](https://github.com/freqtrade/freqtrade/issues/1133)
14
15!!! Note
16 Since 2021.4 release you no longer have to write a separate hyperopt class, but can configure the parameters directly in the strategy.
17 The legacy method is still supported, but it is no longer the recommended way of setting up hyperopt.
18 The legacy documentation is available at [Legacy Hyperopt](advanced-hyperopt.md#legacy-hyperopt).
19
20## Install hyperopt dependencies
21
22Since Hyperopt dependencies are not needed to run the bot itself, are heavy, can not be easily built on some platforms (like Raspberry PI), they are not installed by default. Before you run Hyperopt, you need to install the corresponding dependencies, as described in this section below.
23
24!!! Note
25 Since Hyperopt is a resource intensive process, running it on a Raspberry Pi is not recommended nor supported.
26
27### Docker
28
29The docker-image includes hyperopt dependencies, no further action needed.
30
31### Easy installation script (setup.sh) / Manual installation
32
33```bash
34source .env/bin/activate
35pip install -r requirements-hyperopt.txt
36```
37
38## Hyperopt command reference
39
40```
41usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
42 [--userdir PATH] [-s NAME] [--strategy-path PATH]
43 [-i TIMEFRAME] [--timerange TIMERANGE]
44 [--data-format-ohlcv {json,jsongz,hdf5}]
45 [--max-open-trades INT]
46 [--stake-amount STAKE_AMOUNT] [--fee FLOAT]
47 [-p PAIRS [PAIRS ...]] [--hyperopt NAME]
48 [--hyperopt-path PATH] [--eps] [--dmmp]
49 [--enable-protections]
50 [--dry-run-wallet DRY_RUN_WALLET] [-e INT]
51 [--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]
52 [--print-all] [--no-color] [--print-json] [-j JOBS]
53 [--random-state INT] [--min-trades INT]
54 [--hyperopt-loss NAME]
55
56optional arguments:
57 -h, --help show this help message and exit
58 -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME
59 Specify timeframe (`1m`, `5m`, `30m`, `1h`, `1d`).
60 --timerange TIMERANGE
61 Specify what timerange of data to use.
62 --data-format-ohlcv {json,jsongz,hdf5}
63 Storage format for downloaded candle (OHLCV) data.
64 (default: `None`).
65 --max-open-trades INT
66 Override the value of the `max_open_trades`
67 configuration setting.
68 --stake-amount STAKE_AMOUNT
69 Override the value of the `stake_amount` configuration
70 setting.
71 --fee FLOAT Specify fee ratio. Will be applied twice (on trade
72 entry and exit).
73 -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]
74 Limit command to these pairs. Pairs are space-
75 separated.
76 --hyperopt NAME Specify hyperopt class name which will be used by the
77 bot.
78 --hyperopt-path PATH Specify additional lookup path for Hyperopt and
79 Hyperopt Loss functions.
80 --eps, --enable-position-stacking
81 Allow buying the same pair multiple times (position
82 stacking).
83 --dmmp, --disable-max-market-positions
84 Disable applying `max_open_trades` during backtest
85 (same as setting `max_open_trades` to a very high
86 number).
87 --enable-protections, --enableprotections
88 Enable protections for backtesting.Will slow
89 backtesting down by a considerable amount, but will
90 include configured protections
91 --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET
92 Starting balance, used for backtesting / hyperopt and
93 dry-runs.
94 -e INT, --epochs INT Specify number of epochs (default: 100).
95 --spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]
96 Specify which parameters to hyperopt. Space-separated
97 list.
98 --print-all Print all results, not only the best ones.
99 --no-color Disable colorization of hyperopt results. May be
100 useful if you are redirecting output to a file.
101 --print-json Print output in JSON format.
102 -j JOBS, --job-workers JOBS
103 The number of concurrently running jobs for
104 hyperoptimization (hyperopt worker processes). If -1
105 (default), all CPUs are used, for -2, all CPUs but one
106 are used, etc. If 1 is given, no parallel computing
107 code is used at all.
108 --random-state INT Set random state to some positive integer for
109 reproducible hyperopt results.
110 --min-trades INT Set minimal desired number of trades for evaluations
111 in the hyperopt optimization path (default: 1).
112 --hyperopt-loss NAME, --hyperoptloss NAME
113 Specify the class name of the hyperopt loss function
114 class (IHyperOptLoss). Different functions can
115 generate completely different results, since the
116 target for optimization is different. Built-in
117 Hyperopt-loss-functions are:
118 ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss,
119 SharpeHyperOptLoss, SharpeHyperOptLossDaily,
120 SortinoHyperOptLoss, SortinoHyperOptLossDaily
121
122Common arguments:
123 -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
124 --logfile FILE Log to the file specified. Special values are:
125 'syslog', 'journald'. See the documentation for more
126 details.
127 -V, --version show program's version number and exit
128 -c PATH, --config PATH
129 Specify configuration file (default:
130 `userdir/config.json` or `config.json` whichever
131 exists). Multiple --config options may be used. Can be
132 set to `-` to read config from stdin.
133 -d PATH, --datadir PATH
134 Path to directory with historical backtesting data.
135 --userdir PATH, --user-data-dir PATH
136 Path to userdata directory.
137
138Strategy arguments:
139 -s NAME, --strategy NAME
140 Specify strategy class name which will be used by the
141 bot.
142 --strategy-path PATH Specify additional strategy lookup path.
143
144```
145
146### Hyperopt checklist
147
148Checklist on all tasks / possibilities in hyperopt
149
150Depending on the space you want to optimize, only some of the below are required:
151
152* define parameters with `space='buy'` - for buy signal optimization
153* define parameters with `space='sell'` - for sell signal optimization
154
155!!! Note
156 `populate_indicators` needs to create all indicators any of the spaces may use, otherwise hyperopt will not work.
157
158Rarely you may also need to create a [nested class](advanced-hyperopt.md#overriding-pre-defined-spaces) named `HyperOpt` and implement
159
160* `roi_space` - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
161* `generate_roi_table` - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)
162* `stoploss_space` - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
163* `trailing_space` - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)
164
165!!! Tip "Quickly optimize ROI, stoploss and trailing stoploss"
166 You can quickly optimize the spaces `roi`, `stoploss` and `trailing` without changing anything in your strategy.
167
168 ```python
169 # Have a working strategy at hand.
170 freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100
171 ```
172
173### Configure your Guards and Triggers
174
175There are two places you need to change in your strategy file to add a new buy hyperopt for testing:
176
177* Define the parameters at the class level hyperopt shall be optimizing.
178* Within `populate_buy_trend()` - use defined parameter values instead of raw constants.
179
180There you have two different types of indicators: 1. `guards` and 2. `triggers`.
181
1821. Guards are conditions like "never buy if ADX < 10", or never buy if current price is over EMA10.
1832. Triggers are ones that actually trigger buy in specific moment, like "buy when EMA5 crosses over EMA10" or "buy when close price touches lower Bollinger band".
184
185!!! Hint "Guards and Triggers"
186 Technically, there is no difference between Guards and Triggers.
187 However, this guide will make this distinction to make it clear that signals should not be "sticking".
188 Sticking signals are signals that are active for multiple candles. This can lead into buying a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning).
189
190Hyper-optimization will, for each epoch round, pick one trigger and possibly
191multiple guards. The constructed strategy will be something like "*buy exactly when close price touches lower Bollinger band, BUT only if
192ADX > 10*".
193
194```python
195from freqtrade.strategy import IntParameter, IStrategy
196
197class MyAwesomeStrategy(IStrategy):
198 # If parameter is prefixed with `buy_` or `sell_` then specifying `space` parameter is optional
199 # and space is inferred from parameter name.
200 buy_adx_min = IntParameter(0, 100, default=10)
201
202 def populate_buy_trend(self, dataframe: 'DataFrame', metadata: dict) -> 'DataFrame':
203 dataframe.loc[
204 (
205 (dataframe['adx'] > self.buy_adx_min.value)
206 ), 'buy'] = 1
207 return dataframe
208```
209
210#### Sell optimization
211
212Similar to the buy-signal above, sell-signals can also be optimized.
213Place the corresponding settings into the following methods
214
215* Define the parameters at the class level hyperopt shall be optimizing.
216* Within `populate_sell_trend()` - use defined parameter values instead of raw constants.
217
218The configuration and rules are the same than for buy signals.
219
220```python
221class MyAwesomeStrategy(IStrategy):
222 # There is no strict parameter naming scheme. If you do not use `buy_` or `sell_` prefixes -
223 # please specify to which space parameter belongs using `space` parameter. Possible values:
224 # 'buy' or 'sell'.
225 adx_max = IntParameter(0, 100, default=50, space='sell')
226
227 def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
228 dataframe.loc[
229 (
230 (dataframe['adx'] < self.adx_max.value)
231 ), 'buy'] = 1
232 return dataframe
233```
234
235## Solving a Mystery
236
237Let's say you are curious: should you use MACD crossings or lower Bollinger
238Bands to trigger your buys. And you also wonder should you use RSI or ADX to
239help with those buy decisions. If you decide to use RSI or ADX, which values
240should I use for them? So let's use hyperparameter optimization to solve this
241mystery.
242
243We will start by defining hyperoptable parameters:
244
245```python
246class MyAwesomeStrategy(IStrategy):
247 buy_adx = IntParameter(20, 40, default=30)
248 buy_rsi = IntParameter(20, 40, default=30)
249 buy_adx_enabled = CategoricalParameter([True, False]),
250 buy_rsi_enabled = CategoricalParameter([True, False]),
251 buy_trigger = CategoricalParameter(['bb_lower', 'macd_cross_signal']),
252```
253
254Above definition says: I have five parameters I want to randomly combine to find the best combination.
255Two of them are integer values (`buy_adx` and `buy_rsi`) and I want you test in the range of values 20 to 40.
256Then we have three category variables. First two are either `True` or `False`.
257We use these to either enable or disable the ADX and RSI guards.
258The last one we call `trigger` and use it to decide which buy trigger we want to use.
259
260So let's write the buy strategy using these values:
261
262```python
263 def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
264 conditions = []
265 # GUARDS AND TRENDS
266 if self.buy_adx_enabled.value:
267 conditions.append(dataframe['adx'] > self.buy_adx.value)
268 if self.buy_rsi_enabled.value:
269 conditions.append(dataframe['rsi'] < self.buy_rsi.value)
270
271 # TRIGGERS
272 if self.buy_trigger.value == 'bb_lower':
273 conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
274 if self.buy_trigger.value == 'macd_cross_signal':
275 conditions.append(qtpylib.crossed_above(
276 dataframe['macd'], dataframe['macdsignal']
277 ))
278
279 # Check that volume is not 0
280 conditions.append(dataframe['volume'] > 0)
281
282 if conditions:
283 dataframe.loc[
284 reduce(lambda x, y: x & y, conditions),
285 'buy'] = 1
286
287 return dataframe
288```
289
290Hyperopt will now call `populate_buy_trend()` many times (`epochs`) with different value combinations.
291It will use the given historical data and make buys based on the buy signals generated with the above function.
292Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured [loss function](#loss-functions)).
293
294!!! Note
295 The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
296 When you want to test an indicator that isn't used by the bot currently, remember to
297 add it to the `populate_indicators()` method in your strategy or hyperopt file.
298
299## Parameter types
300
301There are four parameter types each suited for different purposes.
302
303* `IntParameter` - defines an integral parameter with upper and lower boundaries of search space.
304* `DecimalParameter` - defines a floating point parameter with a limited number of decimals (default 3). Should be preferred instead of `RealParameter` in most cases.
305* `RealParameter` - defines a floating point parameter with upper and lower boundaries and no precision limit. Rarely used as it creates a space with a near infinite number of possibilities.
306* `CategoricalParameter` - defines a parameter with a predetermined number of choices.
307
308!!! Tip "Disabling parameter optimization"
309 Each parameter takes two boolean parameters:
310 * `load` - when set to `False` it will not load values configured in `buy_params` and `sell_params`.
311 * `optimize` - when set to `False` parameter will not be included in optimization process.
312 Use these parameters to quickly prototype various ideas.
313
314!!! Warning
315 Hyperoptable parameters cannot be used in `populate_indicators` - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case.
316
317## Loss-functions
318
319Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results.
320
321A loss function must be specified via the `--hyperopt-loss <Class-name>` argument (or optionally via the configuration under the `"hyperopt_loss"` key).
322This class should be in its own file within the `user_data/hyperopts/` directory.
323
324Currently, the following loss functions are builtin:
325
326* `ShortTradeDurHyperOptLoss` (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses.
327* `OnlyProfitHyperOptLoss` (which takes only amount of profit into consideration)
328* `SharpeHyperOptLoss` (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation)
329* `SharpeHyperOptLossDaily` (optimizes Sharpe Ratio calculated on **daily** trade returns relative to standard deviation)
330* `SortinoHyperOptLoss` (optimizes Sortino Ratio calculated on trade returns relative to **downside** standard deviation)
331* `SortinoHyperOptLossDaily` (optimizes Sortino Ratio calculated on **daily** trade returns relative to **downside** standard deviation)
332
333Creation of a custom loss function is covered in the [Advanced Hyperopt](advanced-hyperopt.md) part of the documentation.
334
335## Execute Hyperopt
336
337Once you have updated your hyperopt configuration you can run it.
338Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result.
339
340We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
341
342```bash
343freqtrade hyperopt --config config.json --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all
344```
345
346The `-e` option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs.
347Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results.
348
349The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
350
351!!! Note
352 Hyperopt will store hyperopt results with the timestamp of the hyperopt start time.
353 Reading commands (`hyperopt-list`, `hyperopt-show`) can use `--hyperopt-filename <filename>` to read and display older hyperopt results.
354 You can find a list of filenames with `ls -l user_data/hyperopt_results/`.
355
356### Execute Hyperopt with different historical data source
357
358If you would like to hyperopt parameters using an alternate historical data set that
359you have on-disk, use the `--datadir PATH` option. By default, hyperopt uses data from directory `user_data/data`.
360
361### Running Hyperopt with a smaller test-set
362
363Use the `--timerange` argument to change how much of the test-set you want to use.
364For example, to use one month of data, pass `--timerange 20210101-20210201` (from january 2021 - february 2021) to the hyperopt call.
365
366Full command:
367
368```bash
369freqtrade hyperopt --hyperopt <hyperoptname> --strategy <strategyname> --timerange 20210101-20210201
370```
371
372### Running Hyperopt with Smaller Search Space
373
374Use the `--spaces` option to limit the search space used by hyperopt.
375Letting Hyperopt optimize everything is a huuuuge search space.
376Often it might make more sense to start by just searching for initial buy algorithm.
377Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have.
378
379Legal values are:
380
381* `all`: optimize everything
382* `buy`: just search for a new buy strategy
383* `sell`: just search for a new sell strategy
384* `roi`: just optimize the minimal profit table for your strategy
385* `stoploss`: search for the best stoploss value
386* `trailing`: search for the best trailing stop values
387* `default`: `all` except `trailing`
388* space-separated list of any of the above values for example `--spaces roi stoploss`
389
390The default Hyperopt Search Space, used when no `--space` command line option is specified, does not include the `trailing` hyperspace. We recommend you to run optimization for the `trailing` hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.
391
392## Understand the Hyperopt Result
393
394Once Hyperopt is completed you can use the result to update your strategy.
395Given the following result from hyperopt:
396
397```
398Best result:
399
400 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
401
402 # Buy hyperspace params:
403 buy_params = {
404 'buy_adx': 44,
405 'buy_rsi': 29,
406 'buy_adx_enabled': False,
407 'buy_rsi_enabled': True,
408 'buy_trigger': 'bb_lower'
409 }
410```
411
412You should understand this result like:
413
414* The buy trigger that worked best was `bb_lower`.
415* You should not use ADX because `'buy_adx_enabled': False`.
416* You should **consider** using the RSI indicator (`'buy_rsi_enabled': True`) and the best value is `29.0` (`'buy_rsi': 29.0`)
417
418Your strategy class can immediately take advantage of these results. Simply copy hyperopt results block and paste them at class level, replacing old parameters (if any). New parameters will automatically be loaded next time strategy is executed.
419
420Transferring your whole hyperopt result to your strategy would then look like:
421
422```python
423class MyAwesomeStrategy(IStrategy):
424 # Buy hyperspace params:
425 buy_params = {
426 'buy_adx': 44,
427 'buy_rsi': 29,
428 'buy_adx_enabled': False,
429 'buy_rsi_enabled': True,
430 'buy_trigger': 'bb_lower'
431 }
432```
433
434### Understand Hyperopt ROI results
435
436If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table:
437
438```
439Best result:
440
441 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
442
443 # ROI table:
444 minimal_roi = {
445 0: 0.10674,
446 21: 0.09158,
447 78: 0.03634,
448 118: 0
449 }
450```
451
452In order to use this best ROI table found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the `minimal_roi` attribute of your custom strategy:
453
454```
455 # Minimal ROI designed for the strategy.
456 # This attribute will be overridden if the config file contains "minimal_roi"
457 minimal_roi = {
458 0: 0.10674,
459 21: 0.09158,
460 78: 0.03634,
461 118: 0
462 }
463```
464
465As stated in the comment, you can also use it as the value of the `minimal_roi` setting in the configuration file.
466
467#### Default ROI Search Space
468
469If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the timeframe used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 3 digits after the decimal point):
470
471| # step | 1m | | 5m | | 1h | | 1d | |
472| ------ | ------ | ------------- | -------- | ----------- | ---------- | ------------- | ------------ | ------------- |
473| 1 | 0 | 0.011...0.119 | 0 | 0.03...0.31 | 0 | 0.068...0.711 | 0 | 0.121...1.258 |
474| 2 | 2...8 | 0.007...0.042 | 10...40 | 0.02...0.11 | 120...480 | 0.045...0.252 | 2880...11520 | 0.081...0.446 |
475| 3 | 4...20 | 0.003...0.015 | 20...100 | 0.01...0.04 | 240...1200 | 0.022...0.091 | 5760...28800 | 0.040...0.162 |
476| 4 | 6...44 | 0.0 | 30...220 | 0.0 | 360...2640 | 0.0 | 8640...63360 | 0.0 |
477
478These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used.
479
480If you have the `generate_roi_table()` and `roi_space()` methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
481
482Override the `roi_space()` method if you need components of the ROI tables to vary in other ranges. Override the `generate_roi_table()` and `roi_space()` methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps).
483
484A sample for these methods can be found in [sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
485
486!!! Note "Reduced search space"
487 To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however [overriding pre-defined spaces](advanced-hyperopt.md#pverriding-pre-defined-spaces) to change this to your needs.
488
489### Understand Hyperopt Stoploss results
490
491If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss:
492
493```
494Best result:
495
496 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
497
498 # Buy hyperspace params:
499 buy_params = {
500 'buy_adx': 44,
501 'buy_rsi': 29,
502 'buy_adx_enabled': False,
503 'buy_rsi_enabled': True,
504 'buy_trigger': 'bb_lower'
505 }
506
507 stoploss: -0.27996
508```
509
510In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the `stoploss` attribute of your custom strategy:
511
512``` python
513 # Optimal stoploss designed for the strategy
514 # This attribute will be overridden if the config file contains "stoploss"
515 stoploss = -0.27996
516```
517
518As stated in the comment, you can also use it as the value of the `stoploss` setting in the configuration file.
519
520#### Default Stoploss Search Space
521
522If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace vary in the range -0.35...-0.02, which is sufficient in most cases.
523
524If you have the `stoploss_space()` method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.
525
526Override the `stoploss_space()` method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
527
528!!! Note "Reduced search space"
529 To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however [overriding pre-defined spaces](advanced-hyperopt.md#pverriding-pre-defined-spaces) to change this to your needs.
530
531### Understand Hyperopt Trailing Stop results
532
533If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters:
534
535```
536Best result:
537
538 45/100: 606 trades. Avg profit 1.04%. Total profit 0.31555614 BTC ( 630.48Σ%). Avg duration 150.3 mins. Objective: -1.10161
539
540 # Trailing stop:
541 trailing_stop = True
542 trailing_stop_positive = 0.02001
543 trailing_stop_positive_offset = 0.06038
544 trailing_only_offset_is_reached = True
545```
546
547In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:
548
549``` python
550 # Trailing stop
551 # These attributes will be overridden if the config file contains corresponding values.
552 trailing_stop = True
553 trailing_stop_positive = 0.02001
554 trailing_stop_positive_offset = 0.06038
555 trailing_only_offset_is_reached = True
556```
557
558As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.
559
560#### Default Trailing Stop Search Space
561
562If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the `trailing_stop` parameter is always set to True in that hyperspace, the value of the `trailing_only_offset_is_reached` vary between True and False, the values of the `trailing_stop_positive` and `trailing_stop_positive_offset` parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases.
563
564Override the `trailing_space()` method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in [user_data/hyperopts/sample_hyperopt_advanced.py](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_advanced.py).
565
566!!! Note "Reduced search space"
567 To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however [overriding pre-defined spaces](advanced-hyperopt.md#pverriding-pre-defined-spaces) to change this to your needs.
568
569### Reproducible results
570
571The search for optimal parameters starts with a few (currently 30) random combinations in the hyperspace of parameters, random Hyperopt epochs. These random epochs are marked with an asterisk character (`*`) in the first column in the Hyperopt output.
572
573The initial state for generation of these random values (random state) is controlled by the value of the `--random-state` command line option. You can set it to some arbitrary value of your choice to obtain reproducible results.
574
575If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the `--random-state` command line option to repeat the set of the initial random epochs used.
576
577If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyper-optimization results with same random state value used.
578
579## Output formatting
580
581By default, hyperopt prints colorized results -- epochs with positive profit are printed in the green color. This highlighting helps you find epochs that can be interesting for later analysis. Epochs with zero total profit or with negative profits (losses) are printed in the normal color. If you do not need colorization of results (for instance, when you are redirecting hyperopt output to a file) you can switch colorization off by specifying the `--no-color` option in the command line.
582
583You can use the `--print-all` command line option if you would like to see all results in the hyperopt output, not only the best ones. When `--print-all` is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the `--no-color` command line option.
584
585!!! Note "Windows and color output"
586 Windows does not support color-output natively, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL.
587
588## Position stacking and disabling max market positions
589
590In some situations, you may need to run Hyperopt (and Backtesting) with the
591`--eps`/`--enable-position-staking` and `--dmmp`/`--disable-max-market-positions` arguments.
592
593By default, hyperopt emulates the behavior of the Freqtrade Live Run/Dry Run, where only one
594open trade is allowed for every traded pair. The total number of trades open for all pairs
595is also limited by the `max_open_trades` setting. During Hyperopt/Backtesting this may lead to
596some potential trades to be hidden (or masked) by previously open trades.
597
598The `--eps`/`--enable-position-stacking` argument allows emulation of buying the same pair multiple times,
599while `--dmmp`/`--disable-max-market-positions` disables applying `max_open_trades`
600during Hyperopt/Backtesting (which is equal to setting `max_open_trades` to a very high
601number).
602
603!!! Note
604 Dry/live runs will **NOT** use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
605
606You can also enable position stacking in the configuration file by explicitly setting
607`"position_stacking"=true`.
608
609## Show details of Hyperopt results
610
611After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the `hyperopt-list` and `hyperopt-show` sub-commands. The usage of these sub-commands is described in the [Utils](utils.md#list-hyperopt-results) chapter.
612
613## Validate backtesting results
614
615Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
616
617To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt `--dmmp`/`--disable-max-market-positions` and `--eps`/`--enable-position-stacking` for Backtesting.
618
619Should results don't match, please double-check to make sure you transferred all conditions correctly.
620Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy.
621You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like `stoploss` or `trailing_stop`).