Merge branch 'develop' into dev-merge-rl

This commit is contained in:
robcaulk 2022-09-04 11:23:25 +02:00
commit 69b3fcfd32
97 changed files with 1710 additions and 958 deletions

View File

@ -11,7 +11,7 @@ ENV FT_APP_ENV="docker"
# Prepare environment # Prepare environment
RUN mkdir /freqtrade \ RUN mkdir /freqtrade \
&& apt-get update \ && apt-get update \
&& apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev \ && apt-get -y install sudo libatlas3-base curl sqlite3 libhdf5-serial-dev libgomp1 \
&& apt-get clean \ && apt-get clean \
&& useradd -u 1000 -G sudo -U -m -s /bin/bash ftuser \ && useradd -u 1000 -G sudo -U -m -s /bin/bash ftuser \
&& chown ftuser:ftuser /freqtrade \ && chown ftuser:ftuser /freqtrade \

View File

@ -130,7 +130,7 @@ Telegram is not mandatory. However, this is a great way to control your bot. Mor
- `/start`: Starts the trader. - `/start`: Starts the trader.
- `/stop`: Stops the trader. - `/stop`: Stops the trader.
- `/stopbuy`: Stop entering new trades. - `/stopentry`: Stop entering new trades.
- `/status <trade_id>|[table]`: Lists all or specific open trades. - `/status <trade_id>|[table]`: Lists all or specific open trades.
- `/profit [<n>]`: Lists cumulative profit from all finished trades, over the last n days. - `/profit [<n>]`: Lists cumulative profit from all finished trades, over the last n days.
- `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`). - `/forceexit <trade_id>|all`: Instantly exits the given trade (Ignoring `minimum_roi`).

View File

@ -53,7 +53,6 @@
], ],
"freqai": { "freqai": {
"enabled": true, "enabled": true,
"startup_candles": 10000,
"purge_old_models": true, "purge_old_models": true,
"train_period_days": 15, "train_period_days": 15,
"backtest_period_days": 7, "backtest_period_days": 7,
@ -75,9 +74,10 @@
"weight_factor": 0.9, "weight_factor": 0.9,
"principal_component_analysis": false, "principal_component_analysis": false,
"use_SVM_to_remove_outliers": true, "use_SVM_to_remove_outliers": true,
"stratify_training_data": 0, "indicator_periods_candles": [
"indicator_max_period_candles": 20, 10,
"indicator_periods_candles": [10, 20] 20
]
}, },
"data_split_parameters": { "data_split_parameters": {
"test_size": 0.33, "test_size": 0.33,

View File

@ -64,8 +64,8 @@
"stoploss_on_exchange_limit_ratio": 0.99 "stoploss_on_exchange_limit_ratio": 0.99
}, },
"order_time_in_force": { "order_time_in_force": {
"entry": "gtc", "entry": "GTC",
"exit": "gtc" "exit": "GTC"
}, },
"pairlists": [ "pairlists": [
{"method": "StaticPairList"}, {"method": "StaticPairList"},

BIN
docs/assets/freqai_DI.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 MiB

BIN
docs/assets/freqai_algo.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

View File

@ -561,6 +561,14 @@ BTC trades at 22.000\$ today (0.001 BTC is related to this) - but the backtestin
Today's minimum would be `0.001 * 22_000` - or 22\$. Today's minimum would be `0.001 * 22_000` - or 22\$.
However the limit could also be 50$ - based on `0.001 * 50_000` in some historic setting. However the limit could also be 50$ - based on `0.001 * 50_000` in some historic setting.
#### Trading precision limits
Most exchanges pose precision limits on both price and amounts, so you cannot buy 1.0020401 of a pair, or at a price of 1.24567123123.
Instead, these prices and amounts will be rounded or truncated (based on the exchange definition) to the defined trading precision.
The above values may for example be rounded to an amount of 1.002, and a price of 1.24567.
These precision values are based on current exchange limits (as described in the [above section](#trading-limits-in-backtesting)), as historic precision limits are not available.
## Improved backtest accuracy ## Improved backtest accuracy
One big limitation of backtesting is it's inability to know how prices moved intra-candle (was high before close, or viceversa?). One big limitation of backtesting is it's inability to know how prices moved intra-candle (was high before close, or viceversa?).

View File

@ -70,7 +70,7 @@ This loop will be repeated again and again until the bot is stopped.
* Determine stake size by calling the `custom_stake_amount()` callback. * Determine stake size by calling the `custom_stake_amount()` callback.
* Check position adjustments for open trades if enabled and call `adjust_trade_position()` to determine if an additional order is requested. * Check position adjustments for open trades if enabled and call `adjust_trade_position()` to determine if an additional order is requested.
* Call `custom_stoploss()` and `custom_exit()` to find custom exit points. * Call `custom_stoploss()` and `custom_exit()` to find custom exit points.
* For exits based on exit-signal and custom-exit: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle). * For exits based on exit-signal, custom-exit and partial exits: Call `custom_exit_price()` to determine exit price (Prices are moved to be within the closing candle).
* Generate backtest report output * Generate backtest report output
!!! Note !!! Note

View File

@ -57,10 +57,21 @@ You can specify additional configuration files in `add_config_files`. Files spec
This is similar to using multiple `--config` parameters, but simpler in usage as you don't have to specify all files for all commands. This is similar to using multiple `--config` parameters, but simpler in usage as you don't have to specify all files for all commands.
!!! Tip "Use multiple configuration files to keep secrets secret" !!! Tip "Use multiple configuration files to keep secrets secret"
You can use a 2nd configuration file containing your secrets. That way you can share your "primary" configuration file, while still keeping your API keys for yourself. You can use a 2nd configuration file containing your secrets. That way you can share your "primary" configuration file, while still keeping your API keys for yourself.
The 2nd file should only specify what you intend to override.
If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, `config-private.json`).
For one-off commands, you can also use the below syntax by specifying multiple "--config" parameters.
``` bash
freqtrade trade --config user_data/config1.json --config user_data/config-private.json <...>
```
The below is equivalent to the example above - but having 2 configuration files in the configuration, for easier reuse.
``` json title="user_data/config.json" ``` json title="user_data/config.json"
"add_config_files": [ "add_config_files": [
"config1.json",
"config-private.json" "config-private.json"
] ]
``` ```
@ -69,17 +80,6 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
freqtrade trade --config user_data/config.json <...> freqtrade trade --config user_data/config.json <...>
``` ```
The 2nd file should only specify what you intend to override.
If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, `config-private.json`).
For one-off commands, you can also use the below syntax by specifying multiple "--config" parameters.
``` bash
freqtrade trade --config user_data/config.json --config user_data/config-private.json <...>
```
This is equivalent to the example above - but `config-private.json` is specified as cli argument.
??? Note "config collision handling" ??? Note "config collision handling"
If the same configuration setting takes place in both `config.json` and `config-import.json`, then the parent configuration wins. If the same configuration setting takes place in both `config.json` and `config-import.json`, then the parent configuration wins.
In the below case, `max_open_trades` would be 3 after the merging - as the reusable "import" configuration has this key overwritten. In the below case, `max_open_trades` would be 3 after the merging - as the reusable "import" configuration has this key overwritten.
@ -110,6 +110,8 @@ This is similar to using multiple `--config` parameters, but simpler in usage as
"stake_amount": "unlimited" "stake_amount": "unlimited"
} }
``` ```
If multiple files are in the `add_config_files` section, then they will be assumed to be at identical levels, having the last occurrence override the earlier config (unless a parent already defined such a key).
## Configuration parameters ## Configuration parameters
@ -525,21 +527,28 @@ It means if the order is not executed immediately AND fully then it is cancelled
It is the same as FOK (above) except it can be partially fulfilled. The remaining part It is the same as FOK (above) except it can be partially fulfilled. The remaining part
is automatically cancelled by the exchange. is automatically cancelled by the exchange.
The `order_time_in_force` parameter contains a dict with buy and sell time in force policy values. **PO (Post only):**
Post only order. The order is either placed as a maker order, or it is canceled.
This means the order must be placed on orderbook for at at least time in an unfilled state.
#### time_in_force config
The `order_time_in_force` parameter contains a dict with entry and exit time in force policy values.
This can be set in the configuration file or in the strategy. This can be set in the configuration file or in the strategy.
Values set in the configuration file overwrites values set in the strategy. Values set in the configuration file overwrites values set in the strategy.
The possible values are: `gtc` (default), `fok` or `ioc`. The possible values are: `GTC` (default), `FOK` or `IOC`.
``` python ``` python
"order_time_in_force": { "order_time_in_force": {
"entry": "gtc", "entry": "GTC",
"exit": "gtc" "exit": "GTC"
}, },
``` ```
!!! Warning !!! Warning
This is ongoing work. For now, it is supported only for binance and kucoin. This is ongoing work. For now, it is supported only for binance, gate, ftx and kucoin.
Please don't change the default value unless you know what you are doing and have researched the impact of using different values for your particular exchange. Please don't change the default value unless you know what you are doing and have researched the impact of using different values for your particular exchange.
### What values can be used for fiat_display_currency? ### What values can be used for fiat_display_currency?

View File

@ -63,7 +63,7 @@ optional arguments:
`jsongz`). `jsongz`).
--trading-mode {spot,margin,futures} --trading-mode {spot,margin,futures}
Select Trading mode Select Trading mode
--prepend Allow data prepending. --prepend Allow data prepending. (Data-appending is disabled)
Common arguments: Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages). -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).

View File

@ -409,8 +409,9 @@ Determine if crucial bugfixes have been made between this commit and the current
* Merge the release branch (stable) into this branch. * Merge the release branch (stable) into this branch.
* Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi. * Edit `freqtrade/__init__.py` and add the version matching the current date (for example `2019.7` for July 2019). Minor versions can be `2019.7.1` should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
* Commit this part * Commit this part.
* push that branch to the remote and create a PR against the stable branch * push that branch to the remote and create a PR against the stable branch.
* Update develop version to next version following the pattern `2019.8-dev`.
### Create changelog from git commits ### Create changelog from git commits

View File

@ -61,8 +61,8 @@ Binance supports [time_in_force](configuration.md#understand-order_time_in_force
### Binance Blacklist ### Binance Blacklist
For Binance, please add `"BNB/<STAKE>"` to your blacklist to avoid issues. For Binance, it is suggested to add `"BNB/<STAKE>"` to your blacklist to avoid issues, unless you are willing to maintain enough extra `BNB` on the account or unless you're willing to disable using `BNB` for fees.
Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on `BNB`, further trades will consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore. Binance accounts may use `BNB` for fees, and if a trade happens to be on `BNB`, further trades may consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore.
### Binance Futures ### Binance Futures
@ -205,8 +205,8 @@ Kucoin supports [time_in_force](configuration.md#understand-order_time_in_force)
### Kucoin Blacklists ### Kucoin Blacklists
For Kucoin, please add `"KCS/<STAKE>"` to your blacklist to avoid issues. For Kucoin, it is suggested to add `"KCS/<STAKE>"` to your blacklist to avoid issues, unless you are willing to maintain enough extra `KCS` on the account or unless you're willing to disable using `KCS` for fees.
Accounts having KCS accounts use this to pay for fees - if your first trade happens to be on `KCS`, further trades will consume this position and make the initial KCS trade unsellable as the expected amount is not there anymore. Kucoin accounts may use `KCS` for fees, and if a trade happens to be on `KCS`, further trades may consume this position and make the initial `KCS` trade unsellable as the expected amount is not there anymore.
## Huobi ## Huobi
@ -278,7 +278,7 @@ For example, to test the order type `FOK` with Kraken, and modify candle limit t
"exchange": { "exchange": {
"name": "kraken", "name": "kraken",
"_ft_has_params": { "_ft_has_params": {
"order_time_in_force": ["gtc", "fok"], "order_time_in_force": ["GTC", "FOK"],
"ohlcv_candle_limit": 200 "ohlcv_candle_limit": 200
} }
//... //...

View File

@ -77,9 +77,9 @@ Freqtrade will not provide incomplete candles to strategies. Using incomplete ca
You can use "current" market data by using the [dataprovider](strategy-customization.md#orderbookpair-maximum)'s orderbook or ticker methods - which however cannot be used during backtesting. You can use "current" market data by using the [dataprovider](strategy-customization.md#orderbookpair-maximum)'s orderbook or ticker methods - which however cannot be used during backtesting.
### Is there a setting to only SELL the coins being held and not perform anymore BUYS? ### Is there a setting to only Exit the trades being held and not perform any new Entries?
You can use the `/stopbuy` command in Telegram to prevent future buys, followed by `/forceexit all` (sell all open trades). You can use the `/stopentry` command in Telegram to prevent future trade entry, followed by `/forceexit all` (sell all open trades).
### I want to run multiple bots on the same machine ### I want to run multiple bots on the same machine

View File

@ -38,14 +38,14 @@ The example strategy, example prediction model, and example config can be found
The user provides FreqAI with a set of custom *base* indicators (the same way as in a typical Freqtrade strategy) as well as target values (*labels*). The user provides FreqAI with a set of custom *base* indicators (the same way as in a typical Freqtrade strategy) as well as target values (*labels*).
FreqAI trains a model to predict the target values based on the input of custom indicators, for each pair in the whitelist. These models are consistently retrained to adapt to market conditions. FreqAI offers the ability to both backtest strategies (emulating reality with periodic retraining) and deploy dry/live runs. In dry/live conditions, FreqAI can be set to constant retraining in a background thread in an effort to keep models as up to date as possible. FreqAI trains a model to predict the target values based on the input of custom indicators, for each pair in the whitelist. These models are consistently retrained to adapt to market conditions. FreqAI offers the ability to both backtest strategies (emulating reality with periodic retraining) and deploy dry/live runs. In dry/live conditions, FreqAI can be set to constant retraining in a background thread in an effort to keep models as up to date as possible.
An overview of the algorithm is shown below, explaining the data processing pipeline and the model usage. An overview of the algorithm is shown below, explaining the data processing pipeline and the model usage.
![freqai-algo](assets/freqai_algo.png) ![freqai-algo](assets/freqai_algo.jpg)
### Important machine learning vocabulary ### Important machine learning vocabulary
**Features** - the quantities with which a model is trained. All features for a single candle is stored as a vector. In FreqAI, the user **Features** - the quantities with which a model is trained. All features for a single candle is stored as a vector. In FreqAI, the user
builds the feature sets from anything they can construct in the strategy. builds the feature sets from anything they can construct in the strategy.
**Labels** - the target values that a model is trained **Labels** - the target values that a model is trained
toward. Each set of features is associated with a single label that is toward. Each set of features is associated with a single label that is
@ -53,12 +53,12 @@ defined by the user within the strategy. These labels intentionally look into th
future, and are not available to the model during dry/live/backtesting. future, and are not available to the model during dry/live/backtesting.
**Training** - the process of feeding individual feature sets, composed of historic data, with associated labels into the **Training** - the process of feeding individual feature sets, composed of historic data, with associated labels into the
model with the goal of matching input feature sets to associated labels. model with the goal of matching input feature sets to associated labels.
**Train data** - a subset of the historic data that is fed to the model during **Train data** - a subset of the historic data that is fed to the model during
training. This data directly influences weight connections in the model. training. This data directly influences weight connections in the model.
**Test data** - a subset of the historic data that is used to evaluate the performance of the model after training. This data does not influence nodal weights within the model. **Test data** - a subset of the historic data that is used to evaluate the performance of the model after training. This data does not influence nodal weights within the model.
## Install prerequisites ## Install prerequisites
@ -89,10 +89,10 @@ Mandatory parameters are marked as **Required**, which means that they are requi
|------------|-------------| |------------|-------------|
| | **General configuration parameters** | | **General configuration parameters**
| `freqai` | **Required.** <br> The parent dictionary containing all the parameters for controlling FreqAI. <br> **Datatype:** Dictionary. | `freqai` | **Required.** <br> The parent dictionary containing all the parameters for controlling FreqAI. <br> **Datatype:** Dictionary.
| `startup_candles` | Number of candles needed for *backtesting only* to ensure all indicators are non NaNs at the start of the first train period. <br> **Datatype:** Positive integer.
| `purge_old_models` | Delete obsolete models (otherwise, all historic models will remain on disk). <br> **Datatype:** Boolean. Default: `False`. | `purge_old_models` | Delete obsolete models (otherwise, all historic models will remain on disk). <br> **Datatype:** Boolean. Default: `False`.
| `train_period_days` | **Required.** <br> Number of days to use for the training data (width of the sliding window). <br> **Datatype:** Positive integer. | `train_period_days` | **Required.** <br> Number of days to use for the training data (width of the sliding window). <br> **Datatype:** Positive integer.
| `backtest_period_days` | **Required.** <br> Number of days to inference from the trained model before sliding the window defined above, and retraining the model. This can be fractional days, but beware that the user-provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float. | `backtest_period_days` | **Required.** <br> Number of days to inference from the trained model before sliding the window defined above, and retraining the model. This can be fractional days, but beware that the user-provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float.
| `save_backtest_models` | Backtesting operates most efficiently by saving the prediction data and reusing them directly for subsequent runs (when users wish to tune entry/exit parameters). If a user wishes to save models to disk when running backtesting, they should activate `save_backtest_models`. A user may wish to do this if they plan to use the same model files for starting a dry/live instance with the same `identifier`. <br> **Datatype:** Boolean. Default: `False`.
| `identifier` | **Required.** <br> A unique name for the current model. This can be reused to reload pre-trained models/data. <br> **Datatype:** String. | `identifier` | **Required.** <br> A unique name for the current model. This can be reused to reload pre-trained models/data. <br> **Datatype:** String.
| `live_retrain_hours` | Frequency of retraining during dry/live runs. <br> Default set to 0, which means the model will retrain as often as possible. <br> **Datatype:** Float > 0. | `live_retrain_hours` | Frequency of retraining during dry/live runs. <br> Default set to 0, which means the model will retrain as often as possible. <br> **Datatype:** Float > 0.
| `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old. <br> Defaults set to 0, which means models never expire. <br> **Datatype:** Positive integer. | `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old. <br> Defaults set to 0, which means models never expire. <br> **Datatype:** Positive integer.
@ -104,19 +104,21 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `include_corr_pairlist` | A list of correlated coins that FreqAI will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` during feature engineering (see details [here](#feature-engineering)) will be created for each coin in this list, and that set of features is added to the base asset feature set. <br> **Datatype:** List of assets (strings). | `include_corr_pairlist` | A list of correlated coins that FreqAI will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` during feature engineering (see details [here](#feature-engineering)) will be created for each coin in this list, and that set of features is added to the base asset feature set. <br> **Datatype:** List of assets (strings).
| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators` (see `templates/FreqaiExampleStrategy.py` for detailed usage). The user can create custom labels, making use of this parameter or not. <br> **Datatype:** Positive integer. | `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators` (see `templates/FreqaiExampleStrategy.py` for detailed usage). The user can create custom labels, making use of this parameter or not. <br> **Datatype:** Positive integer.
| `include_shifted_candles` | Add features from previous candles to subsequent candles to add historical information. FreqAI takes all features from the `include_shifted_candles` previous candles, duplicates and shifts them so that the information is available for the subsequent candle. <br> **Datatype:** Positive integer. | `include_shifted_candles` | Add features from previous candles to subsequent candles to add historical information. FreqAI takes all features from the `include_shifted_candles` previous candles, duplicates and shifts them so that the information is available for the subsequent candle. <br> **Datatype:** Positive integer.
| `weight_factor` | Used to set weights for training data points according to their recency. See details about how it works [here](#controlling-the-model-learning-process). <br> **Datatype:** Positive float (typically < 1). | `weight_factor` | Used to set weights for training data points according to their recency. See details about how it works [here](#controlling-the-model-learning-process). <br> **Datatype:** Positive float (typically < 1).
| `indicator_max_period_candles` | The maximum period used in `populate_any_indicators()` for indicator creation. FreqAI uses this information in combination with the maximum timeframe to calculate how many data points that should be downloaded so that the first data point does not have a NaN. <br> **Datatype:** Positive integer. | `indicator_max_period_candles` | **No longer used**. User must use the strategy set `startup_candle_count` which defines the maximum *period* used in `populate_any_indicators()` for indicator creation (timeframe independent). FreqAI uses this information in combination with the maximum timeframe to calculate how many data points it should download so that the first data point does not have a NaN <br> **Datatype:** positive integer.
| `indicator_periods_candles` | Calculate indicators for `indicator_periods_candles` time periods and add them to the feature set. <br> **Datatype:** List of positive integers. | `indicator_periods_candles` | Calculate indicators for `indicator_periods_candles` time periods and add them to the feature set. <br> **Datatype:** List of positive integers.
| `stratify_training_data` | This value is used to indicate the grouping of the data. For example, 2 would set every 2nd data point into a separate dataset to be pulled from during training/testing. See details about how it works [here](#stratifying-the-data-for-training-and-testing-the-model) <br> **Datatype:** Positive integer. | `stratify_training_data` | This value is used to indicate the grouping of the data. For example, 2 would set every 2nd data point into a separate dataset to be pulled from during training/testing. See details about how it works [here](#stratifying-the-data-for-training-and-testing-the-model) <br> **Datatype:** Positive integer.
| `principal_component_analysis` | Automatically reduce the dimensionality of the data set using Principal Component Analysis. See details about how it works [here](#reducing-data-dimensionality-with-principal-component-analysis) <br> **Datatype:** Boolean. | `principal_component_analysis` | Automatically reduce the dimensionality of the data set using Principal Component Analysis. See details about how it works [here](#reducing-data-dimensionality-with-principal-component-analysis) <br> **Datatype:** Boolean.
| `DI_threshold` | Activates the Dissimilarity Index for outlier detection when > 0. See details about how it works [here](#removing-outliers-with-the-dissimilarity-index). <br> **Datatype:** Positive float (typically < 1). | `DI_threshold` | Activates the Dissimilarity Index for outlier detection when > 0. See details about how it works [here](#removing-outliers-with-the-dissimilarity-index). <br> **Datatype:** Positive float (typically < 1).
| `use_SVM_to_remove_outliers` | Train a support vector machine to detect and remove outliers from the training data set, as well as from incoming data points. See details about how it works [here](#removing-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Boolean. | `use_SVM_to_remove_outliers` | Train a support vector machine to detect and remove outliers from the training data set, as well as from incoming data points. See details about how it works [here](#removing-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Boolean.
| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. See details about some select parameters [here](#removing-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Dictionary. | `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. See details about some select parameters [here](#removing-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Dictionary.
| `use_DBSCAN_to_remove_outliers` | Cluster data using DBSCAN to identify and remove outliers from training and prediction data. See details about how it works [here](#removing-outliers-with-dbscan). <br> **Datatype:** Boolean. | `use_DBSCAN_to_remove_outliers` | Cluster data using DBSCAN to identify and remove outliers from training and prediction data. See details about how it works [here](#removing-outliers-with-dbscan). <br> **Datatype:** Boolean.
| `outlier_protection_percentage` | If more than `outlier_protection_percentage` fraction of points are removed as outliers, FreqAI will log a warning message and ignore outlier detection while keeping the original dataset intact. <br> **Datatype:** float. Default: `30`
| `reverse_train_test_order` | If true, FreqAI will train on the latest data split and test on historical split of the data. This allows the model to be trained up to the most recent data point, while avoiding overfitting. However, users should be careful to understand unorthodox nature of this parameter before employing it. <br> **Datatype:** bool. Default: False
| | **Data split parameters** | | **Data split parameters**
| `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website). <br> **Datatype:** Dictionary. | `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website). <br> **Datatype:** Dictionary.
| `test_size` | Fraction of data that should be used for testing instead of training. <br> **Datatype:** Positive float < 1. | `test_size` | Fraction of data that should be used for testing instead of training. <br> **Datatype:** Positive float < 1.
| `shuffle` | Shuffle the training data points during training. Typically, for time-series forecasting, this is set to `False`. <br> | `shuffle` | Shuffle the training data points during training. Typically, for time-series forecasting, this is set to `False`. <br>
| | **Model training parameters** | | **Model training parameters**
| `model_training_parameters` | A flexible dictionary that includes all parameters available by the user selected model library. For example, if the user uses `LightGBMRegressor`, this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html) (external website). If the user selects a different model, such as `PPO` from stable_baselines3, this dictionary can contain any parameter from that model. <br> **Datatype:** Dictionary | `model_training_parameters` | A flexible dictionary that includes all parameters available by the user selected model library. For example, if the user uses `LightGBMRegressor`, this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html) (external website). If the user selects a different model, such as `PPO` from stable_baselines3, this dictionary can contain any parameter from that model. <br> **Datatype:** Dictionary
| `n_estimators` | The number of boosted trees to fit in regression. <br> **Datatype:** Integer. | `n_estimators` | The number of boosted trees to fit in regression. <br> **Datatype:** Integer.
@ -175,7 +177,6 @@ The user interface is isolated to the typical Freqtrade config file. A FreqAI co
], ],
"label_period_candles": 24, "label_period_candles": 24,
"include_shifted_candles": 2, "include_shifted_candles": 2,
"indicator_max_period_candles": 20,
"indicator_periods_candles": [10, 20] "indicator_periods_candles": [10, 20]
}, },
"data_split_parameters" : { "data_split_parameters" : {
@ -192,6 +193,9 @@ The user interface is isolated to the typical Freqtrade config file. A FreqAI co
The FreqAI strategy requires the user to include the following lines of code in the standard Freqtrade strategy: The FreqAI strategy requires the user to include the following lines of code in the standard Freqtrade strategy:
```python ```python
# user should define the maximum startup candle count (the largest number of candles
# passed to any single indicator)
startup_candle_count: int = 20
def informative_pairs(self): def informative_pairs(self):
whitelist_pairs = self.dp.current_whitelist() whitelist_pairs = self.dp.current_whitelist()
@ -208,9 +212,9 @@ The FreqAI strategy requires the user to include the following lines of code in
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# the model will return all labels created by user in `populate_any_indicators` # the model will return all labels created by user in `populate_any_indicators`
# (& appended targets), an indication of whether or not the prediction should be accepted, # (& appended targets), an indication of whether or not the prediction should be accepted,
# the target mean/std values for each of the labels created by user in # the target mean/std values for each of the labels created by user in
# `populate_any_indicators()` for each training period. # `populate_any_indicators()` for each training period.
dataframe = self.freqai.start(dataframe, metadata, self) dataframe = self.freqai.start(dataframe, metadata, self)
@ -285,6 +289,17 @@ The FreqAI strategy requires the user to include the following lines of code in
Notice how the `populate_any_indicators()` is where the user adds their own features ([more information](#feature-engineering)) and labels ([more information](#setting-classifier-targets)). See a full example at `templates/FreqaiExampleStrategy.py`. Notice how the `populate_any_indicators()` is where the user adds their own features ([more information](#feature-engineering)) and labels ([more information](#setting-classifier-targets)). See a full example at `templates/FreqaiExampleStrategy.py`.
### Setting the `startup_candle_count`
Users need to take care to set the `startup_candle_count` in their strategy the same way they would for any normal Freqtrade strategy (see details [here](strategy-customization.md/#strategy-startup-period)). This value is used by Freqtrade to ensure that a sufficient amount of data is provided when calling on the `dataprovider` to avoid any NaNs at the beginning of the first training. Users can easily set this value by identifying the longest period (in candle units) that they pass to their indicator creation functions (e.g. talib functions). In the present example, the user would pass 20 to as this value (since it is the maximum value in their `indicators_periods_candles`).
!!! Note
Typically it is best for users to be safe and multiply their expected `startup_candle_count` by 2. There are instances where the talib functions actually require more data than just the passed `period`. Anecdotally, multiplying the `startup_candle_count` by 2 always leads to a fully NaN free training dataset. Look out for this log message to confirm that your data is clean:
```
2022-08-31 15:14:04 - freqtrade.freqai.data_kitchen - INFO - dropped 0 training points due to NaNs in populated dataset 4319.
```
## Creating a dynamic target ## Creating a dynamic target
The `&*_std/mean` return values describe the statistical fit of the user defined label *during the most recent training*. This value allows the user to know the rarity of a given prediction. For example, `templates/FreqaiExampleStrategy.py`, creates a `target_roi` which is based on filtering out predictions that are below a given z-score of 1.25. The `&*_std/mean` return values describe the statistical fit of the user defined label *during the most recent training*. This value allows the user to know the rarity of a given prediction. For example, `templates/FreqaiExampleStrategy.py`, creates a `target_roi` which is based on filtering out predictions that are below a given z-score of 1.25.
@ -318,7 +333,7 @@ The user is encouraged to inherit `train()` and `predict()` to let them customiz
## Feature engineering ## Feature engineering
Features are added by the user inside the `populate_any_indicators()` method of the strategy Features are added by the user inside the `populate_any_indicators()` method of the strategy
by prepending indicators with `%`, and labels with `&`. by prepending indicators with `%`, and labels with `&`.
There are some important components/structures that the user *must* include when building their feature set; the use of these is shown below: There are some important components/structures that the user *must* include when building their feature set; the use of these is shown below:
@ -427,13 +442,13 @@ In total, the number of features the user of the presented example strat has cre
length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles` length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
$= 3 * 3 * 3 * 2 * 2 = 108$. $= 3 * 3 * 3 * 2 * 2 = 108$.
Another structure to consider is the location of the labels at the bottom of the example function (below `if set_generalized_indicators:`). Another structure to consider is the location of the labels at the bottom of the example function (below `if set_generalized_indicators:`).
This is where the user will add single features and labels to their feature set to avoid duplication of them from This is where the user will add single features and labels to their feature set to avoid duplication of them from
various configuration parameters that multiply the feature set, such as `include_timeframes`. various configuration parameters that multiply the feature set, such as `include_timeframes`.
!!! Note !!! Note
Features **must** be defined in `populate_any_indicators()`. Definining FreqAI features in `populate_indicators()` Features **must** be defined in `populate_any_indicators()`. Definining FreqAI features in `populate_indicators()`
will cause the algorithm to fail in live/dry mode. If the user wishes to add generalized features that are not associated with will cause the algorithm to fail in live/dry mode. If the user wishes to add generalized features that are not associated with
a specific pair or timeframe, they should use the following structure inside `populate_any_indicators()` a specific pair or timeframe, they should use the following structure inside `populate_any_indicators()`
(as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`): (as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`):
@ -442,7 +457,7 @@ various configuration parameters that multiply the feature set, such as `include
... ...
# Add generalized indicators here (because in live, it will call only this function to populate # Add generalized indicators here (because in live, it will call only this function to populate
# indicators for retraining). Notice how we ensure not to add them multiple times by associating # indicators for retraining). Notice how we ensure not to add them multiple times by associating
# these generalized indicators to the basepair/timeframe # these generalized indicators to the basepair/timeframe
if set_generalized_indicators: if set_generalized_indicators:
@ -478,7 +493,7 @@ Additionally, the example classifier models do not accommodate multiple labels,
There are two ways to train and deploy an adaptive machine learning model. FreqAI enables live deployment as well as backtesting analyses. In both cases, a model is trained periodically, as shown in the following figure. There are two ways to train and deploy an adaptive machine learning model. FreqAI enables live deployment as well as backtesting analyses. In both cases, a model is trained periodically, as shown in the following figure.
![freqai-window](assets/freqai_moving-window.png) ![freqai-window](assets/freqai_moving-window.jpg)
### Running the model live ### Running the model live
@ -510,7 +525,7 @@ and if a full `live_retrain_hours` has elapsed since the end of the loaded model
The FreqAI backtesting module can be executed with the following command: The FreqAI backtesting module can be executed with the following command:
```bash ```bash
freqtrade backtesting --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701 freqtrade backtesting --strategy FreqaiExampleStrategy --config config_examples/config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701
``` ```
Backtesting mode requires the user to have the data pre-downloaded (unlike in dry/live mode where FreqAI automatically downloads the necessary data). The user should be careful to consider that the time range of the downloaded data is more than the backtesting time range. This is because FreqAI needs data prior to the desired backtesting time range in order to train a model to be ready to make predictions on the first candle of the user-set backtesting time range. More details on how to calculate the data to download can be found [here](#deciding-the-sliding-training-window-and-backtesting-duration). Backtesting mode requires the user to have the data pre-downloaded (unlike in dry/live mode where FreqAI automatically downloads the necessary data). The user should be careful to consider that the time range of the downloaded data is more than the backtesting time range. This is because FreqAI needs data prior to the desired backtesting time range in order to train a model to be ready to make predictions on the first candle of the user-set backtesting time range. More details on how to calculate the data to download can be found [here](#deciding-the-sliding-training-window-and-backtesting-duration).
@ -537,23 +552,17 @@ the user is asking FreqAI to use a training period of 30 days and backtest on th
This means that if the user sets `--timerange 20210501-20210701`, This means that if the user sets `--timerange 20210501-20210701`,
FreqAI will train have trained 8 separate models at the end of `--timerange` (because the full range comprises 8 weeks). After the training of the model, FreqAI will backtest the subsequent 7 days. The "sliding window" then moves one week forward (emulating FreqAI retraining once per week in live mode) and the new model uses the previous 30 days (including the 7 days used for backtesting by the previous model) to train. This is repeated until the end of `--timerange`. FreqAI will train have trained 8 separate models at the end of `--timerange` (because the full range comprises 8 weeks). After the training of the model, FreqAI will backtest the subsequent 7 days. The "sliding window" then moves one week forward (emulating FreqAI retraining once per week in live mode) and the new model uses the previous 30 days (including the 7 days used for backtesting by the previous model) to train. This is repeated until the end of `--timerange`.
In live mode, the required training data is automatically computed and downloaded. However, in backtesting mode,
the user must manually enter the required number of `startup_candles` in the config. This value
is used to increase the data to FreqAI, which should be sufficient to enable all indicators
to be NaN free at the beginning of the first training. This is done by identifying the
longest timeframe (`4h` in presented example config) and the longest indicator period (`20` days in presented example config)
and adding this to the `train_period_days`. The units need to be in the base candle time frame:
`startup_candles` = ( 4 hours * 20 max period * 60 minutes/hour + 30 day train_period_days * 1440 minutes per day ) / 5 min (base time frame) = 9360.
!!! Note
In dry/live mode, this is all precomputed and handled automatically. Thus, `startup_candle` has no influence on dry/live mode.
!!! Note !!! Note
Although fractional `backtest_period_days` is allowed, the user should be aware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, if the user wants to set a `--timerange` of 10 days, and asks for a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. Because of this, a true backtest of FreqAI adaptive training would take a *very* long time. The best way to fully test a model is to run it dry and let it constantly train. In this case, backtesting would take the exact same amount of time as a dry run. Although fractional `backtest_period_days` is allowed, the user should be aware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, if the user wants to set a `--timerange` of 10 days, and asks for a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. Because of this, a true backtest of FreqAI adaptive training would take a *very* long time. The best way to fully test a model is to run it dry and let it constantly train. In this case, backtesting would take the exact same amount of time as a dry run.
### Downloading data for backtesting
Live/dry instances will download the data automatically for the user, but users who wish to use backtesting functionality still need to download the necessary data using `download-data` (details [here](data-download/#data-downloading)). FreqAI users need to pay careful attention to understanding how much *additional* data needs to be downloaded to ensure that they have a sufficient amount of training data *before* the start of their backtesting timerange. The amount of additional data can be roughly estimated by taking subtracting `train_period_days` and the `startup_candle_count` ([details](#setting-the-startupcandlecount)) from the beginning of the desired backtesting timerange.
As an example, if we wish to backtest the `--timerange` above of `20210501-20210701`, and we use the example config which sets `train_period_days` to 15. The startup candle count is 40 on a maximum `include_timeframes` of 1h. We would need 20210501 - 15 days - 40 * 1h / 24 hours = 20210414 (16.7 days earlier than the start of the desired training timerange).
### Defining model expirations ### Defining model expirations
During dry/live mode, FreqAI trains each coin pair sequentially (on separate threads/GPU from the main Freqtrade bot). This means that there is always an age discrepancy between models. If a user is training on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old. This may be undesirable if the characteristic time scale (the trade duration target) for a strategy is less than 4 hours. The user can decide to only make trade entries if the model is less than During dry/live mode, FreqAI trains each coin pair sequentially (on separate threads/GPU from the main Freqtrade bot). This means that there is always an age discrepancy between models. If a user is training on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old. This may be undesirable if the characteristic time scale (the trade duration target) for a strategy is less than 4 hours. The user can decide to only make trade entries if the model is less than
a certain number of hours old by setting the `expiration_hours` in the config file: a certain number of hours old by setting the `expiration_hours` in the config file:
```json ```json
@ -640,15 +649,15 @@ The user can stratify (group) the training/testing data using:
This will split the data chronologically so that every Xth data point is used to test the model after training. In the This will split the data chronologically so that every Xth data point is used to test the model after training. In the
example above, the user is asking for every third data point in the dataframe to be used for example above, the user is asking for every third data point in the dataframe to be used for
testing; the other points are used for training. testing; the other points are used for training.
The test data is used to evaluate the performance of the model after training. If the test score is high, the model is able to capture the behavior of the data well. If the test score is low, either the model either does not capture the complexity of the data, the test data is significantly different from the train data, or a different model should be used. The test data is used to evaluate the performance of the model after training. If the test score is high, the model is able to capture the behavior of the data well. If the test score is low, either the model either does not capture the complexity of the data, the test data is significantly different from the train data, or a different model should be used.
### Controlling the model learning process ### Controlling the model learning process
Model training parameters are unique to the machine learning library selected by the user. FreqAI allows the user to set any parameter for any library using the `model_training_parameters` dictionary in the user configuration file. The example configuration file (found in `config_examples/config_freqai.example.json`) show some of the example parameters associated with `Catboost` and `LightGBM`, but the user can add any parameters available in those libraries. Model training parameters are unique to the machine learning library selected by the user. FreqAI allows the user to set any parameter for any library using the `model_training_parameters` dictionary in the user configuration file. The example configuration file (found in `config_examples/config_freqai.example.json`) show some of the example parameters associated with `Catboost` and `LightGBM`, but the user can add any parameters available in those libraries.
Data split parameters are defined in `data_split_parameters` which can be any parameters associated with `Sklearn`'s `train_test_split()` function. Data split parameters are defined in `data_split_parameters` which can be any parameters associated with `Sklearn`'s `train_test_split()` function.
FreqAI includes some additional parameters such as `weight_factor`, which allows the user to weight more recent data more strongly FreqAI includes some additional parameters such as `weight_factor`, which allows the user to weight more recent data more strongly
than past data via an exponential function: than past data via an exponential function:
@ -657,7 +666,7 @@ $$ W_i = \exp(\frac{-i}{\alpha*n}) $$
where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. Below is a figure showing the effect of different weight factors on the data points (candles) in a feature set. where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. Below is a figure showing the effect of different weight factors on the data points (candles) in a feature set.
![weight-factor](assets/freqai_weight-factor.png) ![weight-factor](assets/freqai_weight-factor.jpg)
`train_test_split()` has a parameters called `shuffle` that allows the user to keep the data unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data. `train_test_split()` has a parameters called `shuffle` that allows the user to keep the data unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data.
@ -678,7 +687,7 @@ The user can tell FreqAI to remove outlier data points from the training/test da
} }
``` ```
Equity and crypto markets suffer from a high level of non-patterned noise in the form of outlier data points. The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each prediction made by the model. The DI allows predictions which are outliers (not existent in the model feature space) to be thrown out due to low levels of certainty. Equity and crypto markets suffer from a high level of non-patterned noise in the form of outlier data points. The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each prediction made by the model. The DI allows predictions which are outliers (not existent in the model feature space) to be thrown out due to low levels of certainty.
To do so, FreqAI measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points: To do so, FreqAI measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points:
@ -696,11 +705,11 @@ which enables the estimation of the Dissimilarity Index as:
$$ DI_k = d_k/\overline{d} $$ $$ DI_k = d_k/\overline{d} $$
The user can tweak the DI through the `DI_threshold` to increase or decrease the extrapolation of the trained model. The user can tweak the DI through the `DI_threshold` to increase or decrease the extrapolation of the trained model.
Below is a figure that describes the DI for a 3D data set. Below is a figure that describes the DI for a 3D data set.
![DI](assets/freqai_DI.png) ![DI](assets/freqai_DI.jpg)
#### Removing outliers using a Support Vector Machine (SVM) #### Removing outliers using a Support Vector Machine (SVM)
@ -715,11 +724,11 @@ The user can tell FreqAI to remove outlier data points from the training/test da
``` ```
FreqAI will train an SVM on the training data (or components of it if the user activated FreqAI will train an SVM on the training data (or components of it if the user activated
`principal_component_analysis`) and remove any data point that the SVM deems to be beyond the feature space. `principal_component_analysis`) and remove any data point that the SVM deems to be beyond the feature space.
The parameter `shuffle` is by default set to `False` to ensure consistent results. If it is set to `True`, running the SVM multiple times on the same data set might result in different outcomes due to `max_iter` being to low for the algorithm to reach the demanded `tol`. Increasing `max_iter` solves this issue but causes the procedure to take longer time. The parameter `shuffle` is by default set to `False` to ensure consistent results. If it is set to `True`, running the SVM multiple times on the same data set might result in different outcomes due to `max_iter` being to low for the algorithm to reach the demanded `tol`. Increasing `max_iter` solves this issue but causes the procedure to take longer time.
The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers. The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers.
#### Removing outliers with DBSCAN #### Removing outliers with DBSCAN
@ -737,7 +746,7 @@ DBSCAN is an unsupervised machine learning algorithm that clusters data without
Given a number of data points $N$, and a distance $\varepsilon$, DBSCAN clusters the data set by setting all data points that have $N-1$ other data points within a distance of $\varepsilon$ as *core points*. A data point that is within a distance of $\varepsilon$ from a *core point* but that does not have $N-1$ other data points within a distance of $\varepsilon$ from itself is considered an *edge point*. A cluster is then the collection of *core points* and *edge points*. Data points that have no other data points at a distance $<\varepsilon$ are considered outliers. The figure below shows a cluster with $N = 3$. Given a number of data points $N$, and a distance $\varepsilon$, DBSCAN clusters the data set by setting all data points that have $N-1$ other data points within a distance of $\varepsilon$ as *core points*. A data point that is within a distance of $\varepsilon$ from a *core point* but that does not have $N-1$ other data points within a distance of $\varepsilon$ from itself is considered an *edge point*. A cluster is then the collection of *core points* and *edge points*. Data points that have no other data points at a distance $<\varepsilon$ are considered outliers. The figure below shows a cluster with $N = 3$.
![dbscan](assets/freqai_dbscan.png) ![dbscan](assets/freqai_dbscan.jpg)
FreqAI uses `sklearn.cluster.DBSCAN` (details are available on scikit-learn's webpage [here](#https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html)) with `min_samples` ($N$) taken as double the no. of user-defined features, and `eps` ($\varepsilon$) taken as the longest distance in the *k-distance graph* computed from the nearest neighbors in the pairwise distances of all data points in the feature set. FreqAI uses `sklearn.cluster.DBSCAN` (details are available on scikit-learn's webpage [here](#https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html)) with `min_samples` ($N$) taken as double the no. of user-defined features, and `eps` ($\varepsilon$) taken as the longest distance in the *k-distance graph* computed from the nearest neighbors in the pairwise distances of all data points in the feature set.

View File

@ -40,7 +40,8 @@ pip install -r requirements-hyperopt.txt
``` ```
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--userdir PATH] [-s NAME] [--strategy-path PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH]
[--recursive-strategy-search] [-i TIMEFRAME] [--recursive-strategy-search] [--freqaimodel NAME]
[--freqaimodel-path PATH] [-i TIMEFRAME]
[--timerange TIMERANGE] [--timerange TIMERANGE]
[--data-format-ohlcv {json,jsongz,hdf5}] [--data-format-ohlcv {json,jsongz,hdf5}]
[--max-open-trades INT] [--max-open-trades INT]
@ -53,7 +54,7 @@ usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--print-all] [--no-color] [--print-json] [-j JOBS] [--print-all] [--no-color] [--print-json] [-j JOBS]
[--random-state INT] [--min-trades INT] [--random-state INT] [--min-trades INT]
[--hyperopt-loss NAME] [--disable-param-export] [--hyperopt-loss NAME] [--disable-param-export]
[--ignore-missing-spaces] [--ignore-missing-spaces] [--analyze-per-epoch]
optional arguments: optional arguments:
-h, --help show this help message and exit -h, --help show this help message and exit
@ -129,6 +130,7 @@ optional arguments:
--ignore-missing-spaces, --ignore-unparameterized-spaces --ignore-missing-spaces, --ignore-unparameterized-spaces
Suppress errors for any requested Hyperopt spaces that Suppress errors for any requested Hyperopt spaces that
do not contain any parameters. do not contain any parameters.
--analyze-per-epoch Run populate_indicators once per epoch.
Common arguments: Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages). -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
@ -154,6 +156,10 @@ Strategy arguments:
--recursive-strategy-search --recursive-strategy-search
Recursively search for a strategy in the strategies Recursively search for a strategy in the strategies
folder. folder.
--freqaimodel NAME Specify a custom freqaimodels.
--freqaimodel-path PATH
Specify additional lookup path for freqaimodels.
``` ```
### Hyperopt checklist ### Hyperopt checklist
@ -185,7 +191,7 @@ Rarely you may also need to create a [nested class](advanced-hyperopt.md#overrid
### Hyperopt execution logic ### Hyperopt execution logic
Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators. Hyperopt will first load your data into memory and will then run `populate_indicators()` once per Pair to generate all indicators, unless `--analyze-per-epoch` is specified.
Hyperopt will then spawn into different processes (number of processors, or `-j <n>`), and run backtesting over and over again, changing the parameters that are part of the `--spaces` defined. Hyperopt will then spawn into different processes (number of processors, or `-j <n>`), and run backtesting over and over again, changing the parameters that are part of the `--spaces` defined.
@ -426,9 +432,10 @@ While this strategy is most likely too simple to provide consistent profit, it s
`range` property may also be used with `DecimalParameter` and `CategoricalParameter`. `RealParameter` does not provide this property due to infinite search space. `range` property may also be used with `DecimalParameter` and `CategoricalParameter`. `RealParameter` does not provide this property due to infinite search space.
??? Hint "Performance tip" ??? Hint "Performance tip"
By doing the calculation of all possible indicators in `populate_indicators()`, the calculation of the indicator happens only once for every parameter. During normal hyperopting, indicators are calculated once and supplied to each epoch, linearly increasing RAM usage as a factor of increasing cores. As this also has performance implications, hyperopt provides `--analyze-per-epoch` which will move the execution of `populate_indicators()` to the epoch process, calculating a single value per parameter per epoch instead of using the `.range` functionality. In this case, `.range` functionality will only return the actually used value. This will reduce RAM usage, but increase CPU usage. However, your hyperopting run will be less likely to fail due to Out Of Memory (OOM) issues.
While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values).
You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space. In either case, you should try to use space ranges as small as possible this will improve CPU/RAM usage in both scenarios.
## Optimizing protections ## Optimizing protections
@ -879,6 +886,7 @@ To combat these, you have multiple options:
* Avoid using `--timeframe-detail` (this loads a lot of additional data into memory). * Avoid using `--timeframe-detail` (this loads a lot of additional data into memory).
* Reduce the number of parallel processes (`-j <n>`). * Reduce the number of parallel processes (`-j <n>`).
* Increase the memory of your machine. * Increase the memory of your machine.
* Use `--analyze-per-epoch` if you're using a lot of parameters with `.range` functionality.
## The objective has been evaluated at this point before. ## The objective has been evaluated at this point before.

View File

@ -13,7 +13,7 @@
Please only use advanced trading modes when you know how freqtrade (and your strategy) works. Please only use advanced trading modes when you know how freqtrade (and your strategy) works.
Also, never risk more than what you can afford to lose. Also, never risk more than what you can afford to lose.
Please read the [strategy migration guide](strategy_migration.md#strategy-migration-between-v2-and-v3) to migrate your strategy from a freqtrade v2 strategy, to v3 strategy that can short and trade futures. If you already have an existing strategy, please read the [strategy migration guide](strategy_migration.md#strategy-migration-between-v2-and-v3) to migrate your strategy from a freqtrade v2 strategy, to strategy of version 3 which can short and trade futures.
## Shorting ## Shorting
@ -62,6 +62,13 @@ You will also have to pick a "margin mode" (explanation below) - with freqtrade
"margin_mode": "isolated" "margin_mode": "isolated"
``` ```
##### Pair namings
Freqtrade follows the [ccxt naming conventions for futures](https://docs.ccxt.com/en/latest/manual.html?#perpetual-swap-perpetual-future).
A futures pair will therefore have the naming of `base/quote:settle` (e.g. `ETH/USDT:USDT`).
Binance is currently still an exception to this naming scheme, where pairs are named `ETH/USDT` also for futures markets, but will be aligned as soon as CCXT is ready.
### Margin mode ### Margin mode
On top of `trading_mode` - you will also have to configure your `margin_mode`. On top of `trading_mode` - you will also have to configure your `margin_mode`.

View File

@ -1,6 +1,6 @@
markdown==3.3.7 markdown==3.3.7
mkdocs==1.3.1 mkdocs==1.3.1
mkdocs-material==8.4.1 mkdocs-material==8.4.2
mdx_truly_sane_lists==1.3 mdx_truly_sane_lists==1.3
pymdown-extensions==9.5 pymdown-extensions==9.5
jinja2==3.1.2 jinja2==3.1.2

View File

@ -163,6 +163,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
| `strategy <strategy>` | Get specific Strategy content. **Alpha** | `strategy <strategy>` | Get specific Strategy content. **Alpha**
| `available_pairs` | List available backtest data. **Alpha** | `available_pairs` | List available backtest data. **Alpha**
| `version` | Show version. | `version` | Show version.
| `sysinfo` | Show informations about the system load.
| `health` | Show bot health (last bot loop).
!!! Warning "Alpha status" !!! Warning "Alpha status"
Endpoints labeled with *Alpha status* above may change at any time without notice. Endpoints labeled with *Alpha status* above may change at any time without notice.
@ -227,6 +229,11 @@ forceexit
Force-exit a trade. Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command) :param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
health
Provides a quick health check of the running bot.
locks locks
Return current locks Return current locks
@ -312,6 +319,7 @@ version
whitelist whitelist
Show the current whitelist. Show the current whitelist.
``` ```
### OpenAPI interface ### OpenAPI interface

View File

@ -423,7 +423,7 @@ class AwesomeStrategy(IStrategy):
!!! Warning "Backtesting" !!! Warning "Backtesting"
Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range. Custom prices are supported in backtesting (starting with 2021.12), and orders will fill if the price falls within the candle's low/high range.
Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle. Orders that don't fill immediately are subject to regular timeout handling, which happens once per (detail) candle.
`custom_exit_price()` is only called for sells of type exit_signal and Custom exit. All other exit-types will use regular backtesting prices. `custom_exit_price()` is only called for sells of type exit_signal, Custom exit and partial exits. All other exit-types will use regular backtesting prices.
## Custom order timeout rules ## Custom order timeout rules
@ -654,7 +654,7 @@ Position adjustments will always be applied in the direction of the trade, so a
Stoploss is still calculated from the initial opening price, not averaged price. Stoploss is still calculated from the initial opening price, not averaged price.
Regular stoploss rules still apply (cannot move down). Regular stoploss rules still apply (cannot move down).
While `/stopbuy` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades. While `/stopentry` command stops the bot from entering new trades, the position adjustment feature will continue buying new orders on existing trades.
!!! Warning "Backtesting" !!! Warning "Backtesting"
During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so run-time performance will be affected. During backtesting this callback is called for each candle in `timeframe` or `timeframe_detail`, so run-time performance will be affected.

View File

@ -166,7 +166,7 @@ Additional technical libraries can be installed as necessary, or custom indicato
Most indicators have an instable startup period, in which they are either not available (NaN), or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be. Most indicators have an instable startup period, in which they are either not available (NaN), or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be.
To account for this, the strategy can be assigned the `startup_candle_count` attribute. To account for this, the strategy can be assigned the `startup_candle_count` attribute.
This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In the case where a user includes higher timeframes with informative pairs, the `startup_candle_count` does not necessarily change. The value is the maximum period (in candles) that any of the informatives timeframes need to compute stable indicators.
In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles. In this example strategy, this should be set to 100 (`startup_candle_count = 100`), since the longest needed history is 100 candles.

View File

@ -332,8 +332,8 @@ After:
``` python hl_lines="2 3" ``` python hl_lines="2 3"
order_time_in_force: Dict = { order_time_in_force: Dict = {
"entry": "gtc", "entry": "GTC",
"exit": "gtc", "exit": "GTC",
} }
``` ```

View File

@ -149,7 +149,7 @@ You can create your own keyboard in `config.json`:
!!! Note "Supported Commands" !!! Note "Supported Commands"
Only the following commands are allowed. Command arguments are not supported! Only the following commands are allowed. Command arguments are not supported!
`/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopbuy`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version` `/start`, `/stop`, `/status`, `/status table`, `/trades`, `/profit`, `/performance`, `/daily`, `/stats`, `/count`, `/locks`, `/balance`, `/stopentry`, `/reload_config`, `/show_config`, `/logs`, `/whitelist`, `/blacklist`, `/edge`, `/help`, `/version`
## Telegram commands ## Telegram commands
@ -161,7 +161,7 @@ official commands. You can ask at any moment for help with `/help`.
|----------|-------------| |----------|-------------|
| `/start` | Starts the trader | `/start` | Starts the trader
| `/stop` | Stops the trader | `/stop` | Stops the trader
| `/stopbuy` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules. | `/stopbuy | /stopentry` | Stops the trader from opening new trades. Gracefully closes open trades according to their rules.
| `/reload_config` | Reloads the configuration file | `/reload_config` | Reloads the configuration file
| `/show_config` | Shows part of the current configuration with relevant settings to operation | `/show_config` | Shows part of the current configuration with relevant settings to operation
| `/logs [limit]` | Show last log messages. | `/logs [limit]` | Show last log messages.

View File

@ -1,5 +1,5 @@
""" Freqtrade bot """ """ Freqtrade bot """
__version__ = '2022.8.dev' __version__ = '2022.9.dev'
if 'dev' in __version__: if 'dev' in __version__:
try: try:

View File

@ -34,7 +34,7 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
"print_colorized", "print_json", "hyperopt_jobs", "print_colorized", "print_json", "hyperopt_jobs",
"hyperopt_random_state", "hyperopt_min_trades", "hyperopt_random_state", "hyperopt_min_trades",
"hyperopt_loss", "disableparamexport", "hyperopt_loss", "disableparamexport",
"hyperopt_ignore_missing_space"] "hyperopt_ignore_missing_space", "analyze_per_epoch"]
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"] ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]

View File

@ -255,6 +255,13 @@ AVAILABLE_CLI_OPTIONS = {
nargs='+', nargs='+',
default='default', default='default',
), ),
"analyze_per_epoch": Arg(
'--analyze-per-epoch',
help='Run populate_indicators once per epoch.',
action='store_true',
default=False,
),
"print_all": Arg( "print_all": Arg(
'--print-all', '--print-all',
help='Print all results, not only the best ones.', help='Print all results, not only the best ones.',
@ -455,7 +462,7 @@ AVAILABLE_CLI_OPTIONS = {
), ),
"prepend_data": Arg( "prepend_data": Arg(
'--prepend', '--prepend',
help='Allow data prepending.', help='Allow data prepending. (Data-appending is disabled)',
action='store_true', action='store_true',
), ),
"erase": Arg( "erase": Arg(

View File

@ -11,8 +11,7 @@ from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_oh
refresh_backtest_trades_data) refresh_backtest_trades_data)
from freqtrade.enums import CandleType, RunMode, TradingMode from freqtrade.enums import CandleType, RunMode, TradingMode
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import market_is_active, timeframe_to_minutes
from freqtrade.exchange.exchange import market_is_active
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist
from freqtrade.resolvers import ExchangeResolver from freqtrade.resolvers import ExchangeResolver

View File

@ -302,6 +302,9 @@ class Configuration:
self._args_to_config(config, argname='spaces', self._args_to_config(config, argname='spaces',
logstring='Parameter -s/--spaces detected: {}') logstring='Parameter -s/--spaces detected: {}')
self._args_to_config(config, argname='analyze_per_epoch',
logstring='Parameter --analyze-per-epoch detected.')
self._args_to_config(config, argname='print_all', self._args_to_config(config, argname='print_all',
logstring='Parameter --print-all detected ...') logstring='Parameter --print-all detected ...')

View File

@ -23,7 +23,8 @@ REQUIRED_ORDERTIF = ['entry', 'exit']
REQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange'] REQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']
PRICING_SIDES = ['ask', 'bid', 'same', 'other'] PRICING_SIDES = ['ask', 'bid', 'same', 'other']
ORDERTYPE_POSSIBILITIES = ['limit', 'market'] ORDERTYPE_POSSIBILITIES = ['limit', 'market']
ORDERTIF_POSSIBILITIES = ['gtc', 'fok', 'ioc'] _ORDERTIF_POSSIBILITIES = ['GTC', 'FOK', 'IOC', 'PO']
ORDERTIF_POSSIBILITIES = _ORDERTIF_POSSIBILITIES + [t.lower() for t in _ORDERTIF_POSSIBILITIES]
HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss', HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',
'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily', 'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',
'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily', 'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily',

View File

@ -91,9 +91,9 @@ class DataProvider:
timerange = TimeRange.parse_timerange(None if self._config.get( timerange = TimeRange.parse_timerange(None if self._config.get(
'timerange') is None else str(self._config.get('timerange'))) 'timerange') is None else str(self._config.get('timerange')))
# Move informative start time respecting startup_candle_count # Move informative start time respecting startup_candle_count
timerange.subtract_start( startup_candles = self.get_required_startup(str(timeframe))
timeframe_to_seconds(str(timeframe)) * self._config.get('startup_candle_count', 0) tf_seconds = timeframe_to_seconds(str(timeframe))
) timerange.subtract_start(tf_seconds * startup_candles)
self.__cached_pairs_backtesting[saved_pair] = load_pair_history( self.__cached_pairs_backtesting[saved_pair] = load_pair_history(
pair=pair, pair=pair,
timeframe=timeframe or self._config['timeframe'], timeframe=timeframe or self._config['timeframe'],
@ -105,6 +105,21 @@ class DataProvider:
) )
return self.__cached_pairs_backtesting[saved_pair].copy() return self.__cached_pairs_backtesting[saved_pair].copy()
def get_required_startup(self, timeframe: str) -> int:
freqai_config = self._config.get('freqai', {})
if not freqai_config.get('enabled', False):
return self._config.get('startup_candle_count', 0)
else:
startup_candles = self._config.get('startup_candle_count', 0)
indicator_periods = freqai_config['feature_parameters']['indicator_periods_candles']
# make sure the startupcandles is at least the set maximum indicator periods
self._config['startup_candle_count'] = max(startup_candles, max(indicator_periods))
tf_seconds = timeframe_to_seconds(timeframe)
train_candles = freqai_config['train_period_days'] * 86400 / tf_seconds
total_candles = int(self._config['startup_candle_count'] + train_candles)
logger.info(f'Increasing startup_candle_count for freqai to {total_candles}')
return total_candles
def get_pair_dataframe( def get_pair_dataframe(
self, self,
pair: str, pair: str,

View File

@ -15,7 +15,7 @@ from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT
from freqtrade.data.history import get_timerange, load_data, refresh_data from freqtrade.data.history import get_timerange, load_data, refresh_data
from freqtrade.enums import CandleType, ExitType, RunMode from freqtrade.enums import CandleType, ExitType, RunMode
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange.exchange import timeframe_to_seconds from freqtrade.exchange import timeframe_to_seconds
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.strategy.interface import IStrategy from freqtrade.strategy.interface import IStrategy

View File

@ -3,6 +3,7 @@ from freqtrade.enums.backteststate import BacktestState
from freqtrade.enums.candletype import CandleType from freqtrade.enums.candletype import CandleType
from freqtrade.enums.exitchecktuple import ExitCheckTuple from freqtrade.enums.exitchecktuple import ExitCheckTuple
from freqtrade.enums.exittype import ExitType from freqtrade.enums.exittype import ExitType
from freqtrade.enums.hyperoptstate import HyperoptState
from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.marginmode import MarginMode
from freqtrade.enums.ordertypevalue import OrderTypeValues from freqtrade.enums.ordertypevalue import OrderTypeValues
from freqtrade.enums.rpcmessagetype import RPCMessageType from freqtrade.enums.rpcmessagetype import RPCMessageType

View File

@ -0,0 +1,12 @@
from enum import Enum
class HyperoptState(Enum):
""" Hyperopt states """
STARTUP = 1
DATALOAD = 2
INDICATORS = 3
OPTIMIZE = 4
def __str__(self):
return f"{self.name.lower()}"

View File

@ -9,11 +9,11 @@ from freqtrade.exchange.bitpanda import Bitpanda
from freqtrade.exchange.bittrex import Bittrex from freqtrade.exchange.bittrex import Bittrex
from freqtrade.exchange.bybit import Bybit from freqtrade.exchange.bybit import Bybit
from freqtrade.exchange.coinbasepro import Coinbasepro from freqtrade.exchange.coinbasepro import Coinbasepro
from freqtrade.exchange.exchange import (amount_to_contracts, amount_to_precision, from freqtrade.exchange.exchange import (amount_to_contract_precision, amount_to_contracts,
available_exchanges, ccxt_exchanges, contracts_to_amount, amount_to_precision, available_exchanges, ccxt_exchanges,
date_minus_candles, is_exchange_known_ccxt, contracts_to_amount, date_minus_candles,
is_exchange_officially_supported, market_is_active, is_exchange_known_ccxt, is_exchange_officially_supported,
price_to_precision, timeframe_to_minutes, market_is_active, price_to_precision, timeframe_to_minutes,
timeframe_to_msecs, timeframe_to_next_date, timeframe_to_msecs, timeframe_to_next_date,
timeframe_to_prev_date, timeframe_to_seconds, timeframe_to_prev_date, timeframe_to_seconds,
validate_exchange, validate_exchanges) validate_exchange, validate_exchanges)

View File

@ -23,8 +23,7 @@ class Binance(Exchange):
_ft_has: Dict = { _ft_has: Dict = {
"stoploss_on_exchange": True, "stoploss_on_exchange": True,
"stoploss_order_types": {"limit": "stop_loss_limit"}, "stoploss_order_types": {"limit": "stop_loss_limit"},
"order_time_in_force": ['gtc', 'fok', 'ioc'], "order_time_in_force": ['GTC', 'FOK', 'IOC'],
"time_in_force_parameter": "timeInForce",
"ohlcv_candle_limit": 1000, "ohlcv_candle_limit": 1000,
"trades_pagination": "id", "trades_pagination": "id",
"trades_pagination_arg": "fromId", "trades_pagination_arg": "fromId",
@ -137,23 +136,27 @@ class Binance(Exchange):
pair: str, pair: str,
open_rate: float, # Entry price of position open_rate: float, # Entry price of position
is_short: bool, is_short: bool,
position: float, # Absolute value of position size amount: float,
stake_amount: float,
wallet_balance: float, # Or margin balance wallet_balance: float, # Or margin balance
mm_ex_1: float = 0.0, # (Binance) Cross only mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]: ) -> Optional[float]:
""" """
Important: Must be fetching data from cached values as this is used by backtesting!
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93 PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
:param exchange_name: :param exchange_name:
:param open_rate: (EP1) Entry price of position :param open_rate: Entry price of position
:param is_short: True if the trade is a short, false otherwise :param is_short: True if the trade is a short, false otherwise
:param position: Absolute value of position size (in base currency) :param amount: Absolute value of position size incl. leverage (in base currency)
:param wallet_balance: (WB) :param stake_amount: Stake amount - Collateral in settle currency.
:param trading_mode: SPOT, MARGIN, FUTURES, etc.
:param margin_mode: Either ISOLATED or CROSS
:param wallet_balance: Amount of margin_mode in the wallet being used to trade
Cross-Margin Mode: crossWalletBalance Cross-Margin Mode: crossWalletBalance
Isolated-Margin Mode: isolatedWalletBalance Isolated-Margin Mode: isolatedWalletBalance
:param maintenance_amt:
# * Only required for Cross # * Only required for Cross
:param mm_ex_1: (TMM) :param mm_ex_1: (TMM)
@ -165,12 +168,11 @@ class Binance(Exchange):
""" """
side_1 = -1 if is_short else 1 side_1 = -1 if is_short else 1
position = abs(position)
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0 cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100% # mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
# maintenance_amt: (CUM) Maintenance Amount of position # maintenance_amt: (CUM) Maintenance Amount of position
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, position) mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, stake_amount)
if (maintenance_amt is None): if (maintenance_amt is None):
raise OperationalException( raise OperationalException(
@ -182,9 +184,9 @@ class Binance(Exchange):
return ( return (
( (
(wallet_balance + cross_vars + maintenance_amt) - (wallet_balance + cross_vars + maintenance_amt) -
(side_1 * position * open_rate) (side_1 * amount * open_rate)
) / ( ) / (
(position * mm_ratio) - (side_1 * position) (amount * mm_ratio) - (side_1 * amount)
) )
) )
else: else:

View File

@ -62,7 +62,7 @@ class Exchange:
# or by specifying them in the configuration. # or by specifying them in the configuration.
_ft_has_default: Dict = { _ft_has_default: Dict = {
"stoploss_on_exchange": False, "stoploss_on_exchange": False,
"order_time_in_force": ["gtc"], "order_time_in_force": ["GTC"],
"time_in_force_parameter": "timeInForce", "time_in_force_parameter": "timeInForce",
"ohlcv_params": {}, "ohlcv_params": {},
"ohlcv_candle_limit": 500, "ohlcv_candle_limit": 500,
@ -611,7 +611,7 @@ class Exchange:
""" """
Checks if order time in force configured in strategy/config are supported Checks if order time in force configured in strategy/config are supported
""" """
if any(v not in self._ft_has["order_time_in_force"] if any(v.upper() not in self._ft_has["order_time_in_force"]
for k, v in order_time_in_force.items()): for k, v in order_time_in_force.items()):
raise OperationalException( raise OperationalException(
f'Time in force policies are not supported for {self.name} yet.') f'Time in force policies are not supported for {self.name} yet.')
@ -989,12 +989,12 @@ class Exchange:
ordertype: str, ordertype: str,
leverage: float, leverage: float,
reduceOnly: bool, reduceOnly: bool,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
params = self._params.copy() params = self._params.copy()
if time_in_force != 'gtc' and ordertype != 'market': if time_in_force != 'GTC' and ordertype != 'market':
param = self._ft_has.get('time_in_force_parameter', '') param = self._ft_has.get('time_in_force_parameter', '')
params.update({param: time_in_force}) params.update({param: time_in_force.upper()})
if reduceOnly: if reduceOnly:
params.update({'reduceOnly': True}) params.update({'reduceOnly': True})
return params return params
@ -1009,7 +1009,7 @@ class Exchange:
rate: float, rate: float,
leverage: float, leverage: float,
reduceOnly: bool = False, reduceOnly: bool = False,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
if self._config['dry_run']: if self._config['dry_run']:
dry_order = self.create_dry_run_order( dry_order = self.create_dry_run_order(
@ -2316,10 +2316,10 @@ class Exchange:
def parse_leverage_tier(self, tier) -> Dict: def parse_leverage_tier(self, tier) -> Dict:
info = tier.get('info', {}) info = tier.get('info', {})
return { return {
'min': tier['minNotional'], 'minNotional': tier['minNotional'],
'max': tier['maxNotional'], 'maxNotional': tier['maxNotional'],
'mmr': tier['maintenanceMarginRate'], 'maintenanceMarginRate': tier['maintenanceMarginRate'],
'lev': tier['maxLeverage'], 'maxLeverage': tier['maxLeverage'],
'maintAmt': float(info['cum']) if 'cum' in info else None, 'maintAmt': float(info['cum']) if 'cum' in info else None,
} }
@ -2348,18 +2348,18 @@ class Exchange:
pair_tiers = self._leverage_tiers[pair] pair_tiers = self._leverage_tiers[pair]
if stake_amount == 0: if stake_amount == 0:
return self._leverage_tiers[pair][0]['lev'] # Max lev for lowest amount return self._leverage_tiers[pair][0]['maxLeverage'] # Max lev for lowest amount
for tier_index in range(len(pair_tiers)): for tier_index in range(len(pair_tiers)):
tier = pair_tiers[tier_index] tier = pair_tiers[tier_index]
lev = tier['lev'] lev = tier['maxLeverage']
if tier_index < len(pair_tiers) - 1: if tier_index < len(pair_tiers) - 1:
next_tier = pair_tiers[tier_index + 1] next_tier = pair_tiers[tier_index + 1]
next_floor = next_tier['min'] / next_tier['lev'] next_floor = next_tier['minNotional'] / next_tier['maxLeverage']
if next_floor > stake_amount: # Next tier min too high for stake amount if next_floor > stake_amount: # Next tier min too high for stake amount
return min((tier['max'] / stake_amount), lev) return min((tier['maxNotional'] / stake_amount), lev)
# #
# With the two leverage tiers below, # With the two leverage tiers below,
# - a stake amount of 150 would mean a max leverage of (10000 / 150) = 66.66 # - a stake amount of 150 would mean a max leverage of (10000 / 150) = 66.66
@ -2380,10 +2380,11 @@ class Exchange:
# #
else: # if on the last tier else: # if on the last tier
if stake_amount > tier['max']: # If stake is > than max tradeable amount if stake_amount > tier['maxNotional']:
# If stake is > than max tradeable amount
raise InvalidOrderException(f'Amount {stake_amount} too high for {pair}') raise InvalidOrderException(f'Amount {stake_amount} too high for {pair}')
else: else:
return tier['lev'] return tier['maxLeverage']
raise OperationalException( raise OperationalException(
'Looped through all tiers without finding a max leverage. Should never be reached' 'Looped through all tiers without finding a max leverage. Should never be reached'
@ -2431,35 +2432,6 @@ class Exchange:
""" """
return 0.0 return 0.0
def get_liquidation_price(
self,
pair: str,
open_rate: float,
amount: float, # quote currency, includes leverage
leverage: float,
is_short: bool
) -> Optional[float]:
if self.trading_mode in TradingMode.SPOT:
return None
elif (
self.trading_mode == TradingMode.FUTURES
):
wallet_balance = (amount * open_rate) / leverage
isolated_liq = self.get_or_calculate_liquidation_price(
pair=pair,
open_rate=open_rate,
is_short=is_short,
position=amount,
wallet_balance=wallet_balance,
mm_ex_1=0.0,
upnl_ex_1=0.0,
)
return isolated_liq
else:
raise OperationalException(
"Freqtrade currently only supports futures for leverage trading.")
def funding_fee_cutoff(self, open_date: datetime): def funding_fee_cutoff(self, open_date: datetime):
""" """
:param open_date: The open date for a trade :param open_date: The open date for a trade
@ -2620,34 +2592,36 @@ class Exchange:
else: else:
return 0.0 return 0.0
def get_or_calculate_liquidation_price( def get_liquidation_price(
self, self,
pair: str, pair: str,
# Dry-run # Dry-run
open_rate: float, # Entry price of position open_rate: float, # Entry price of position
is_short: bool, is_short: bool,
position: float, # Absolute value of position size amount: float, # Absolute value of position size
wallet_balance: float, # Or margin balance stake_amount: float,
wallet_balance: float,
mm_ex_1: float = 0.0, # (Binance) Cross only mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]: ) -> Optional[float]:
""" """
Set's the margin mode on the exchange to cross or isolated for a specific pair Set's the margin mode on the exchange to cross or isolated for a specific pair
:param pair: base/quote currency pair (e.g. "ADA/USDT")
""" """
if self.trading_mode == TradingMode.SPOT: if self.trading_mode == TradingMode.SPOT:
return None return None
elif (self.trading_mode != TradingMode.FUTURES): elif (self.trading_mode != TradingMode.FUTURES):
raise OperationalException( raise OperationalException(
f"{self.name} does not support {self.margin_mode.value} {self.trading_mode.value}") f"{self.name} does not support {self.margin_mode} {self.trading_mode}")
isolated_liq = None
if self._config['dry_run'] or not self.exchange_has("fetchPositions"): if self._config['dry_run'] or not self.exchange_has("fetchPositions"):
isolated_liq = self.dry_run_liquidation_price( isolated_liq = self.dry_run_liquidation_price(
pair=pair, pair=pair,
open_rate=open_rate, open_rate=open_rate,
is_short=is_short, is_short=is_short,
position=position, amount=amount,
stake_amount=stake_amount,
wallet_balance=wallet_balance, wallet_balance=wallet_balance,
mm_ex_1=mm_ex_1, mm_ex_1=mm_ex_1,
upnl_ex_1=upnl_ex_1 upnl_ex_1=upnl_ex_1
@ -2657,8 +2631,6 @@ class Exchange:
if len(positions) > 0: if len(positions) > 0:
pos = positions[0] pos = positions[0]
isolated_liq = pos['liquidationPrice'] isolated_liq = pos['liquidationPrice']
else:
return None
if isolated_liq: if isolated_liq:
buffer_amount = abs(open_rate - isolated_liq) * self.liquidation_buffer buffer_amount = abs(open_rate - isolated_liq) * self.liquidation_buffer
@ -2676,22 +2648,24 @@ class Exchange:
pair: str, pair: str,
open_rate: float, # Entry price of position open_rate: float, # Entry price of position
is_short: bool, is_short: bool,
position: float, # Absolute value of position size amount: float,
stake_amount: float,
wallet_balance: float, # Or margin balance wallet_balance: float, # Or margin balance
mm_ex_1: float = 0.0, # (Binance) Cross only mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]: ) -> Optional[float]:
""" """
Important: Must be fetching data from cached values as this is used by backtesting!
PERPETUAL: PERPETUAL:
gateio: https://www.gate.io/help/futures/perpetual/22160/calculation-of-liquidation-price gateio: https://www.gate.io/help/futures/perpetual/22160/calculation-of-liquidation-price
okex: https://www.okex.com/support/hc/en-us/articles/ okex: https://www.okex.com/support/hc/en-us/articles/
360053909592-VI-Introduction-to-the-isolated-mode-of-Single-Multi-currency-Portfolio-margin 360053909592-VI-Introduction-to-the-isolated-mode-of-Single-Multi-currency-Portfolio-margin
Important: Must be fetching data from cached values as this is used by backtesting!
:param exchange_name: :param exchange_name:
:param open_rate: Entry price of position :param open_rate: Entry price of position
:param is_short: True if the trade is a short, false otherwise :param is_short: True if the trade is a short, false otherwise
:param position: Absolute value of position size incl. leverage (in base currency) :param amount: Absolute value of position size incl. leverage (in base currency)
:param stake_amount: Stake amount - Collateral in settle currency.
:param trading_mode: SPOT, MARGIN, FUTURES, etc. :param trading_mode: SPOT, MARGIN, FUTURES, etc.
:param margin_mode: Either ISOLATED or CROSS :param margin_mode: Either ISOLATED or CROSS
:param wallet_balance: Amount of margin_mode in the wallet being used to trade :param wallet_balance: Amount of margin_mode in the wallet being used to trade
@ -2705,7 +2679,7 @@ class Exchange:
market = self.markets[pair] market = self.markets[pair]
taker_fee_rate = market['taker'] taker_fee_rate = market['taker']
mm_ratio, _ = self.get_maintenance_ratio_and_amt(pair, position) mm_ratio, _ = self.get_maintenance_ratio_and_amt(pair, stake_amount)
if self.trading_mode == TradingMode.FUTURES and self.margin_mode == MarginMode.ISOLATED: if self.trading_mode == TradingMode.FUTURES and self.margin_mode == MarginMode.ISOLATED:
@ -2713,7 +2687,7 @@ class Exchange:
raise OperationalException( raise OperationalException(
"Freqtrade does not yet support inverse contracts") "Freqtrade does not yet support inverse contracts")
value = wallet_balance / position value = wallet_balance / amount
mm_ratio_taker = (mm_ratio + taker_fee_rate) mm_ratio_taker = (mm_ratio + taker_fee_rate)
if is_short: if is_short:
@ -2749,8 +2723,8 @@ class Exchange:
pair_tiers = self._leverage_tiers[pair] pair_tiers = self._leverage_tiers[pair]
for tier in reversed(pair_tiers): for tier in reversed(pair_tiers):
if nominal_value >= tier['min']: if nominal_value >= tier['minNotional']:
return (tier['mmr'], tier['maintAmt']) return (tier['maintenanceMarginRate'], tier['maintAmt'])
raise OperationalException("nominal value can not be lower than 0") raise OperationalException("nominal value can not be lower than 0")
# The lowest notional_floor for any pair in fetch_leverage_tiers is always 0 because it # The lowest notional_floor for any pair in fetch_leverage_tiers is always 0 because it
@ -2943,6 +2917,29 @@ def amount_to_precision(amount: float, amount_precision: Optional[float],
return amount return amount
def amount_to_contract_precision(
amount, amount_precision: Optional[float], precisionMode: Optional[int],
contract_size: Optional[float]) -> float:
"""
Returns the amount to buy or sell to a precision the Exchange accepts
including calculation to and from contracts.
Re-implementation of ccxt internal methods - ensuring we can test the result is correct
based on our definitions.
:param amount: amount to truncate
:param amount_precision: amount precision to use.
should be retrieved from markets[pair]['precision']['amount']
:param precisionMode: precision mode to use. Should be used from precisionMode
one of ccxt's DECIMAL_PLACES, SIGNIFICANT_DIGITS, or TICK_SIZE
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: truncated amount
"""
if amount_precision is not None and precisionMode is not None:
contracts = amount_to_contracts(amount, contract_size)
amount_p = amount_to_precision(contracts, amount_precision, precisionMode)
return contracts_to_amount(amount_p, contract_size)
return amount
def price_to_precision(price: float, price_precision: Optional[float], def price_to_precision(price: float, price_precision: Optional[float],
precisionMode: Optional[int]) -> float: precisionMode: Optional[int]) -> float:
""" """

View File

@ -19,6 +19,7 @@ logger = logging.getLogger(__name__)
class Ftx(Exchange): class Ftx(Exchange):
_ft_has: Dict = { _ft_has: Dict = {
"order_time_in_force": ['GTC', 'IOC', 'PO'],
"stoploss_on_exchange": True, "stoploss_on_exchange": True,
"ohlcv_candle_limit": 1500, "ohlcv_candle_limit": 1500,
"ohlcv_require_since": True, "ohlcv_require_since": True,

View File

@ -25,8 +25,7 @@ class Gateio(Exchange):
_ft_has: Dict = { _ft_has: Dict = {
"ohlcv_candle_limit": 1000, "ohlcv_candle_limit": 1000,
"time_in_force_parameter": "timeInForce", "order_time_in_force": ['GTC', 'IOC'],
"order_time_in_force": ['gtc', 'ioc'],
"stoploss_order_types": {"limit": "limit"}, "stoploss_order_types": {"limit": "limit"},
"stoploss_on_exchange": True, "stoploss_on_exchange": True,
} }
@ -57,7 +56,7 @@ class Gateio(Exchange):
ordertype: str, ordertype: str,
leverage: float, leverage: float,
reduceOnly: bool, reduceOnly: bool,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
params = super()._get_params( params = super()._get_params(
side=side, side=side,
@ -69,7 +68,7 @@ class Gateio(Exchange):
if ordertype == 'market' and self.trading_mode == TradingMode.FUTURES: if ordertype == 'market' and self.trading_mode == TradingMode.FUTURES:
params['type'] = 'market' params['type'] = 'market'
param = self._ft_has.get('time_in_force_parameter', '') param = self._ft_has.get('time_in_force_parameter', '')
params.update({param: 'ioc'}) params.update({param: 'IOC'})
return params return params
def get_trades_for_order(self, order_id: str, pair: str, since: datetime, def get_trades_for_order(self, order_id: str, pair: str, since: datetime,

View File

@ -171,7 +171,7 @@ class Kraken(Exchange):
ordertype: str, ordertype: str,
leverage: float, leverage: float,
reduceOnly: bool, reduceOnly: bool,
time_in_force: str = 'gtc' time_in_force: str = 'GTC'
) -> Dict: ) -> Dict:
params = super()._get_params( params = super()._get_params(
side=side, side=side,

View File

@ -23,8 +23,7 @@ class Kucoin(Exchange):
"stoploss_order_types": {"limit": "limit", "market": "market"}, "stoploss_order_types": {"limit": "limit", "market": "market"},
"l2_limit_range": [20, 100], "l2_limit_range": [20, 100],
"l2_limit_range_required": False, "l2_limit_range_required": False,
"order_time_in_force": ['gtc', 'fok', 'ioc'], "order_time_in_force": ['GTC', 'FOK', 'IOC'],
"time_in_force_parameter": "timeInForce",
"ohlcv_candle_limit": 1500, "ohlcv_candle_limit": 1500,
} }

View File

@ -98,7 +98,7 @@ class Okx(Exchange):
ordertype: str, ordertype: str,
leverage: float, leverage: float,
reduceOnly: bool, reduceOnly: bool,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
params = super()._get_params( params = super()._get_params(
side=side, side=side,
@ -146,4 +146,4 @@ class Okx(Exchange):
return float('inf') return float('inf')
pair_tiers = self._leverage_tiers[pair] pair_tiers = self._leverage_tiers[pair]
return pair_tiers[-1]['max'] / leverage return pair_tiers[-1]['maxNotional'] / leverage

View File

@ -579,7 +579,6 @@ class FreqaiDataDrawer:
for training according to user defined train_period_days for training according to user defined train_period_days
metadata: dict = strategy furnished pair metadata metadata: dict = strategy furnished pair metadata
""" """
with self.history_lock: with self.history_lock:
corr_dataframes: Dict[Any, Any] = {} corr_dataframes: Dict[Any, Any] = {}
base_dataframes: Dict[Any, Any] = {} base_dataframes: Dict[Any, Any] = {}

View File

@ -16,8 +16,6 @@ from sklearn.model_selection import train_test_split
from sklearn.neighbors import NearestNeighbors from sklearn.neighbors import NearestNeighbors
from freqtrade.configuration import TimeRange from freqtrade.configuration import TimeRange
from freqtrade.data.dataprovider import DataProvider
from freqtrade.data.history.history_utils import refresh_backtest_ohlcv_data
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_seconds from freqtrade.exchange import timeframe_to_seconds
from freqtrade.strategy.interface import IStrategy from freqtrade.strategy.interface import IStrategy
@ -71,6 +69,8 @@ class FreqaiDataKitchen:
self.label_list: List = [] self.label_list: List = []
self.training_features_list: List = [] self.training_features_list: List = []
self.model_filename: str = "" self.model_filename: str = ""
self.backtesting_results_path = Path()
self.backtest_predictions_folder: str = "backtesting_predictions"
self.live = live self.live = live
self.pair = pair self.pair = pair
@ -168,9 +168,17 @@ class FreqaiDataKitchen:
train_labels = labels train_labels = labels
train_weights = weights train_weights = weights
return self.build_data_dictionary( # Simplest way to reverse the order of training and test data:
train_features, test_features, train_labels, test_labels, train_weights, test_weights if self.freqai_config['feature_parameters'].get('reverse_train_test_order', False):
) return self.build_data_dictionary(
test_features, train_features, test_labels,
train_labels, test_weights, train_weights
)
else:
return self.build_data_dictionary(
train_features, test_features, train_labels,
test_labels, train_weights, test_weights
)
def filter_features( def filter_features(
self, self,
@ -281,6 +289,7 @@ class FreqaiDataKitchen:
:returns: :returns:
:data_dictionary: updated dictionary with standardized values. :data_dictionary: updated dictionary with standardized values.
""" """
# standardize the data by training stats # standardize the data by training stats
train_max = data_dictionary["train_features"].max() train_max = data_dictionary["train_features"].max()
train_min = data_dictionary["train_features"].min() train_min = data_dictionary["train_features"].min()
@ -314,10 +323,24 @@ class FreqaiDataKitchen:
- 1 - 1
) )
self.data[f"{item}_max"] = train_labels_max # .to_dict() self.data[f"{item}_max"] = train_labels_max
self.data[f"{item}_min"] = train_labels_min # .to_dict() self.data[f"{item}_min"] = train_labels_min
return data_dictionary return data_dictionary
def normalize_single_dataframe(self, df: DataFrame) -> DataFrame:
train_max = df.max()
train_min = df.min()
df = (
2 * (df - train_min) / (train_max - train_min) - 1
)
for item in train_max.keys():
self.data[item + "_max"] = train_max[item]
self.data[item + "_min"] = train_min[item]
return df
def normalize_data_from_metadata(self, df: DataFrame) -> DataFrame: def normalize_data_from_metadata(self, df: DataFrame) -> DataFrame:
""" """
Normalize a set of data using the mean and standard deviation from Normalize a set of data using the mean and standard deviation from
@ -444,22 +467,23 @@ class FreqaiDataKitchen:
from sklearn.decomposition import PCA # avoid importing if we dont need it from sklearn.decomposition import PCA # avoid importing if we dont need it
n_components = self.data_dictionary["train_features"].shape[1] pca = PCA(0.999)
pca = PCA(n_components=n_components)
pca = pca.fit(self.data_dictionary["train_features"]) pca = pca.fit(self.data_dictionary["train_features"])
n_keep_components = np.argmin(pca.explained_variance_ratio_.cumsum() < 0.999) n_keep_components = pca.n_components_
pca2 = PCA(n_components=n_keep_components)
self.data["n_kept_components"] = n_keep_components self.data["n_kept_components"] = n_keep_components
pca2 = pca2.fit(self.data_dictionary["train_features"]) n_components = self.data_dictionary["train_features"].shape[1]
logger.info("reduced feature dimension by %s", n_components - n_keep_components) logger.info("reduced feature dimension by %s", n_components - n_keep_components)
logger.info("explained variance %f", np.sum(pca2.explained_variance_ratio_)) logger.info("explained variance %f", np.sum(pca.explained_variance_ratio_))
train_components = pca2.transform(self.data_dictionary["train_features"])
train_components = pca.transform(self.data_dictionary["train_features"])
self.data_dictionary["train_features"] = pd.DataFrame( self.data_dictionary["train_features"] = pd.DataFrame(
data=train_components, data=train_components,
columns=["PC" + str(i) for i in range(0, n_keep_components)], columns=["PC" + str(i) for i in range(0, n_keep_components)],
index=self.data_dictionary["train_features"].index, index=self.data_dictionary["train_features"].index,
) )
# normalsing transformed training features
self.data_dictionary["train_features"] = self.normalize_single_dataframe(
self.data_dictionary["train_features"])
# keeping a copy of the non-transformed features so we can check for errors during # keeping a copy of the non-transformed features so we can check for errors during
# model load from disk # model load from disk
@ -467,15 +491,18 @@ class FreqaiDataKitchen:
self.training_features_list = self.data_dictionary["train_features"].columns self.training_features_list = self.data_dictionary["train_features"].columns
if self.freqai_config.get('data_split_parameters', {}).get('test_size', 0.1) != 0: if self.freqai_config.get('data_split_parameters', {}).get('test_size', 0.1) != 0:
test_components = pca2.transform(self.data_dictionary["test_features"]) test_components = pca.transform(self.data_dictionary["test_features"])
self.data_dictionary["test_features"] = pd.DataFrame( self.data_dictionary["test_features"] = pd.DataFrame(
data=test_components, data=test_components,
columns=["PC" + str(i) for i in range(0, n_keep_components)], columns=["PC" + str(i) for i in range(0, n_keep_components)],
index=self.data_dictionary["test_features"].index, index=self.data_dictionary["test_features"].index,
) )
# normalise transformed test feature to transformed training features
self.data_dictionary["test_features"] = self.normalize_data_from_metadata(
self.data_dictionary["test_features"])
self.data["n_kept_components"] = n_keep_components self.data["n_kept_components"] = n_keep_components
self.pca = pca2 self.pca = pca
logger.info(f"PCA reduced total features from {n_components} to {n_keep_components}") logger.info(f"PCA reduced total features from {n_components} to {n_keep_components}")
@ -496,6 +523,9 @@ class FreqaiDataKitchen:
columns=["PC" + str(i) for i in range(0, self.data["n_kept_components"])], columns=["PC" + str(i) for i in range(0, self.data["n_kept_components"])],
index=filtered_dataframe.index, index=filtered_dataframe.index,
) )
# normalise transformed predictions to transformed training features
self.data_dictionary["prediction_features"] = self.normalize_data_from_metadata(
self.data_dictionary["prediction_features"])
def compute_distances(self) -> float: def compute_distances(self) -> float:
""" """
@ -513,6 +543,18 @@ class FreqaiDataKitchen:
return avg_mean_dist return avg_mean_dist
def get_outlier_percentage(self, dropped_pts: npt.NDArray) -> float:
"""
Check if more than X% of points werer dropped during outlier detection.
"""
outlier_protection_pct = self.freqai_config["feature_parameters"].get(
"outlier_protection_percentage", 30)
outlier_pct = (dropped_pts.sum() / len(dropped_pts)) * 100
if outlier_pct >= outlier_protection_pct:
return outlier_pct
else:
return 0.0
def use_SVM_to_remove_outliers(self, predict: bool) -> None: def use_SVM_to_remove_outliers(self, predict: bool) -> None:
""" """
Build/inference a Support Vector Machine to detect outliers Build/inference a Support Vector Machine to detect outliers
@ -550,8 +592,17 @@ class FreqaiDataKitchen:
self.data_dictionary["train_features"] self.data_dictionary["train_features"]
) )
y_pred = self.svm_model.predict(self.data_dictionary["train_features"]) y_pred = self.svm_model.predict(self.data_dictionary["train_features"])
dropped_points = np.where(y_pred == -1, 0, y_pred) kept_points = np.where(y_pred == -1, 0, y_pred)
# keep_index = np.where(y_pred == 1) # keep_index = np.where(y_pred == 1)
outlier_pct = self.get_outlier_percentage(1 - kept_points)
if outlier_pct:
logger.warning(
f"SVM detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
self.svm_model = None
return
self.data_dictionary["train_features"] = self.data_dictionary["train_features"][ self.data_dictionary["train_features"] = self.data_dictionary["train_features"][
(y_pred == 1) (y_pred == 1)
] ]
@ -563,7 +614,7 @@ class FreqaiDataKitchen:
] ]
logger.info( logger.info(
f"SVM tossed {len(y_pred) - dropped_points.sum()}" f"SVM tossed {len(y_pred) - kept_points.sum()}"
f" train points from {len(y_pred)} total points." f" train points from {len(y_pred)} total points."
) )
@ -572,7 +623,7 @@ class FreqaiDataKitchen:
# to reduce code duplication # to reduce code duplication
if self.freqai_config['data_split_parameters'].get('test_size', 0.1) != 0: if self.freqai_config['data_split_parameters'].get('test_size', 0.1) != 0:
y_pred = self.svm_model.predict(self.data_dictionary["test_features"]) y_pred = self.svm_model.predict(self.data_dictionary["test_features"])
dropped_points = np.where(y_pred == -1, 0, y_pred) kept_points = np.where(y_pred == -1, 0, y_pred)
self.data_dictionary["test_features"] = self.data_dictionary["test_features"][ self.data_dictionary["test_features"] = self.data_dictionary["test_features"][
(y_pred == 1) (y_pred == 1)
] ]
@ -583,7 +634,7 @@ class FreqaiDataKitchen:
] ]
logger.info( logger.info(
f"SVM tossed {len(y_pred) - dropped_points.sum()}" f"SVM tossed {len(y_pred) - kept_points.sum()}"
f" test points from {len(y_pred)} total points." f" test points from {len(y_pred)} total points."
) )
@ -604,6 +655,8 @@ class FreqaiDataKitchen:
from math import cos, sin from math import cos, sin
if predict: if predict:
if not self.data['DBSCAN_eps']:
return
train_ft_df = self.data_dictionary['train_features'] train_ft_df = self.data_dictionary['train_features']
pred_ft_df = self.data_dictionary['prediction_features'] pred_ft_df = self.data_dictionary['prediction_features']
num_preds = len(pred_ft_df) num_preds = len(pred_ft_df)
@ -635,8 +688,8 @@ class FreqaiDataKitchen:
cos(angle) * (point[1] - origin[1]) cos(angle) * (point[1] - origin[1])
return (x, y) return (x, y)
MinPts = len(self.data_dictionary['train_features'].columns) * 2 MinPts = int(len(self.data_dictionary['train_features'].index) * 0.25)
# measure pairwise distances to train_features.shape[1]*2 nearest neighbours # measure pairwise distances to nearest neighbours
neighbors = NearestNeighbors( neighbors = NearestNeighbors(
n_neighbors=MinPts, n_jobs=self.thread_count) n_neighbors=MinPts, n_jobs=self.thread_count)
neighbors_fit = neighbors.fit(self.data_dictionary['train_features']) neighbors_fit = neighbors.fit(self.data_dictionary['train_features'])
@ -667,6 +720,15 @@ class FreqaiDataKitchen:
self.data['DBSCAN_min_samples'] = MinPts self.data['DBSCAN_min_samples'] = MinPts
dropped_points = np.where(clustering.labels_ == -1, 1, 0) dropped_points = np.where(clustering.labels_ == -1, 1, 0)
outlier_pct = self.get_outlier_percentage(dropped_points)
if outlier_pct:
logger.warning(
f"DBSCAN detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
self.data['DBSCAN_eps'] = 0
return
self.data_dictionary['train_features'] = self.data_dictionary['train_features'][ self.data_dictionary['train_features'] = self.data_dictionary['train_features'][
(clustering.labels_ != -1) (clustering.labels_ != -1)
] ]
@ -725,7 +787,7 @@ class FreqaiDataKitchen:
if (len(do_predict) - do_predict.sum()) > 0: if (len(do_predict) - do_predict.sum()) > 0:
logger.info( logger.info(
f"DI tossed {len(do_predict) - do_predict.sum()} predictions for " f"DI tossed {len(do_predict) - do_predict.sum()} predictions for "
"being too far from training data" "being too far from training data."
) )
self.do_predict += do_predict self.do_predict += do_predict
@ -740,9 +802,10 @@ class FreqaiDataKitchen:
weights = np.exp(-np.arange(num_weights) / (wfactor * num_weights))[::-1] weights = np.exp(-np.arange(num_weights) / (wfactor * num_weights))[::-1]
return weights return weights
def append_predictions(self, predictions: DataFrame, do_predict: npt.ArrayLike) -> None: def get_predictions_to_append(self, predictions: DataFrame,
do_predict: npt.ArrayLike) -> DataFrame:
""" """
Append backtest prediction from current backtest period to all previous periods Get backtest prediction from current backtest period
""" """
append_df = DataFrame() append_df = DataFrame()
@ -757,13 +820,18 @@ class FreqaiDataKitchen:
if self.freqai_config["feature_parameters"].get("DI_threshold", 0) > 0: if self.freqai_config["feature_parameters"].get("DI_threshold", 0) > 0:
append_df["DI_values"] = self.DI_values append_df["DI_values"] = self.DI_values
return append_df
def append_predictions(self, append_df: DataFrame) -> None:
"""
Append backtest prediction from current backtest period to all previous periods
"""
if self.full_df.empty: if self.full_df.empty:
self.full_df = append_df self.full_df = append_df
else: else:
self.full_df = pd.concat([self.full_df, append_df], axis=0) self.full_df = pd.concat([self.full_df, append_df], axis=0)
return
def fill_predictions(self, dataframe): def fill_predictions(self, dataframe):
""" """
Back fill values to before the backtesting range so that the dataframe matches size Back fill values to before the backtesting range so that the dataframe matches size
@ -863,9 +931,7 @@ class FreqaiDataKitchen:
# We notice that users like to use exotic indicators where # We notice that users like to use exotic indicators where
# they do not know the required timeperiod. Here we include a factor # they do not know the required timeperiod. Here we include a factor
# of safety by multiplying the user considered "max" by 2. # of safety by multiplying the user considered "max" by 2.
max_period = self.freqai_config["feature_parameters"].get( max_period = self.config.get('startup_candle_count', 20) * 2
"indicator_max_period_candles", 20
) * 2
additional_seconds = max_period * max_tf_seconds additional_seconds = max_period * max_tf_seconds
if trained_timestamp != 0: if trained_timestamp != 0:
@ -911,31 +977,6 @@ class FreqaiDataKitchen:
self.model_filename = f"cb_{coin.lower()}_{int(trained_timerange.stopts)}" self.model_filename = f"cb_{coin.lower()}_{int(trained_timerange.stopts)}"
def download_all_data_for_training(self, timerange: TimeRange, dp: DataProvider) -> None:
"""
Called only once upon start of bot to download the necessary data for
populating indicators and training the model.
:param timerange: TimeRange = The full data timerange for populating the indicators
and training the model.
:param dp: DataProvider instance attached to the strategy
"""
new_pairs_days = int((timerange.stopts - timerange.startts) / SECONDS_IN_DAY)
if not dp._exchange:
# Not realistic - this is only called in live mode.
raise OperationalException("Dataprovider did not have an exchange attached.")
refresh_backtest_ohlcv_data(
dp._exchange,
pairs=self.all_pairs,
timeframes=self.freqai_config["feature_parameters"].get("include_timeframes"),
datadir=self.config["datadir"],
timerange=timerange,
new_pairs_days=new_pairs_days,
erase=False,
data_format=self.config.get("dataformat_ohlcv", "json"),
trading_mode=self.config.get("trading_mode", "spot"),
prepend=self.config.get("prepend_data", False),
)
def set_all_pairs(self) -> None: def set_all_pairs(self) -> None:
self.all_pairs = copy.deepcopy( self.all_pairs = copy.deepcopy(
@ -1049,3 +1090,50 @@ class FreqaiDataKitchen:
if self.unique_classes: if self.unique_classes:
for label in self.unique_classes: for label in self.unique_classes:
self.unique_class_list += list(self.unique_classes[label]) self.unique_class_list += list(self.unique_classes[label])
def save_backtesting_prediction(
self, append_df: DataFrame
) -> None:
"""
Save prediction dataframe from backtesting to h5 file format
:param append_df: dataframe for backtesting period
"""
full_predictions_folder = Path(self.full_path / self.backtest_predictions_folder)
if not full_predictions_folder.is_dir():
full_predictions_folder.mkdir(parents=True, exist_ok=True)
append_df.to_hdf(self.backtesting_results_path, key='append_df', mode='w')
def get_backtesting_prediction(
self
) -> DataFrame:
"""
Get prediction dataframe from h5 file format
"""
append_df = pd.read_hdf(self.backtesting_results_path)
return append_df
def check_if_backtest_prediction_exists(
self
) -> bool:
"""
Check if a backtesting prediction already exists
:param dk: FreqaiDataKitchen
:return:
:boolean: whether the prediction file exists or not.
"""
path_to_predictionfile = Path(self.full_path /
self.backtest_predictions_folder /
f"{self.model_filename}_prediction.h5")
self.backtesting_results_path = path_to_predictionfile
file_exists = path_to_predictionfile.is_file()
if file_exists:
logger.info(f"Found backtesting prediction file at {path_to_predictionfile}")
else:
logger.info(
f"Could not find backtesting prediction file at {path_to_predictionfile}"
)
return file_exists

View File

@ -71,6 +71,9 @@ class IFreqaiModel(ABC):
self.first = True self.first = True
self.set_full_path() self.set_full_path()
self.follow_mode: bool = self.freqai_info.get("follow_mode", False) self.follow_mode: bool = self.freqai_info.get("follow_mode", False)
self.save_backtest_models: bool = self.freqai_info.get("save_backtest_models", False)
if self.save_backtest_models:
logger.info('Backtesting module configured to save all models.')
self.dd = FreqaiDataDrawer(Path(self.full_path), self.config, self.follow_mode) self.dd = FreqaiDataDrawer(Path(self.full_path), self.config, self.follow_mode)
self.identifier: str = self.freqai_info.get("identifier", "no_id_provided") self.identifier: str = self.freqai_info.get("identifier", "no_id_provided")
self.scanning = False self.scanning = False
@ -125,10 +128,9 @@ class IFreqaiModel(ABC):
elif not self.follow_mode: elif not self.follow_mode:
self.dk = FreqaiDataKitchen(self.config, self.live, metadata["pair"]) self.dk = FreqaiDataKitchen(self.config, self.live, metadata["pair"])
logger.info(f"Training {len(self.dk.training_timeranges)} timeranges") logger.info(f"Training {len(self.dk.training_timeranges)} timeranges")
with self.analysis_lock: dataframe = self.dk.use_strategy_to_populate_indicators(
dataframe = self.dk.use_strategy_to_populate_indicators( strategy, prediction_dataframe=dataframe, pair=metadata["pair"]
strategy, prediction_dataframe=dataframe, pair=metadata["pair"] )
)
dk = self.start_backtesting(dataframe, metadata, self.dk) dk = self.start_backtesting(dataframe, metadata, self.dk)
dataframe = dk.remove_features_from_df(dk.return_dataframe) dataframe = dk.remove_features_from_df(dk.return_dataframe)
@ -225,28 +227,39 @@ class IFreqaiModel(ABC):
"trains" "trains"
) )
trained_timestamp_int = int(trained_timestamp.stopts)
dk.data_path = Path( dk.data_path = Path(
dk.full_path dk.full_path
/ /
f"sub-train-{metadata['pair'].split('/')[0]}_{int(trained_timestamp.stopts)}" f"sub-train-{metadata['pair'].split('/')[0]}_{trained_timestamp_int}"
) )
if not self.model_exists(
metadata["pair"], dk, trained_timestamp=int(trained_timestamp.stopts) dk.set_new_model_names(metadata["pair"], trained_timestamp)
):
dk.find_features(dataframe_train) if dk.check_if_backtest_prediction_exists():
self.model = self.train(dataframe_train, metadata["pair"], dk) append_df = dk.get_backtesting_prediction()
self.dd.pair_dict[metadata["pair"]]["trained_timestamp"] = int( dk.append_predictions(append_df)
trained_timestamp.stopts)
dk.set_new_model_names(metadata["pair"], trained_timestamp)
self.dd.save_data(self.model, metadata["pair"], dk)
else: else:
self.model = self.dd.load_data(metadata["pair"], dk) if not self.model_exists(
metadata["pair"], dk, trained_timestamp=trained_timestamp_int
):
dk.find_features(dataframe_train)
self.model = self.train(dataframe_train, metadata["pair"], dk)
self.dd.pair_dict[metadata["pair"]]["trained_timestamp"] = int(
trained_timestamp.stopts)
self.check_if_feature_list_matches_strategy(dataframe_train, dk) if self.save_backtest_models:
logger.info('Saving backtest model to disk.')
self.dd.save_data(self.model, metadata["pair"], dk)
else:
self.model = self.dd.load_data(metadata["pair"], dk)
pred_df, do_preds = self.predict(dataframe_backtest, dk) self.check_if_feature_list_matches_strategy(dataframe_train, dk)
dk.append_predictions(pred_df, do_preds) pred_df, do_preds = self.predict(dataframe_backtest, dk)
append_df = dk.get_predictions_to_append(pred_df, do_preds)
dk.append_predictions(append_df)
dk.save_backtesting_prediction(append_df)
dk.fill_predictions(dataframe) dk.fill_predictions(dataframe)
@ -291,14 +304,8 @@ class IFreqaiModel(ABC):
) )
dk.set_paths(metadata["pair"], new_trained_timerange.stopts) dk.set_paths(metadata["pair"], new_trained_timerange.stopts)
# download candle history if it is not already in memory # load candle history into memory if it is not yet.
if not self.dd.historic_data: if not self.dd.historic_data:
logger.info(
"Downloading all training data for all pairs in whitelist and "
"corr_pairlist, this may take a while if you do not have the "
"data saved"
)
dk.download_all_data_for_training(data_load_timerange, strategy.dp)
self.dd.load_all_pair_histories(data_load_timerange, dk) self.dd.load_all_pair_histories(data_load_timerange, dk)
if not self.scanning: if not self.scanning:
@ -463,11 +470,6 @@ class IFreqaiModel(ABC):
:return: :return:
:boolean: whether the model file exists or not. :boolean: whether the model file exists or not.
""" """
coin, _ = pair.split("/")
if not self.live:
dk.model_filename = model_filename = f"cb_{coin.lower()}_{trained_timestamp}"
path_to_modelfile = Path(dk.data_path / f"{model_filename}_model.joblib") path_to_modelfile = Path(dk.data_path / f"{model_filename}_model.joblib")
file_exists = path_to_modelfile.is_file() file_exists = path_to_modelfile.is_file()
if file_exists and not scanning: if file_exists and not scanning:
@ -620,8 +622,8 @@ class IFreqaiModel(ABC):
logger.info( logger.info(
f'Total time spent inferencing pairlist {self.inference_time:.2f} seconds') f'Total time spent inferencing pairlist {self.inference_time:.2f} seconds')
if self.inference_time > 0.25 * self.base_tf_seconds: if self.inference_time > 0.25 * self.base_tf_seconds:
logger.warning('Inference took over 25/% of the candle time. Reduce pairlist to' logger.warning("Inference took over 25% of the candle time. Reduce pairlist to"
' avoid blinding open trades and degrading performance.') " avoid blinding open trades and degrading performance.")
self.pair_it = 0 self.pair_it = 0
self.inference_time = 0 self.inference_time = 0
return return

134
freqtrade/freqai/utils.py Normal file
View File

@ -0,0 +1,134 @@
import logging
from datetime import datetime, timezone
from freqtrade.configuration import TimeRange
from freqtrade.data.dataprovider import DataProvider
from freqtrade.data.history.history_utils import refresh_backtest_ohlcv_data
from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_seconds
from freqtrade.exchange.exchange import market_is_active
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist
logger = logging.getLogger(__name__)
def download_all_data_for_training(dp: DataProvider, config: dict) -> None:
"""
Called only once upon start of bot to download the necessary data for
populating indicators and training the model.
:param timerange: TimeRange = The full data timerange for populating the indicators
and training the model.
:param dp: DataProvider instance attached to the strategy
"""
if dp._exchange is None:
raise OperationalException('No exchange object found.')
markets = [p for p, m in dp._exchange.markets.items() if market_is_active(m)
or config.get('include_inactive')]
all_pairs = dynamic_expand_pairlist(config, markets)
timerange = get_required_data_timerange(config)
new_pairs_days = int((timerange.stopts - timerange.startts) / 86400)
refresh_backtest_ohlcv_data(
dp._exchange,
pairs=all_pairs,
timeframes=config["freqai"]["feature_parameters"].get("include_timeframes"),
datadir=config["datadir"],
timerange=timerange,
new_pairs_days=new_pairs_days,
erase=False,
data_format=config.get("dataformat_ohlcv", "json"),
trading_mode=config.get("trading_mode", "spot"),
prepend=config.get("prepend_data", False),
)
def get_required_data_timerange(
config: dict
) -> TimeRange:
"""
Used to compute the required data download time range
for auto data-download in FreqAI
"""
time = datetime.now(tz=timezone.utc).timestamp()
timeframes = config["freqai"]["feature_parameters"].get("include_timeframes")
max_tf_seconds = 0
for tf in timeframes:
secs = timeframe_to_seconds(tf)
if secs > max_tf_seconds:
max_tf_seconds = secs
startup_candles = config.get('startup_candle_count', 0)
indicator_periods = config["freqai"]["feature_parameters"]["indicator_periods_candles"]
# factor the max_period as a factor of safety.
max_period = int(max(startup_candles, max(indicator_periods)) * 1.5)
config['startup_candle_count'] = max_period
logger.info(f'FreqAI auto-downloader using {max_period} startup candles.')
additional_seconds = max_period * max_tf_seconds
startts = int(
time
- config["freqai"].get("train_period_days", 0) * 86400
- additional_seconds
)
stopts = int(time)
data_load_timerange = TimeRange('date', 'date', startts, stopts)
return data_load_timerange
# Keep below for when we wish to download heterogeneously lengthed data for FreqAI.
# def download_all_data_for_training(dp: DataProvider, config: dict) -> None:
# """
# Called only once upon start of bot to download the necessary data for
# populating indicators and training a FreqAI model.
# :param timerange: TimeRange = The full data timerange for populating the indicators
# and training the model.
# :param dp: DataProvider instance attached to the strategy
# """
# if dp._exchange is not None:
# markets = [p for p, m in dp._exchange.markets.items() if market_is_active(m)
# or config.get('include_inactive')]
# else:
# # This should not occur:
# raise OperationalException('No exchange object found.')
# all_pairs = dynamic_expand_pairlist(config, markets)
# if not dp._exchange:
# # Not realistic - this is only called in live mode.
# raise OperationalException("Dataprovider did not have an exchange attached.")
# time = datetime.now(tz=timezone.utc).timestamp()
# for tf in config["freqai"]["feature_parameters"].get("include_timeframes"):
# timerange = TimeRange()
# timerange.startts = int(time)
# timerange.stopts = int(time)
# startup_candles = dp.get_required_startup(str(tf))
# tf_seconds = timeframe_to_seconds(str(tf))
# timerange.subtract_start(tf_seconds * startup_candles)
# new_pairs_days = int((timerange.stopts - timerange.startts) / 86400)
# # FIXME: now that we are looping on `refresh_backtest_ohlcv_data`, the function
# # redownloads the funding rate for each pair.
# refresh_backtest_ohlcv_data(
# dp._exchange,
# pairs=all_pairs,
# timeframes=[tf],
# datadir=config["datadir"],
# timerange=timerange,
# new_pairs_days=new_pairs_days,
# erase=False,
# data_format=config.get("dataformat_ohlcv", "json"),
# trading_mode=config.get("trading_mode", "spot"),
# prepend=config.get("prepend_data", False),
# )

View File

@ -21,8 +21,7 @@ from freqtrade.enums import (ExitCheckTuple, ExitType, RPCMessageType, RunMode,
State, TradingMode) State, TradingMode)
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError, from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
InvalidOrderException, PricingError) InvalidOrderException, PricingError)
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds
from freqtrade.exchange.exchange import timeframe_to_next_date
from freqtrade.misc import safe_value_fallback, safe_value_fallback2 from freqtrade.misc import safe_value_fallback, safe_value_fallback2
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.persistence import Order, PairLocks, Trade, init_db from freqtrade.persistence import Order, PairLocks, Trade, init_db
@ -240,7 +239,7 @@ class FreqtradeBot(LoggingMixin):
'status': 'status':
f"{len(open_trades)} open trades active.\n\n" f"{len(open_trades)} open trades active.\n\n"
f"Handle these trades manually on {self.exchange.name}, " f"Handle these trades manually on {self.exchange.name}, "
f"or '/start' the bot again and use '/stopbuy' " f"or '/start' the bot again and use '/stopentry' "
f"to handle open trades gracefully. \n" f"to handle open trades gracefully. \n"
f"{'Note: Trades are simulated (dry run).' if self.config['dry_run'] else ''}", f"{'Note: Trades are simulated (dry run).' if self.config['dry_run'] else ''}",
} }
@ -1553,9 +1552,10 @@ class FreqtradeBot(LoggingMixin):
trade.close_rate_requested = limit trade.close_rate_requested = limit
trade.exit_reason = exit_reason trade.exit_reason = exit_reason
# Lock pair for one candle to prevent immediate re-trading if not sub_trade_amt:
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc), # Lock pair for one candle to prevent immediate re-trading
reason='Auto lock') self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),
reason='Auto lock')
self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj) self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj)
# In case of market sell orders the order can be closed immediately # In case of market sell orders the order can be closed immediately
@ -1732,11 +1732,12 @@ class FreqtradeBot(LoggingMixin):
# TODO: Margin will need to use interest_rate as well. # TODO: Margin will need to use interest_rate as well.
# interest_rate = self.exchange.get_interest_rate() # interest_rate = self.exchange.get_interest_rate()
trade.set_liquidation_price(self.exchange.get_liquidation_price( trade.set_liquidation_price(self.exchange.get_liquidation_price(
leverage=trade.leverage,
pair=trade.pair, pair=trade.pair,
amount=trade.amount,
open_rate=trade.open_rate, open_rate=trade.open_rate,
is_short=trade.is_short is_short=trade.is_short,
amount=trade.amount,
stake_amount=trade.stake_amount,
wallet_balance=trade.stake_amount,
)) ))
# Updating wallets when order is closed # Updating wallets when order is closed
@ -1777,7 +1778,7 @@ class FreqtradeBot(LoggingMixin):
self.rpc.send_msg(msg) self.rpc.send_msg(msg)
def apply_fee_conditional(self, trade: Trade, trade_base_currency: str, def apply_fee_conditional(self, trade: Trade, trade_base_currency: str,
amount: float, fee_abs: float) -> float: amount: float, fee_abs: float, order_obj: Order) -> Optional[float]:
""" """
Applies the fee to amount (either from Order or from Trades). Applies the fee to amount (either from Order or from Trades).
Can eat into dust if more than the required asset is available. Can eat into dust if more than the required asset is available.
@ -1785,40 +1786,42 @@ class FreqtradeBot(LoggingMixin):
never in base currency. never in base currency.
""" """
self.wallets.update() self.wallets.update()
if fee_abs != 0 and self.wallets.get_free(trade_base_currency) >= amount: amount_ = amount
if order_obj.ft_order_side == trade.exit_side or order_obj.ft_order_side == 'stoploss':
# check against remaining amount!
amount_ = trade.amount - amount
if fee_abs != 0 and self.wallets.get_free(trade_base_currency) >= amount_:
# Eat into dust if we own more than base currency # Eat into dust if we own more than base currency
logger.info(f"Fee amount for {trade} was in base currency - " logger.info(f"Fee amount for {trade} was in base currency - "
f"Eating Fee {fee_abs} into dust.") f"Eating Fee {fee_abs} into dust.")
elif fee_abs != 0: elif fee_abs != 0:
real_amount = self.exchange.amount_to_precision(trade.pair, amount - fee_abs) logger.info(f"Applying fee on amount for {trade}, fee={fee_abs}.")
logger.info(f"Applying fee on amount for {trade} " return fee_abs
f"(from {amount} to {real_amount}).") return None
return real_amount
return amount
def handle_order_fee(self, trade: Trade, order_obj: Order, order: Dict[str, Any]) -> None: def handle_order_fee(self, trade: Trade, order_obj: Order, order: Dict[str, Any]) -> None:
# Try update amount (binance-fix) # Try update amount (binance-fix)
try: try:
new_amount = self.get_real_amount(trade, order, order_obj) fee_abs = self.get_real_amount(trade, order, order_obj)
if not isclose(safe_value_fallback(order, 'filled', 'amount'), new_amount, if fee_abs is not None:
abs_tol=constants.MATH_CLOSE_PREC): order_obj.ft_fee_base = fee_abs
order_obj.ft_fee_base = trade.amount - new_amount
except DependencyException as exception: except DependencyException as exception:
logger.warning("Could not update trade amount: %s", exception) logger.warning("Could not update trade amount: %s", exception)
def get_real_amount(self, trade: Trade, order: Dict, order_obj: Order) -> float: def get_real_amount(self, trade: Trade, order: Dict, order_obj: Order) -> Optional[float]:
""" """
Detect and update trade fee. Detect and update trade fee.
Calls trade.update_fee() upon correct detection. Calls trade.update_fee() upon correct detection.
Returns modified amount if the fee was taken from the destination currency. Returns modified amount if the fee was taken from the destination currency.
Necessary for exchanges which charge fees in base currency (e.g. binance) Necessary for exchanges which charge fees in base currency (e.g. binance)
:return: identical (or new) amount for the trade :return: Absolute fee to apply for this order or None
""" """
# Init variables # Init variables
order_amount = safe_value_fallback(order, 'filled', 'amount') order_amount = safe_value_fallback(order, 'filled', 'amount')
# Only run for closed orders # Only run for closed orders
if trade.fee_updated(order.get('side', '')) or order['status'] == 'open': if trade.fee_updated(order.get('side', '')) or order['status'] == 'open':
return order_amount return None
trade_base_currency = self.exchange.get_pair_base_currency(trade.pair) trade_base_currency = self.exchange.get_pair_base_currency(trade.pair)
# use fee from order-dict if possible # use fee from order-dict if possible
@ -1835,13 +1838,14 @@ class FreqtradeBot(LoggingMixin):
if trade_base_currency == fee_currency: if trade_base_currency == fee_currency:
# Apply fee to amount # Apply fee to amount
return self.apply_fee_conditional(trade, trade_base_currency, return self.apply_fee_conditional(trade, trade_base_currency,
amount=order_amount, fee_abs=fee_cost) amount=order_amount, fee_abs=fee_cost,
return order_amount order_obj=order_obj)
return None
return self.fee_detection_from_trades( return self.fee_detection_from_trades(
trade, order, order_obj, order_amount, order.get('trades', [])) trade, order, order_obj, order_amount, order.get('trades', []))
def fee_detection_from_trades(self, trade: Trade, order: Dict, order_obj: Order, def fee_detection_from_trades(self, trade: Trade, order: Dict, order_obj: Order,
order_amount: float, trades: List) -> float: order_amount: float, trades: List) -> Optional[float]:
""" """
fee-detection fallback to Trades. fee-detection fallback to Trades.
Either uses provided trades list or the result of fetch_my_trades to get correct fee. Either uses provided trades list or the result of fetch_my_trades to get correct fee.
@ -1852,7 +1856,7 @@ class FreqtradeBot(LoggingMixin):
if len(trades) == 0: if len(trades) == 0:
logger.info("Applying fee on amount for %s failed: myTrade-Dict empty found", trade) logger.info("Applying fee on amount for %s failed: myTrade-Dict empty found", trade)
return order_amount return None
fee_currency = None fee_currency = None
amount = 0 amount = 0
fee_abs = 0.0 fee_abs = 0.0
@ -1894,10 +1898,9 @@ class FreqtradeBot(LoggingMixin):
raise DependencyException("Half bought? Amounts don't match") raise DependencyException("Half bought? Amounts don't match")
if fee_abs != 0: if fee_abs != 0:
return self.apply_fee_conditional(trade, trade_base_currency, return self.apply_fee_conditional(
amount=amount, fee_abs=fee_abs) trade, trade_base_currency, amount=amount, fee_abs=fee_abs, order_obj=order_obj)
else: return None
return amount
def get_valid_price(self, custom_price: float, proposed_price: float) -> float: def get_valid_price(self, custom_price: float, proposed_price: float) -> float:
""" """

View File

@ -23,9 +23,8 @@ from freqtrade.data.dataprovider import DataProvider
from freqtrade.enums import (BacktestState, CandleType, ExitCheckTuple, ExitType, RunMode, from freqtrade.enums import (BacktestState, CandleType, ExitCheckTuple, ExitType, RunMode,
TradingMode) TradingMode)
from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange import (amount_to_contract_precision, price_to_precision,
from freqtrade.exchange.exchange import (amount_to_contracts, amount_to_precision, timeframe_to_minutes, timeframe_to_seconds)
contracts_to_amount)
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.optimize.backtest_caching import get_strategy_run_id from freqtrade.optimize.backtest_caching import get_strategy_run_id
from freqtrade.optimize.bt_progress import BTProgress from freqtrade.optimize.bt_progress import BTProgress
@ -213,21 +212,12 @@ class Backtesting:
""" """
self.progress.init_step(BacktestState.DATALOAD, 1) self.progress.init_step(BacktestState.DATALOAD, 1)
if self.config.get('freqai', {}).get('enabled', False):
startup_candles = int(self.config.get('freqai', {}).get('startup_candles', 0))
if not startup_candles:
raise OperationalException('FreqAI backtesting module requires user set '
'startup_candles in config.')
self.required_startup += int(self.config.get('freqai', {}).get('startup_candles', 0))
logger.info(f'Increasing startup_candle_count for freqai to {self.required_startup}')
self.config['startup_candle_count'] = self.required_startup
data = history.load_data( data = history.load_data(
datadir=self.config['datadir'], datadir=self.config['datadir'],
pairs=self.pairlists.whitelist, pairs=self.pairlists.whitelist,
timeframe=self.timeframe, timeframe=self.timeframe,
timerange=self.timerange, timerange=self.timerange,
startup_candles=self.required_startup, startup_candles=self.dataprovider.get_required_startup(self.timeframe),
fail_without_data=True, fail_without_data=True,
data_format=self.config.get('dataformat_ohlcv', 'json'), data_format=self.config.get('dataformat_ohlcv', 'json'),
candle_type=self.config.get('candle_type_def', CandleType.SPOT) candle_type=self.config.get('candle_type_def', CandleType.SPOT)
@ -535,12 +525,16 @@ class Backtesting:
# Check if we should increase our position # Check if we should increase our position
if stake_amount is not None and stake_amount > 0.0: if stake_amount is not None and stake_amount > 0.0:
check_adjust_entry = True
pos_trade = self._enter_trade( if self.strategy.max_entry_position_adjustment > -1:
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade) entry_count = trade.nr_of_successful_entries
if pos_trade is not None: check_adjust_entry = (entry_count <= self.strategy.max_entry_position_adjustment)
self.wallets.update() if check_adjust_entry:
return pos_trade pos_trade = self._enter_trade(
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade)
if pos_trade is not None:
self.wallets.update()
return pos_trade
if stake_amount is not None and stake_amount < 0.0: if stake_amount is not None and stake_amount < 0.0:
amount = abs(stake_amount) / current_rate amount = abs(stake_amount) / current_rate
@ -551,7 +545,8 @@ class Backtesting:
if remaining < min_stake: if remaining < min_stake:
# Remaining stake is too low to be sold. # Remaining stake is too low to be sold.
return trade return trade
pos_trade = self._exit_trade(trade, row, current_rate, amount) exit_ = ExitCheckTuple(ExitType.PARTIAL_EXIT)
pos_trade = self._get_exit_for_signal(trade, row, exit_, amount)
if pos_trade is not None: if pos_trade is not None:
order = pos_trade.orders[-1] order = pos_trade.orders[-1]
if self._get_order_filled(order.price, row): if self._get_order_filled(order.price, row):
@ -571,12 +566,7 @@ class Backtesting:
# Check if we need to adjust our current positions # Check if we need to adjust our current positions
if self.strategy.position_adjustment_enable: if self.strategy.position_adjustment_enable:
check_adjust_entry = True trade = self._get_adjust_trade_entry_for_candle(trade, row)
if self.strategy.max_entry_position_adjustment > -1:
entry_count = trade.nr_of_successful_entries
check_adjust_entry = (entry_count <= self.strategy.max_entry_position_adjustment)
if check_adjust_entry:
trade = self._get_adjust_trade_entry_for_candle(trade, row)
enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX] enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX]
exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX] exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX]
@ -591,14 +581,15 @@ class Backtesting:
return t return t
return None return None
def _get_exit_for_signal(self, trade: LocalTrade, row: Tuple, def _get_exit_for_signal(
exit_: ExitCheckTuple) -> Optional[LocalTrade]: self, trade: LocalTrade, row: Tuple, exit_: ExitCheckTuple,
amount: Optional[float] = None) -> Optional[LocalTrade]:
exit_candle_time: datetime = row[DATE_IDX].to_pydatetime() exit_candle_time: datetime = row[DATE_IDX].to_pydatetime()
if exit_.exit_flag: if exit_.exit_flag:
trade.close_date = exit_candle_time trade.close_date = exit_candle_time
exit_reason = exit_.exit_reason exit_reason = exit_.exit_reason
amount_ = amount if amount is not None else trade.amount
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60) trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
try: try:
close_rate = self._get_close_rate(row, trade, exit_, trade_dur) close_rate = self._get_close_rate(row, trade, exit_, trade_dur)
@ -607,7 +598,8 @@ class Backtesting:
# call the custom exit price,with default value as previous close_rate # call the custom exit price,with default value as previous close_rate
current_profit = trade.calc_profit_ratio(close_rate) current_profit = trade.calc_profit_ratio(close_rate)
order_type = self.strategy.order_types['exit'] order_type = self.strategy.order_types['exit']
if exit_.exit_type in (ExitType.EXIT_SIGNAL, ExitType.CUSTOM_EXIT): if exit_.exit_type in (ExitType.EXIT_SIGNAL, ExitType.CUSTOM_EXIT,
ExitType.PARTIAL_EXIT):
# Checks and adds an exit tag, after checking that the length of the # Checks and adds an exit tag, after checking that the length of the
# row has the length for an exit tag column # row has the length for an exit tag column
if ( if (
@ -635,22 +627,23 @@ class Backtesting:
# Confirm trade exit: # Confirm trade exit:
time_in_force = self.strategy.order_time_in_force['exit'] time_in_force = self.strategy.order_time_in_force['exit']
if (exit_.exit_type != ExitType.LIQUIDATION and not strategy_safe_wrapper( if (exit_.exit_type not in (ExitType.LIQUIDATION, ExitType.PARTIAL_EXIT)
self.strategy.confirm_trade_exit, default_retval=True)( and not strategy_safe_wrapper(
pair=trade.pair, self.strategy.confirm_trade_exit, default_retval=True)(
trade=trade, # type: ignore[arg-type] pair=trade.pair,
order_type=order_type, trade=trade, # type: ignore[arg-type]
amount=trade.amount, order_type=order_type,
rate=close_rate, amount=amount_,
time_in_force=time_in_force, rate=close_rate,
sell_reason=exit_reason, # deprecated time_in_force=time_in_force,
exit_reason=exit_reason, sell_reason=exit_reason, # deprecated
current_time=exit_candle_time)): exit_reason=exit_reason,
current_time=exit_candle_time)):
return None return None
trade.exit_reason = exit_reason trade.exit_reason = exit_reason
return self._exit_trade(trade, row, close_rate, trade.amount) return self._exit_trade(trade, row, close_rate, amount_)
return None return None
def _exit_trade(self, trade: LocalTrade, sell_row: Tuple, def _exit_trade(self, trade: LocalTrade, sell_row: Tuple,
@ -658,7 +651,10 @@ class Backtesting:
self.order_id_counter += 1 self.order_id_counter += 1
exit_candle_time = sell_row[DATE_IDX].to_pydatetime() exit_candle_time = sell_row[DATE_IDX].to_pydatetime()
order_type = self.strategy.order_types['exit'] order_type = self.strategy.order_types['exit']
amount = amount or trade.amount # amount = amount or trade.amount
amount = amount_to_contract_precision(amount or trade.amount, trade.amount_precision,
self.precision_mode, trade.contract_size)
rate = price_to_precision(close_rate, trade.price_precision, self.precision_mode)
order = Order( order = Order(
id=self.order_id_counter, id=self.order_id_counter,
ft_trade_id=trade.id, ft_trade_id=trade.id,
@ -672,12 +668,12 @@ class Backtesting:
side=trade.exit_side, side=trade.exit_side,
order_type=order_type, order_type=order_type,
status="open", status="open",
price=close_rate, price=rate,
average=close_rate, average=rate,
amount=amount, amount=amount,
filled=0, filled=0,
remaining=amount, remaining=amount,
cost=amount * close_rate, cost=amount * rate,
) )
trade.orders.append(order) trade.orders.append(order)
return trade return trade
@ -823,14 +819,14 @@ class Backtesting:
if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount): if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount):
self.order_id_counter += 1 self.order_id_counter += 1
base_currency = self.exchange.get_pair_base_currency(pair) base_currency = self.exchange.get_pair_base_currency(pair)
precision_price = self.exchange.get_precision_price(pair)
propose_rate = price_to_precision(propose_rate, precision_price, self.precision_mode)
amount_p = (stake_amount / propose_rate) * leverage amount_p = (stake_amount / propose_rate) * leverage
contract_size = self.exchange.get_contract_size(pair) contract_size = self.exchange.get_contract_size(pair)
precision_amount = self.exchange.get_precision_amount(pair) precision_amount = self.exchange.get_precision_amount(pair)
amount = contracts_to_amount( amount = amount_to_contract_precision(amount_p, precision_amount, self.precision_mode,
amount_to_precision( contract_size)
amount_to_contracts(amount_p, contract_size),
precision_amount, self.precision_mode),
contract_size)
# Backcalculate actual stake amount. # Backcalculate actual stake amount.
stake_amount = amount * propose_rate / leverage stake_amount = amount * propose_rate / leverage
@ -863,7 +859,7 @@ class Backtesting:
leverage=leverage, leverage=leverage,
# interest_rate=interest_rate, # interest_rate=interest_rate,
amount_precision=precision_amount, amount_precision=precision_amount,
price_precision=self.exchange.get_precision_price(pair), price_precision=precision_price,
precision_mode=self.precision_mode, precision_mode=self.precision_mode,
contract_size=contract_size, contract_size=contract_size,
orders=[], orders=[],
@ -875,7 +871,8 @@ class Backtesting:
pair=pair, pair=pair,
open_rate=propose_rate, open_rate=propose_rate,
amount=amount, amount=amount,
leverage=leverage, stake_amount=trade.stake_amount,
wallet_balance=trade.stake_amount,
is_short=is_short, is_short=is_short,
)) ))

View File

@ -24,13 +24,15 @@ from pandas import DataFrame
from freqtrade.constants import DATETIME_PRINT_FORMAT, FTHYPT_FILEVERSION, LAST_BT_RESULT_FN from freqtrade.constants import DATETIME_PRINT_FORMAT, FTHYPT_FILEVERSION, LAST_BT_RESULT_FN
from freqtrade.data.converter import trim_dataframes from freqtrade.data.converter import trim_dataframes
from freqtrade.data.history import get_timerange from freqtrade.data.history import get_timerange
from freqtrade.enums import HyperoptState
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.misc import deep_merge_dicts, file_dump_json, plural from freqtrade.misc import deep_merge_dicts, file_dump_json, plural
from freqtrade.optimize.backtesting import Backtesting from freqtrade.optimize.backtesting import Backtesting
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules # Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
from freqtrade.optimize.hyperopt_auto import HyperOptAuto from freqtrade.optimize.hyperopt_auto import HyperOptAuto
from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss from freqtrade.optimize.hyperopt_loss_interface import IHyperOptLoss
from freqtrade.optimize.hyperopt_tools import HyperoptTools, hyperopt_serializer from freqtrade.optimize.hyperopt_tools import (HyperoptStateContainer, HyperoptTools,
hyperopt_serializer)
from freqtrade.optimize.optimize_reports import generate_strategy_stats from freqtrade.optimize.optimize_reports import generate_strategy_stats
from freqtrade.resolvers.hyperopt_resolver import HyperOptLossResolver from freqtrade.resolvers.hyperopt_resolver import HyperOptLossResolver
@ -74,10 +76,14 @@ class Hyperopt:
self.dimensions: List[Dimension] = [] self.dimensions: List[Dimension] = []
self.config = config self.config = config
self.min_date: datetime
self.max_date: datetime
self.backtesting = Backtesting(self.config) self.backtesting = Backtesting(self.config)
self.pairlist = self.backtesting.pairlists.whitelist self.pairlist = self.backtesting.pairlists.whitelist
self.custom_hyperopt: HyperOptAuto self.custom_hyperopt: HyperOptAuto
self.analyze_per_epoch = self.config.get('analyze_per_epoch', False)
HyperoptStateContainer.set_state(HyperoptState.STARTUP)
if not self.config.get('hyperopt'): if not self.config.get('hyperopt'):
self.custom_hyperopt = HyperOptAuto(self.config) self.custom_hyperopt = HyperOptAuto(self.config)
@ -290,6 +296,7 @@ class Hyperopt:
Called once per epoch to optimize whatever is configured. Called once per epoch to optimize whatever is configured.
Keep this function as optimized as possible! Keep this function as optimized as possible!
""" """
HyperoptStateContainer.set_state(HyperoptState.OPTIMIZE)
backtest_start_time = datetime.now(timezone.utc) backtest_start_time = datetime.now(timezone.utc)
params_dict = self._get_params_dict(self.dimensions, raw_params) params_dict = self._get_params_dict(self.dimensions, raw_params)
@ -321,6 +328,10 @@ class Hyperopt:
with self.data_pickle_file.open('rb') as f: with self.data_pickle_file.open('rb') as f:
processed = load(f, mmap_mode='r') processed = load(f, mmap_mode='r')
if self.analyze_per_epoch:
# Data is not yet analyzed, rerun populate_indicators.
processed = self.advise_and_trim(processed)
bt_results = self.backtesting.backtest( bt_results = self.backtesting.backtest(
processed=processed, processed=processed,
start_date=self.min_date, start_date=self.min_date,
@ -406,22 +417,33 @@ class Hyperopt:
def _set_random_state(self, random_state: Optional[int]) -> int: def _set_random_state(self, random_state: Optional[int]) -> int:
return random_state or random.randint(1, 2**16 - 1) return random_state or random.randint(1, 2**16 - 1)
def prepare_hyperopt_data(self) -> None: def advise_and_trim(self, data: Dict[str, DataFrame]) -> Dict[str, DataFrame]:
data, timerange = self.backtesting.load_bt_data()
self.backtesting.load_bt_data_detail()
logger.info("Dataload complete. Calculating indicators")
preprocessed = self.backtesting.strategy.advise_all_indicators(data) preprocessed = self.backtesting.strategy.advise_all_indicators(data)
# Trim startup period from analyzed dataframe to get correct dates for output. # Trim startup period from analyzed dataframe to get correct dates for output.
processed = trim_dataframes(preprocessed, timerange, self.backtesting.required_startup) processed = trim_dataframes(preprocessed, self.timerange, self.backtesting.required_startup)
self.min_date, self.max_date = get_timerange(processed) self.min_date, self.max_date = get_timerange(processed)
return processed
logger.info(f'Hyperopting with data from {self.min_date.strftime(DATETIME_PRINT_FORMAT)} ' def prepare_hyperopt_data(self) -> None:
f'up to {self.max_date.strftime(DATETIME_PRINT_FORMAT)} ' HyperoptStateContainer.set_state(HyperoptState.DATALOAD)
f'({(self.max_date - self.min_date).days} days)..') data, self.timerange = self.backtesting.load_bt_data()
# Store non-trimmed data - will be trimmed after signal generation. self.backtesting.load_bt_data_detail()
dump(preprocessed, self.data_pickle_file) logger.info("Dataload complete. Calculating indicators")
if not self.analyze_per_epoch:
HyperoptStateContainer.set_state(HyperoptState.INDICATORS)
preprocessed = self.advise_and_trim(data)
logger.info(f'Hyperopting with data from '
f'{self.min_date.strftime(DATETIME_PRINT_FORMAT)} '
f'up to {self.max_date.strftime(DATETIME_PRINT_FORMAT)} '
f'({(self.max_date - self.min_date).days} days)..')
# Store non-trimmed data - will be trimmed after signal generation.
dump(preprocessed, self.data_pickle_file)
else:
dump(data, self.data_pickle_file)
def get_asked_points(self, n_points: int) -> Tuple[List[List[Any]], List[bool]]: def get_asked_points(self, n_points: int) -> Tuple[List[List[Any]], List[bool]]:
""" """

View File

@ -13,6 +13,7 @@ from colorama import Fore, Style
from pandas import isna, json_normalize from pandas import isna, json_normalize
from freqtrade.constants import FTHYPT_FILEVERSION, USERPATH_STRATEGIES from freqtrade.constants import FTHYPT_FILEVERSION, USERPATH_STRATEGIES
from freqtrade.enums import HyperoptState
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.misc import deep_merge_dicts, round_coin_value, round_dict, safe_value_fallback2 from freqtrade.misc import deep_merge_dicts, round_coin_value, round_dict, safe_value_fallback2
from freqtrade.optimize.hyperopt_epoch_filters import hyperopt_filter_epochs from freqtrade.optimize.hyperopt_epoch_filters import hyperopt_filter_epochs
@ -32,6 +33,15 @@ def hyperopt_serializer(x):
return str(x) return str(x)
class HyperoptStateContainer():
""" Singleton class to track state of hyperopt"""
state: HyperoptState = HyperoptState.OPTIMIZE
@classmethod
def set_state(cls, value: HyperoptState):
cls.state = value
class HyperoptTools(): class HyperoptTools():
@staticmethod @staticmethod

View File

@ -14,8 +14,7 @@ from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPE
BuySell, LongShort) BuySell, LongShort)
from freqtrade.enums import ExitType, TradingMode from freqtrade.enums import ExitType, TradingMode
from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import amount_to_precision, price_to_precision from freqtrade.exchange import amount_to_contract_precision, price_to_precision
from freqtrade.exchange.exchange import amount_to_contracts, contracts_to_amount
from freqtrade.leverage import interest from freqtrade.leverage import interest
from freqtrade.persistence.base import _DECL_BASE from freqtrade.persistence.base import _DECL_BASE
from freqtrade.util import FtPrecise from freqtrade.util import FtPrecise
@ -625,11 +624,8 @@ class LocalTrade():
else: else:
logger.warning( logger.warning(
f'Got different open_order_id {self.open_order_id} != {order.order_id}') f'Got different open_order_id {self.open_order_id} != {order.order_id}')
amount_tr = contracts_to_amount( amount_tr = amount_to_contract_precision(self.amount, self.amount_precision,
amount_to_precision( self.precision_mode, self.contract_size)
amount_to_contracts(self.amount, self.contract_size),
self.amount_precision, self.precision_mode),
self.contract_size)
if isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC): if isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC):
self.close(order.safe_price) self.close(order.safe_price)
else: else:
@ -652,7 +648,6 @@ class LocalTrade():
""" """
self.close_rate = rate self.close_rate = rate
self.close_date = self.close_date or datetime.utcnow() self.close_date = self.close_date or datetime.utcnow()
self.close_profit_abs = self.calc_profit(rate) + self.realized_profit
self.is_open = False self.is_open = False
self.exit_order_status = 'closed' self.exit_order_status = 'closed'
self.open_order_id = None self.open_order_id = None
@ -847,7 +842,7 @@ class LocalTrade():
avg_price = FtPrecise(0.0) avg_price = FtPrecise(0.0)
close_profit = 0.0 close_profit = 0.0
close_profit_abs = 0.0 close_profit_abs = 0.0
profit = None
for o in self.orders: for o in self.orders:
if o.ft_is_open or not o.filled: if o.ft_is_open or not o.filled:
continue continue
@ -874,8 +869,6 @@ class LocalTrade():
close_profit_abs += profit close_profit_abs += profit
close_profit = self.calc_profit_ratio( close_profit = self.calc_profit_ratio(
exit_rate, amount=exit_amount, open_rate=avg_price) exit_rate, amount=exit_amount, open_rate=avg_price)
if current_amount <= ZERO:
profit = close_profit_abs
else: else:
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price) total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
@ -884,8 +877,8 @@ class LocalTrade():
self.realized_profit = close_profit_abs self.realized_profit = close_profit_abs
self.close_profit_abs = profit self.close_profit_abs = profit
current_amount_tr = amount_to_precision(float(current_amount), current_amount_tr = amount_to_contract_precision(
self.amount_precision, self.precision_mode) float(current_amount), self.amount_precision, self.precision_mode, self.contract_size)
if current_amount_tr > 0.0: if current_amount_tr > 0.0:
# Trade is still open # Trade is still open
# Leverage not updated, as we don't allow changing leverage through DCA at the moment. # Leverage not updated, as we don't allow changing leverage through DCA at the moment.
@ -900,6 +893,7 @@ class LocalTrade():
# Close profit abs / maximum owned # Close profit abs / maximum owned
# Fees are considered as they are part of close_profit_abs # Fees are considered as they are part of close_profit_abs
self.close_profit = (close_profit_abs / total_stake) * self.leverage self.close_profit = (close_profit_abs / total_stake) * self.leverage
self.close_profit_abs = close_profit_abs
def select_order_by_order_id(self, order_id: str) -> Optional[Order]: def select_order_by_order_id(self, order_id: str) -> Optional[Order]:
""" """

View File

@ -52,7 +52,7 @@ class PrecisionFilter(IPairList):
:return: True if the pair can stay, false if it should be removed :return: True if the pair can stay, false if it should be removed
""" """
if ticker.get('last', None) is None: if ticker.get('last', None) is None:
self.log_once(f"Removed {ticker['symbol']} from whitelist, because " self.log_once(f"Removed {pair} from whitelist, because "
"ticker['last'] is empty (Usually no trade in the last 24h).", "ticker['last'] is empty (Usually no trade in the last 24h).",
logger.info) logger.info)
return False return False
@ -62,10 +62,10 @@ class PrecisionFilter(IPairList):
sp = self._exchange.price_to_precision(pair, stop_price) sp = self._exchange.price_to_precision(pair, stop_price)
stop_gap_price = self._exchange.price_to_precision(pair, stop_price * 0.99) stop_gap_price = self._exchange.price_to_precision(pair, stop_price * 0.99)
logger.debug(f"{ticker['symbol']} - {sp} : {stop_gap_price}") logger.debug(f"{pair} - {sp} : {stop_gap_price}")
if sp <= stop_gap_price: if sp <= stop_gap_price:
self.log_once(f"Removed {ticker['symbol']} from whitelist, because " self.log_once(f"Removed {pair} from whitelist, because "
f"stop price {sp} would be <= stop limit {stop_gap_price}", logger.info) f"stop price {sp} would be <= stop limit {stop_gap_price}", logger.info)
return False return False

View File

@ -186,6 +186,7 @@ class VolumePairList(IPairList):
needed_pairs, since_ms=since_ms, cache=False needed_pairs, since_ms=since_ms, cache=False
) )
for i, p in enumerate(filtered_tickers): for i, p in enumerate(filtered_tickers):
contract_size = self._exchange.markets[p['symbol']].get('contractSize', 1.0) or 1.0
pair_candles = candles[ pair_candles = candles[
(p['symbol'], self._lookback_timeframe, self._def_candletype) (p['symbol'], self._lookback_timeframe, self._def_candletype)
] if ( ] if (
@ -199,6 +200,7 @@ class VolumePairList(IPairList):
pair_candles['quoteVolume'] = ( pair_candles['quoteVolume'] = (
pair_candles['volume'] * pair_candles['typical_price'] pair_candles['volume'] * pair_candles['typical_price']
* contract_size
) )
else: else:
# Exchange ohlcv data is in quote volume already. # Exchange ohlcv data is in quote volume already.

View File

@ -216,9 +216,10 @@ def stop(rpc: RPC = Depends(get_rpc)):
return rpc._rpc_stop() return rpc._rpc_stop()
@router.post('/stopentry', response_model=StatusMsg, tags=['botcontrol'])
@router.post('/stopbuy', response_model=StatusMsg, tags=['botcontrol']) @router.post('/stopbuy', response_model=StatusMsg, tags=['botcontrol'])
def stop_buy(rpc: RPC = Depends(get_rpc)): def stop_buy(rpc: RPC = Depends(get_rpc)):
return rpc._rpc_stopbuy() return rpc._rpc_stopentry()
@router.post('/reload_config', response_model=StatusMsg, tags=['botcontrol']) @router.post('/reload_config', response_model=StatusMsg, tags=['botcontrol'])

View File

@ -657,7 +657,7 @@ class RPC:
self._freqtrade.state = State.RELOAD_CONFIG self._freqtrade.state = State.RELOAD_CONFIG
return {'status': 'Reloading config ...'} return {'status': 'Reloading config ...'}
def _rpc_stopbuy(self) -> Dict[str, str]: def _rpc_stopentry(self) -> Dict[str, str]:
""" """
Handler to stop buying, but handle open trades gracefully. Handler to stop buying, but handle open trades gracefully.
""" """
@ -665,7 +665,7 @@ class RPC:
# Set 'max_open_trades' to 0 # Set 'max_open_trades' to 0
self._freqtrade.config['max_open_trades'] = 0 self._freqtrade.config['max_open_trades'] = 0
return {'status': 'No more buy will occur from now. Run /reload_config to reset.'} return {'status': 'No more entries will occur from now. Run /reload_config to reset.'}
def __exec_force_exit(self, trade: Trade, ordertype: Optional[str], def __exec_force_exit(self, trade: Trade, ordertype: Optional[str],
amount: Optional[float] = None) -> None: amount: Optional[float] = None) -> None:

View File

@ -114,18 +114,20 @@ class Telegram(RPCHandler):
# TODO: DRY! - its not good to list all valid cmds here. But otherwise # TODO: DRY! - its not good to list all valid cmds here. But otherwise
# this needs refactoring of the whole telegram module (same # this needs refactoring of the whole telegram module (same
# problem in _help()). # problem in _help()).
valid_keys: List[str] = [r'/start$', r'/stop$', r'/status$', r'/status table$', valid_keys: List[str] = [
r'/trades$', r'/performance$', r'/buys', r'/entries', r'/start$', r'/stop$', r'/status$', r'/status table$',
r'/sells', r'/exits', r'/mix_tags', r'/trades$', r'/performance$', r'/buys', r'/entries',
r'/daily$', r'/daily \d+$', r'/profit$', r'/profit \d+', r'/sells', r'/exits', r'/mix_tags',
r'/stats$', r'/count$', r'/locks$', r'/balance$', r'/daily$', r'/daily \d+$', r'/profit$', r'/profit \d+',
r'/stopbuy$', r'/reload_config$', r'/show_config$', r'/stats$', r'/count$', r'/locks$', r'/balance$',
r'/logs$', r'/whitelist$', r'/whitelist(\ssorted|\sbaseonly)+$', r'/stopbuy$', r'/stopentry$', r'/reload_config$', r'/show_config$',
r'/blacklist$', r'/bl_delete$', r'/logs$', r'/whitelist$', r'/whitelist(\ssorted|\sbaseonly)+$',
r'/weekly$', r'/weekly \d+$', r'/monthly$', r'/monthly \d+$', r'/blacklist$', r'/bl_delete$',
r'/forcebuy$', r'/forcelong$', r'/forceshort$', r'/weekly$', r'/weekly \d+$', r'/monthly$', r'/monthly \d+$',
r'/forcesell$', r'/forceexit$', r'/forcebuy$', r'/forcelong$', r'/forceshort$',
r'/edge$', r'/health$', r'/help$', r'/version$'] r'/forcesell$', r'/forceexit$',
r'/edge$', r'/health$', r'/help$', r'/version$'
]
# Create keys for generation # Create keys for generation
valid_keys_print = [k.replace('$', '') for k in valid_keys] valid_keys_print = [k.replace('$', '') for k in valid_keys]
@ -182,7 +184,7 @@ class Telegram(RPCHandler):
CommandHandler(['unlock', 'delete_locks'], self._delete_locks), CommandHandler(['unlock', 'delete_locks'], self._delete_locks),
CommandHandler(['reload_config', 'reload_conf'], self._reload_config), CommandHandler(['reload_config', 'reload_conf'], self._reload_config),
CommandHandler(['show_config', 'show_conf'], self._show_config), CommandHandler(['show_config', 'show_conf'], self._show_config),
CommandHandler('stopbuy', self._stopbuy), CommandHandler(['stopbuy', 'stopentry'], self._stopentry),
CommandHandler('whitelist', self._whitelist), CommandHandler('whitelist', self._whitelist),
CommandHandler('blacklist', self._blacklist), CommandHandler('blacklist', self._blacklist),
CommandHandler(['blacklist_delete', 'bl_delete'], self._blacklist_delete), CommandHandler(['blacklist_delete', 'bl_delete'], self._blacklist_delete),
@ -984,7 +986,7 @@ class Telegram(RPCHandler):
self._send_msg(f"Status: `{msg['status']}`") self._send_msg(f"Status: `{msg['status']}`")
@authorized_only @authorized_only
def _stopbuy(self, update: Update, context: CallbackContext) -> None: def _stopentry(self, update: Update, context: CallbackContext) -> None:
""" """
Handler for /stop_buy. Handler for /stop_buy.
Sets max_open_trades to 0 and gracefully sells all open trades Sets max_open_trades to 0 and gracefully sells all open trades
@ -992,7 +994,7 @@ class Telegram(RPCHandler):
:param update: message update :param update: message update
:return: None :return: None
""" """
msg = self._rpc._rpc_stopbuy() msg = self._rpc._rpc_stopentry()
self._send_msg(f"Status: `{msg['status']}`") self._send_msg(f"Status: `{msg['status']}`")
@authorized_only @authorized_only
@ -1488,7 +1490,7 @@ class Telegram(RPCHandler):
"------------\n" "------------\n"
"*/start:* `Starts the trader`\n" "*/start:* `Starts the trader`\n"
"*/stop:* Stops the trader\n" "*/stop:* Stops the trader\n"
"*/stopbuy:* `Stops buying, but handles open trades gracefully` \n" "*/stopentry:* `Stops entering, but handles open trades gracefully` \n"
"*/forceexit <trade_id>|all:* `Instantly exits the given trade or all trades, " "*/forceexit <trade_id>|all:* `Instantly exits the given trade or all trades, "
"regardless of profit`\n" "regardless of profit`\n"
"*/fx <trade_id>|all:* `Alias to /forceexit`\n" "*/fx <trade_id>|all:* `Alias to /forceexit`\n"

View File

@ -78,8 +78,8 @@ class IStrategy(ABC, HyperStrategyMixin):
# Optional time in force # Optional time in force
order_time_in_force: Dict = { order_time_in_force: Dict = {
'entry': 'gtc', 'entry': 'GTC',
'exit': 'gtc', 'exit': 'GTC',
} }
# run "populate_indicators" only for new candle # run "populate_indicators" only for new candle
@ -148,10 +148,19 @@ class IStrategy(ABC, HyperStrategyMixin):
def load_freqAI_model(self) -> None: def load_freqAI_model(self) -> None:
if self.config.get('freqai', {}).get('enabled', False): if self.config.get('freqai', {}).get('enabled', False):
# Import here to avoid importing this if freqAI is disabled # Import here to avoid importing this if freqAI is disabled
from freqtrade.freqai.utils import download_all_data_for_training
from freqtrade.resolvers.freqaimodel_resolver import FreqaiModelResolver from freqtrade.resolvers.freqaimodel_resolver import FreqaiModelResolver
self.freqai = FreqaiModelResolver.load_freqaimodel(self.config) self.freqai = FreqaiModelResolver.load_freqaimodel(self.config)
self.freqai_info = self.config["freqai"] self.freqai_info = self.config["freqai"]
# download the desired data in dry/live
if self.config.get('runmode') in (RunMode.DRY_RUN, RunMode.LIVE):
logger.info(
"Downloading all training data for all pairs in whitelist and "
"corr_pairlist, this may take a while if the data is not "
"already on disk."
)
download_all_data_for_training(self.dp, self.config)
self.freqai.strategy = self self.freqai.strategy = self
else: else:
# Gracious failures if freqAI is disabled but "start" is called. # Gracious failures if freqAI is disabled but "start" is called.

View File

@ -7,6 +7,9 @@ from abc import ABC, abstractmethod
from contextlib import suppress from contextlib import suppress
from typing import Any, Optional, Sequence, Union from typing import Any, Optional, Sequence, Union
from freqtrade.enums.hyperoptstate import HyperoptState
from freqtrade.optimize.hyperopt_tools import HyperoptStateContainer
with suppress(ImportError): with suppress(ImportError):
from skopt.space import Integer, Real, Categorical from skopt.space import Integer, Real, Categorical
@ -57,6 +60,13 @@ class BaseParameter(ABC):
Get-space - will be used by Hyperopt to get the hyperopt Space Get-space - will be used by Hyperopt to get the hyperopt Space
""" """
def can_optimize(self):
return (
self.in_space
and self.optimize
and HyperoptStateContainer.state != HyperoptState.OPTIMIZE
)
class NumericParameter(BaseParameter): class NumericParameter(BaseParameter):
""" Internal parameter used for Numeric purposes """ """ Internal parameter used for Numeric purposes """
@ -133,7 +143,7 @@ class IntParameter(NumericParameter):
Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid
calculating 100ds of indicators. calculating 100ds of indicators.
""" """
if self.in_space and self.optimize: if self.can_optimize():
# Scikit-optimize ranges are "inclusive", while python's "range" is exclusive # Scikit-optimize ranges are "inclusive", while python's "range" is exclusive
return range(self.low, self.high + 1) return range(self.low, self.high + 1)
else: else:
@ -212,7 +222,7 @@ class DecimalParameter(NumericParameter):
Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid
calculating 100ds of indicators. calculating 100ds of indicators.
""" """
if self.in_space and self.optimize: if self.can_optimize():
low = int(self.low * pow(10, self._decimals)) low = int(self.low * pow(10, self._decimals))
high = int(self.high * pow(10, self._decimals)) + 1 high = int(self.high * pow(10, self._decimals)) + 1
return [round(n * pow(0.1, self._decimals), self._decimals) for n in range(low, high)] return [round(n * pow(0.1, self._decimals), self._decimals) for n in range(low, high)]
@ -261,7 +271,7 @@ class CategoricalParameter(BaseParameter):
Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid Returns a List with 1 item (`value`) in "non-hyperopt" mode, to avoid
calculating 100ds of indicators. calculating 100ds of indicators.
""" """
if self.in_space and self.optimize: if self.can_optimize():
return self.opt_range return self.opt_range
else: else:
return [self.value] return [self.value]

View File

@ -43,7 +43,8 @@ class FreqaiExampleStrategy(IStrategy):
process_only_new_candles = True process_only_new_candles = True
stoploss = -0.05 stoploss = -0.05
use_exit_signal = True use_exit_signal = True
startup_candle_count: int = 300 # this is the maximum period fed to talib (timeframe independent)
startup_candle_count: int = 40
can_short = False can_short = False
linear_roi_offset = DecimalParameter( linear_roi_offset = DecimalParameter(

View File

@ -0,0 +1,258 @@
import logging
import numpy as np
import pandas as pd
import talib.abstract as ta
from pandas import DataFrame
from technical import qtpylib
from freqtrade.strategy import IntParameter, IStrategy, merge_informative_pair
logger = logging.getLogger(__name__)
class FreqaiExampleHybridStrategy(IStrategy):
"""
Example of a hybrid FreqAI strat, designed to illustrate how a user may employ
FreqAI to bolster a typical Freqtrade strategy.
Launching this strategy would be:
freqtrade trade --strategy FreqaiExampleHyridStrategy --strategy-path freqtrade/templates
--freqaimodel CatboostClassifier --config config_examples/config_freqai.example.json
or the user simply adds this to their config:
"freqai": {
"enabled": true,
"purge_old_models": true,
"train_period_days": 15,
"identifier": "uniqe-id",
"feature_parameters": {
"include_timeframes": [
"3m",
"15m",
"1h"
],
"include_corr_pairlist": [
"BTC/USDT",
"ETH/USDT"
],
"label_period_candles": 20,
"include_shifted_candles": 2,
"DI_threshold": 0.9,
"weight_factor": 0.9,
"principal_component_analysis": false,
"use_SVM_to_remove_outliers": true,
"indicator_periods_candles": [10, 20]
},
"data_split_parameters": {
"test_size": 0,
"random_state": 1
},
"model_training_parameters": {
"n_estimators": 800
}
},
Thanks to @smarmau and @johanvulgt for developing and sharing the strategy.
"""
minimal_roi = {
"60": 0.01,
"30": 0.02,
"0": 0.04
}
plot_config = {
'main_plot': {
'tema': {},
},
'subplots': {
"MACD": {
'macd': {'color': 'blue'},
'macdsignal': {'color': 'orange'},
},
"RSI": {
'rsi': {'color': 'red'},
},
"Up_or_down": {
'&s-up_or_down': {'color': 'green'},
}
}
}
process_only_new_candles = True
stoploss = -0.05
use_exit_signal = True
startup_candle_count: int = 300
can_short = True
# Hyperoptable parameters
buy_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)
sell_rsi = IntParameter(low=50, high=100, default=70, space='sell', optimize=True, load=True)
short_rsi = IntParameter(low=51, high=100, default=70, space='sell', optimize=True, load=True)
exit_short_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)
# FreqAI required function, leave as is or add additional informatives to existing structure.
def informative_pairs(self):
whitelist_pairs = self.dp.current_whitelist()
corr_pairs = self.config["freqai"]["feature_parameters"]["include_corr_pairlist"]
informative_pairs = []
for tf in self.config["freqai"]["feature_parameters"]["include_timeframes"]:
for pair in whitelist_pairs:
informative_pairs.append((pair, tf))
for pair in corr_pairs:
if pair in whitelist_pairs:
continue # avoid duplication
informative_pairs.append((pair, tf))
return informative_pairs
# FreqAI required function, user can add or remove indicators, but general structure
# must stay the same.
def populate_any_indicators(
self, pair, df, tf, informative=None, set_generalized_indicators=False
):
"""
User feeds these indicators to FreqAI to train a classifier to decide
if the market will go up or down.
:param pair: pair to be used as informative
:param df: strategy dataframe which will receive merges from informatives
:param tf: timeframe of the dataframe which will modify the feature names
:param informative: the dataframe associated with the informative pair
"""
coin = pair.split('/')[0]
if informative is None:
informative = self.dp.get_pair_dataframe(pair, tf)
# first loop is automatically duplicating indicators for time periods
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
t = int(t)
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
informative[f"%-{coin}sma-period_{t}"] = ta.SMA(informative, timeperiod=t)
informative[f"%-{coin}ema-period_{t}"] = ta.EMA(informative, timeperiod=t)
informative[f"%-{coin}roc-period_{t}"] = ta.ROC(informative, timeperiod=t)
informative[f"%-{coin}relative_volume-period_{t}"] = (
informative["volume"] / informative["volume"].rolling(t).mean()
)
# FreqAI needs the following lines in order to detect features and automatically
# expand upon them.
indicators = [col for col in informative if col.startswith("%")]
# This loop duplicates and shifts all indicators to add a sense of recency to data
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
if n == 0:
continue
informative_shift = informative[indicators].shift(n)
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
informative = pd.concat((informative, informative_shift), axis=1)
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
skip_columns = [
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
]
df = df.drop(columns=skip_columns)
# User can set the "target" here (in present case it is the
# "up" or "down")
if set_generalized_indicators:
# User "looks into the future" here to figure out if the future
# will be "up" or "down". This same column name is available to
# the user
df['&s-up_or_down'] = np.where(df["close"].shift(-50) >
df["close"], 'up', 'down')
return df
# flake8: noqa: C901
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# User creates their own custom strat here. Present example is a supertrend
# based strategy.
dataframe = self.freqai.start(dataframe, metadata, self)
# TA indicators to combine with the Freqai targets
# RSI
dataframe['rsi'] = ta.RSI(dataframe)
# Bollinger Bands
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
dataframe['bb_lowerband'] = bollinger['lower']
dataframe['bb_middleband'] = bollinger['mid']
dataframe['bb_upperband'] = bollinger['upper']
dataframe["bb_percent"] = (
(dataframe["close"] - dataframe["bb_lowerband"]) /
(dataframe["bb_upperband"] - dataframe["bb_lowerband"])
)
dataframe["bb_width"] = (
(dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"]
)
# TEMA - Triple Exponential Moving Average
dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
return dataframe
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
df.loc[
(
# Signal: RSI crosses above 30
(qtpylib.crossed_above(df['rsi'], self.buy_rsi.value)) &
(df['tema'] <= df['bb_middleband']) & # Guard: tema below BB middle
(df['tema'] > df['tema'].shift(1)) & # Guard: tema is raising
(df['volume'] > 0) & # Make sure Volume is not 0
(df['do_predict'] == 1) & # Make sure Freqai is confident in the prediction
# Only enter trade if Freqai thinks the trend is in this direction
(df['&s-up_or_down'] == 'up')
),
'enter_long'] = 1
df.loc[
(
# Signal: RSI crosses above 70
(qtpylib.crossed_above(df['rsi'], self.short_rsi.value)) &
(df['tema'] > df['bb_middleband']) & # Guard: tema above BB middle
(df['tema'] < df['tema'].shift(1)) & # Guard: tema is falling
(df['volume'] > 0) & # Make sure Volume is not 0
(df['do_predict'] == 1) & # Make sure Freqai is confident in the prediction
# Only enter trade if Freqai thinks the trend is in this direction
(df['&s-up_or_down'] == 'down')
),
'enter_short'] = 1
return df
def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
df.loc[
(
# Signal: RSI crosses above 70
(qtpylib.crossed_above(df['rsi'], self.sell_rsi.value)) &
(df['tema'] > df['bb_middleband']) & # Guard: tema above BB middle
(df['tema'] < df['tema'].shift(1)) & # Guard: tema is falling
(df['volume'] > 0) # Make sure Volume is not 0
),
'exit_long'] = 1
df.loc[
(
# Signal: RSI crosses above 30
(qtpylib.crossed_above(df['rsi'], self.exit_short_rsi.value)) &
# Guard: tema below BB middle
(df['tema'] <= df['bb_middleband']) &
(df['tema'] > df['tema'].shift(1)) & # Guard: tema is raising
(df['volume'] > 0) # Make sure Volume is not 0
),
'exit_short'] = 1
return df

View File

@ -88,8 +88,8 @@ class {{ strategy }}(IStrategy):
# Optional order time in force. # Optional order time in force.
order_time_in_force = { order_time_in_force = {
'entry': 'gtc', 'entry': 'GTC',
'exit': 'gtc' 'exit': 'GTC'
} }
{{ plot_config | indent(4) }} {{ plot_config | indent(4) }}

View File

@ -88,8 +88,8 @@ class SampleStrategy(IStrategy):
# Optional order time in force. # Optional order time in force.
order_time_in_force = { order_time_in_force = {
'entry': 'gtc', 'entry': 'GTC',
'exit': 'gtc' 'exit': 'GTC'
} }
plot_config = { plot_config = {

View File

@ -20,7 +20,7 @@ isort==5.10.1
time-machine==2.8.1 time-machine==2.8.1
# Convert jupyter notebooks to markdown documents # Convert jupyter notebooks to markdown documents
nbconvert==6.5.3 nbconvert==7.0.0
# mypy types # mypy types
types-cachetools==5.2.1 types-cachetools==5.2.1

View File

@ -2,7 +2,7 @@
-r requirements.txt -r requirements.txt
# Required for hyperopt # Required for hyperopt
scipy==1.9.0 scipy==1.9.1
scikit-learn==1.1.2 scikit-learn==1.1.2
scikit-optimize==0.9.0 scikit-optimize==0.9.0
filelock==3.8.0 filelock==3.8.0

View File

@ -2,7 +2,7 @@ numpy==1.23.2
pandas==1.4.3 pandas==1.4.3
pandas-ta==0.3.14b pandas-ta==0.3.14b
ccxt==1.92.52 ccxt==1.92.84
# Pin cryptography for now due to rust build errors with piwheels # Pin cryptography for now due to rust build errors with piwheels
cryptography==37.0.4 cryptography==37.0.4
aiohttp==3.8.1 aiohttp==3.8.1
@ -11,7 +11,7 @@ python-telegram-bot==13.13
arrow==1.2.2 arrow==1.2.2
cachetools==4.2.2 cachetools==4.2.2
requests==2.28.1 requests==2.28.1
urllib3==1.26.11 urllib3==1.26.12
jsonschema==4.14.0 jsonschema==4.14.0
TA-Lib==0.4.24 TA-Lib==0.4.24
technical==1.3.0 technical==1.3.0
@ -28,14 +28,14 @@ py_find_1st==1.1.5
# Load ticker files 30% faster # Load ticker files 30% faster
python-rapidjson==1.8 python-rapidjson==1.8
# Properly format api responses # Properly format api responses
orjson==3.7.12 orjson==3.8.0
# Notify systemd # Notify systemd
sdnotify==0.3.2 sdnotify==0.3.2
# API Server # API Server
fastapi==0.79.1 fastapi==0.81.0
uvicorn==0.18.2 uvicorn==0.18.3
pyjwt==2.4.0 pyjwt==2.4.0
aiofiles==0.8.0 aiofiles==0.8.0
psutil==5.9.1 psutil==5.9.1

View File

@ -361,6 +361,13 @@ class FtRestClient():
""" """
return self._get("sysinfo") return self._get("sysinfo")
def health(self):
"""Provides a quick health check of the running bot.
:return: json object
"""
return self._get("health")
def add_arguments(): def add_arguments():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()

View File

@ -3085,416 +3085,416 @@ def leverage_tiers():
return { return {
"1000SHIB/USDT": [ "1000SHIB/USDT": [
{ {
'min': 0, 'minNotional': 0,
'max': 50000, 'maxNotional': 50000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 50, 'maxLeverage': 50,
'maintAmt': 0.0 'maintAmt': 0.0
}, },
{ {
'min': 50000, 'minNotional': 50000,
'max': 150000, 'maxNotional': 150000,
'mmr': 0.025, 'maintenanceMarginRate': 0.025,
'lev': 20, 'maxLeverage': 20,
'maintAmt': 750.0 'maintAmt': 750.0
}, },
{ {
'min': 150000, 'minNotional': 150000,
'max': 250000, 'maxNotional': 250000,
'mmr': 0.05, 'maintenanceMarginRate': 0.05,
'lev': 10, 'maxLeverage': 10,
'maintAmt': 4500.0 'maintAmt': 4500.0
}, },
{ {
'min': 250000, 'minNotional': 250000,
'max': 500000, 'maxNotional': 500000,
'mmr': 0.1, 'maintenanceMarginRate': 0.1,
'lev': 5, 'maxLeverage': 5,
'maintAmt': 17000.0 'maintAmt': 17000.0
}, },
{ {
'min': 500000, 'minNotional': 500000,
'max': 1000000, 'maxNotional': 1000000,
'mmr': 0.125, 'maintenanceMarginRate': 0.125,
'lev': 4, 'maxLeverage': 4,
'maintAmt': 29500.0 'maintAmt': 29500.0
}, },
{ {
'min': 1000000, 'minNotional': 1000000,
'max': 2000000, 'maxNotional': 2000000,
'mmr': 0.25, 'maintenanceMarginRate': 0.25,
'lev': 2, 'maxLeverage': 2,
'maintAmt': 154500.0 'maintAmt': 154500.0
}, },
{ {
'min': 2000000, 'minNotional': 2000000,
'max': 30000000, 'maxNotional': 30000000,
'mmr': 0.5, 'maintenanceMarginRate': 0.5,
'lev': 1, 'maxLeverage': 1,
'maintAmt': 654500.0 'maintAmt': 654500.0
}, },
], ],
"1INCH/USDT": [ "1INCH/USDT": [
{ {
'min': 0, 'minNotional': 0,
'max': 5000, 'maxNotional': 5000,
'mmr': 0.012, 'maintenanceMarginRate': 0.012,
'lev': 50, 'maxLeverage': 50,
'maintAmt': 0.0 'maintAmt': 0.0
}, },
{ {
'min': 5000, 'minNotional': 5000,
'max': 25000, 'maxNotional': 25000,
'mmr': 0.025, 'maintenanceMarginRate': 0.025,
'lev': 20, 'maxLeverage': 20,
'maintAmt': 65.0 'maintAmt': 65.0
}, },
{ {
'min': 25000, 'minNotional': 25000,
'max': 100000, 'maxNotional': 100000,
'mmr': 0.05, 'maintenanceMarginRate': 0.05,
'lev': 10, 'maxLeverage': 10,
'maintAmt': 690.0 'maintAmt': 690.0
}, },
{ {
'min': 100000, 'minNotional': 100000,
'max': 250000, 'maxNotional': 250000,
'mmr': 0.1, 'maintenanceMarginRate': 0.1,
'lev': 5, 'maxLeverage': 5,
'maintAmt': 5690.0 'maintAmt': 5690.0
}, },
{ {
'min': 250000, 'minNotional': 250000,
'max': 1000000, 'maxNotional': 1000000,
'mmr': 0.125, 'maintenanceMarginRate': 0.125,
'lev': 2, 'maxLeverage': 2,
'maintAmt': 11940.0 'maintAmt': 11940.0
}, },
{ {
'min': 1000000, 'minNotional': 1000000,
'max': 100000000, 'maxNotional': 100000000,
'mmr': 0.5, 'maintenanceMarginRate': 0.5,
'lev': 1, 'maxLeverage': 1,
'maintAmt': 386940.0 'maintAmt': 386940.0
}, },
], ],
"AAVE/USDT": [ "AAVE/USDT": [
{ {
'min': 0, 'minNotional': 0,
'max': 5000, 'maxNotional': 5000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 50, 'maxLeverage': 50,
'maintAmt': 0.0 'maintAmt': 0.0
}, },
{ {
'min': 5000, 'minNotional': 5000,
'max': 25000, 'maxNotional': 25000,
'mmr': 0.02, 'maintenanceMarginRate': 0.02,
'lev': 25, 'maxLeverage': 25,
'maintAmt': 75.0 'maintAmt': 75.0
}, },
{ {
'min': 25000, 'minNotional': 25000,
'max': 100000, 'maxNotional': 100000,
'mmr': 0.05, 'maintenanceMarginRate': 0.05,
'lev': 10, 'maxLeverage': 10,
'maintAmt': 700.0 'maintAmt': 700.0
}, },
{ {
'min': 100000, 'minNotional': 100000,
'max': 250000, 'maxNotional': 250000,
'mmr': 0.1, 'maintenanceMarginRate': 0.1,
'lev': 5, 'maxLeverage': 5,
'maintAmt': 5700.0 'maintAmt': 5700.0
}, },
{ {
'min': 250000, 'minNotional': 250000,
'max': 1000000, 'maxNotional': 1000000,
'mmr': 0.125, 'maintenanceMarginRate': 0.125,
'lev': 2, 'maxLeverage': 2,
'maintAmt': 11950.0 'maintAmt': 11950.0
}, },
{ {
'min': 10000000, 'minNotional': 10000000,
'max': 50000000, 'maxNotional': 50000000,
'mmr': 0.5, 'maintenanceMarginRate': 0.5,
'lev': 1, 'maxLeverage': 1,
'maintAmt': 386950.0 'maintAmt': 386950.0
}, },
], ],
"ADA/BUSD": [ "ADA/BUSD": [
{ {
"min": 0, "minNotional": 0,
"max": 100000, "maxNotional": 100000,
"mmr": 0.025, "maintenanceMarginRate": 0.025,
"lev": 20, "maxLeverage": 20,
"maintAmt": 0.0 "maintAmt": 0.0
}, },
{ {
"min": 100000, "minNotional": 100000,
"max": 500000, "maxNotional": 500000,
"mmr": 0.05, "maintenanceMarginRate": 0.05,
"lev": 10, "maxLeverage": 10,
"maintAmt": 2500.0 "maintAmt": 2500.0
}, },
{ {
"min": 500000, "minNotional": 500000,
"max": 1000000, "maxNotional": 1000000,
"mmr": 0.1, "maintenanceMarginRate": 0.1,
"lev": 5, "maxLeverage": 5,
"maintAmt": 27500.0 "maintAmt": 27500.0
}, },
{ {
"min": 1000000, "minNotional": 1000000,
"max": 2000000, "maxNotional": 2000000,
"mmr": 0.15, "maintenanceMarginRate": 0.15,
"lev": 3, "maxLeverage": 3,
"maintAmt": 77500.0 "maintAmt": 77500.0
}, },
{ {
"min": 2000000, "minNotional": 2000000,
"max": 5000000, "maxNotional": 5000000,
"mmr": 0.25, "maintenanceMarginRate": 0.25,
"lev": 2, "maxLeverage": 2,
"maintAmt": 277500.0 "maintAmt": 277500.0
}, },
{ {
"min": 5000000, "minNotional": 5000000,
"max": 30000000, "maxNotional": 30000000,
"mmr": 0.5, "maintenanceMarginRate": 0.5,
"lev": 1, "maxLeverage": 1,
"maintAmt": 1527500.0 "maintAmt": 1527500.0
}, },
], ],
'BNB/BUSD': [ 'BNB/BUSD': [
{ {
"min": 0, # stake(before leverage) = 0 "minNotional": 0, # stake(before leverage) = 0
"max": 100000, # max stake(before leverage) = 5000 "maxNotional": 100000, # max stake(before leverage) = 5000
"mmr": 0.025, "maintenanceMarginRate": 0.025,
"lev": 20, "maxLeverage": 20,
"maintAmt": 0.0 "maintAmt": 0.0
}, },
{ {
"min": 100000, # stake = 10000.0 "minNotional": 100000, # stake = 10000.0
"max": 500000, # max_stake = 50000.0 "maxNotional": 500000, # max_stake = 50000.0
"mmr": 0.05, "maintenanceMarginRate": 0.05,
"lev": 10, "maxLeverage": 10,
"maintAmt": 2500.0 "maintAmt": 2500.0
}, },
{ {
"min": 500000, # stake = 100000.0 "minNotional": 500000, # stake = 100000.0
"max": 1000000, # max_stake = 200000.0 "maxNotional": 1000000, # max_stake = 200000.0
"mmr": 0.1, "maintenanceMarginRate": 0.1,
"lev": 5, "maxLeverage": 5,
"maintAmt": 27500.0 "maintAmt": 27500.0
}, },
{ {
"min": 1000000, # stake = 333333.3333333333 "minNotional": 1000000, # stake = 333333.3333333333
"max": 2000000, # max_stake = 666666.6666666666 "maxNotional": 2000000, # max_stake = 666666.6666666666
"mmr": 0.15, "maintenanceMarginRate": 0.15,
"lev": 3, "maxLeverage": 3,
"maintAmt": 77500.0 "maintAmt": 77500.0
}, },
{ {
"min": 2000000, # stake = 1000000.0 "minNotional": 2000000, # stake = 1000000.0
"max": 5000000, # max_stake = 2500000.0 "maxNotional": 5000000, # max_stake = 2500000.0
"mmr": 0.25, "maintenanceMarginRate": 0.25,
"lev": 2, "maxLeverage": 2,
"maintAmt": 277500.0 "maintAmt": 277500.0
}, },
{ {
"min": 5000000, # stake = 5000000.0 "minNotional": 5000000, # stake = 5000000.0
"max": 30000000, # max_stake = 30000000.0 "maxNotional": 30000000, # max_stake = 30000000.0
"mmr": 0.5, "maintenanceMarginRate": 0.5,
"lev": 1, "maxLeverage": 1,
"maintAmt": 1527500.0 "maintAmt": 1527500.0
} }
], ],
'BNB/USDT': [ 'BNB/USDT': [
{ {
"min": 0, # stake = 0.0 "minNotional": 0, # stake = 0.0
"max": 10000, # max_stake = 133.33333333333334 "maxNotional": 10000, # max_stake = 133.33333333333334
"mmr": 0.0065, "maintenanceMarginRate": 0.0065,
"lev": 75, "maxLeverage": 75,
"maintAmt": 0.0 "maintAmt": 0.0
}, },
{ {
"min": 10000, # stake = 200.0 "minNotional": 10000, # stake = 200.0
"max": 50000, # max_stake = 1000.0 "maxNotional": 50000, # max_stake = 1000.0
"mmr": 0.01, "maintenanceMarginRate": 0.01,
"lev": 50, "maxLeverage": 50,
"maintAmt": 35.0 "maintAmt": 35.0
}, },
{ {
"min": 50000, # stake = 2000.0 "minNotional": 50000, # stake = 2000.0
"max": 250000, # max_stake = 10000.0 "maxNotional": 250000, # max_stake = 10000.0
"mmr": 0.02, "maintenanceMarginRate": 0.02,
"lev": 25, "maxLeverage": 25,
"maintAmt": 535.0 "maintAmt": 535.0
}, },
{ {
"min": 250000, # stake = 25000.0 "minNotional": 250000, # stake = 25000.0
"max": 1000000, # max_stake = 100000.0 "maxNotional": 1000000, # max_stake = 100000.0
"mmr": 0.05, "maintenanceMarginRate": 0.05,
"lev": 10, "maxLeverage": 10,
"maintAmt": 8035.0 "maintAmt": 8035.0
}, },
{ {
"min": 1000000, # stake = 200000.0 "minNotional": 1000000, # stake = 200000.0
"max": 2000000, # max_stake = 400000.0 "maxNotional": 2000000, # max_stake = 400000.0
"mmr": 0.1, "maintenanceMarginRate": 0.1,
"lev": 5, "maxLeverage": 5,
"maintAmt": 58035.0 "maintAmt": 58035.0
}, },
{ {
"min": 2000000, # stake = 500000.0 "minNotional": 2000000, # stake = 500000.0
"max": 5000000, # max_stake = 1250000.0 "maxNotional": 5000000, # max_stake = 1250000.0
"mmr": 0.125, "maintenanceMarginRate": 0.125,
"lev": 4, "maxLeverage": 4,
"maintAmt": 108035.0 "maintAmt": 108035.0
}, },
{ {
"min": 5000000, # stake = 1666666.6666666667 "minNotional": 5000000, # stake = 1666666.6666666667
"max": 10000000, # max_stake = 3333333.3333333335 "maxNotional": 10000000, # max_stake = 3333333.3333333335
"mmr": 0.15, "maintenanceMarginRate": 0.15,
"lev": 3, "maxLeverage": 3,
"maintAmt": 233035.0 "maintAmt": 233035.0
}, },
{ {
"min": 10000000, # stake = 5000000.0 "minNotional": 10000000, # stake = 5000000.0
"max": 20000000, # max_stake = 10000000.0 "maxNotional": 20000000, # max_stake = 10000000.0
"mmr": 0.25, "maintenanceMarginRate": 0.25,
"lev": 2, "maxLeverage": 2,
"maintAmt": 1233035.0 "maintAmt": 1233035.0
}, },
{ {
"min": 20000000, # stake = 20000000.0 "minNotional": 20000000, # stake = 20000000.0
"max": 50000000, # max_stake = 50000000.0 "maxNotional": 50000000, # max_stake = 50000000.0
"mmr": 0.5, "maintenanceMarginRate": 0.5,
"lev": 1, "maxLeverage": 1,
"maintAmt": 6233035.0 "maintAmt": 6233035.0
}, },
], ],
'BTC/USDT': [ 'BTC/USDT': [
{ {
"min": 0, # stake = 0.0 "minNotional": 0, # stake = 0.0
"max": 50000, # max_stake = 400.0 "maxNotional": 50000, # max_stake = 400.0
"mmr": 0.004, "maintenanceMarginRate": 0.004,
"lev": 125, "maxLeverage": 125,
"maintAmt": 0.0 "maintAmt": 0.0
}, },
{ {
"min": 50000, # stake = 500.0 "minNotional": 50000, # stake = 500.0
"max": 250000, # max_stake = 2500.0 "maxNotional": 250000, # max_stake = 2500.0
"mmr": 0.005, "maintenanceMarginRate": 0.005,
"lev": 100, "maxLeverage": 100,
"maintAmt": 50.0 "maintAmt": 50.0
}, },
{ {
"min": 250000, # stake = 5000.0 "minNotional": 250000, # stake = 5000.0
"max": 1000000, # max_stake = 20000.0 "maxNotional": 1000000, # max_stake = 20000.0
"mmr": 0.01, "maintenanceMarginRate": 0.01,
"lev": 50, "maxLeverage": 50,
"maintAmt": 1300.0 "maintAmt": 1300.0
}, },
{ {
"min": 1000000, # stake = 50000.0 "minNotional": 1000000, # stake = 50000.0
"max": 7500000, # max_stake = 375000.0 "maxNotional": 7500000, # max_stake = 375000.0
"mmr": 0.025, "maintenanceMarginRate": 0.025,
"lev": 20, "maxLeverage": 20,
"maintAmt": 16300.0 "maintAmt": 16300.0
}, },
{ {
"min": 7500000, # stake = 750000.0 "minNotional": 7500000, # stake = 750000.0
"max": 40000000, # max_stake = 4000000.0 "maxNotional": 40000000, # max_stake = 4000000.0
"mmr": 0.05, "maintenanceMarginRate": 0.05,
"lev": 10, "maxLeverage": 10,
"maintAmt": 203800.0 "maintAmt": 203800.0
}, },
{ {
"min": 40000000, # stake = 8000000.0 "minNotional": 40000000, # stake = 8000000.0
"max": 100000000, # max_stake = 20000000.0 "maxNotional": 100000000, # max_stake = 20000000.0
"mmr": 0.1, "maintenanceMarginRate": 0.1,
"lev": 5, "maxLeverage": 5,
"maintAmt": 2203800.0 "maintAmt": 2203800.0
}, },
{ {
"min": 100000000, # stake = 25000000.0 "minNotional": 100000000, # stake = 25000000.0
"max": 200000000, # max_stake = 50000000.0 "maxNotional": 200000000, # max_stake = 50000000.0
"mmr": 0.125, "maintenanceMarginRate": 0.125,
"lev": 4, "maxLeverage": 4,
"maintAmt": 4703800.0 "maintAmt": 4703800.0
}, },
{ {
"min": 200000000, # stake = 66666666.666666664 "minNotional": 200000000, # stake = 66666666.666666664
"max": 400000000, # max_stake = 133333333.33333333 "maxNotional": 400000000, # max_stake = 133333333.33333333
"mmr": 0.15, "maintenanceMarginRate": 0.15,
"lev": 3, "maxLeverage": 3,
"maintAmt": 9703800.0 "maintAmt": 9703800.0
}, },
{ {
"min": 400000000, # stake = 200000000.0 "minNotional": 400000000, # stake = 200000000.0
"max": 600000000, # max_stake = 300000000.0 "maxNotional": 600000000, # max_stake = 300000000.0
"mmr": 0.25, "maintenanceMarginRate": 0.25,
"lev": 2, "maxLeverage": 2,
"maintAmt": 4.97038E7 "maintAmt": 4.97038E7
}, },
{ {
"min": 600000000, # stake = 600000000.0 "minNotional": 600000000, # stake = 600000000.0
"max": 1000000000, # max_stake = 1000000000.0 "maxNotional": 1000000000, # max_stake = 1000000000.0
"mmr": 0.5, "maintenanceMarginRate": 0.5,
"lev": 1, "maxLeverage": 1,
"maintAmt": 1.997038E8 "maintAmt": 1.997038E8
}, },
], ],
"ZEC/USDT": [ "ZEC/USDT": [
{ {
'min': 0, 'minNotional': 0,
'max': 50000, 'maxNotional': 50000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 50, 'maxLeverage': 50,
'maintAmt': 0.0 'maintAmt': 0.0
}, },
{ {
'min': 50000, 'minNotional': 50000,
'max': 150000, 'maxNotional': 150000,
'mmr': 0.025, 'maintenanceMarginRate': 0.025,
'lev': 20, 'maxLeverage': 20,
'maintAmt': 750.0 'maintAmt': 750.0
}, },
{ {
'min': 150000, 'minNotional': 150000,
'max': 250000, 'maxNotional': 250000,
'mmr': 0.05, 'maintenanceMarginRate': 0.05,
'lev': 10, 'maxLeverage': 10,
'maintAmt': 4500.0 'maintAmt': 4500.0
}, },
{ {
'min': 250000, 'minNotional': 250000,
'max': 500000, 'maxNotional': 500000,
'mmr': 0.1, 'maintenanceMarginRate': 0.1,
'lev': 5, 'maxLeverage': 5,
'maintAmt': 17000.0 'maintAmt': 17000.0
}, },
{ {
'min': 500000, 'minNotional': 500000,
'max': 1000000, 'maxNotional': 1000000,
'mmr': 0.125, 'maintenanceMarginRate': 0.125,
'lev': 4, 'maxLeverage': 4,
'maintAmt': 29500.0 'maintAmt': 29500.0
}, },
{ {
'min': 1000000, 'minNotional': 1000000,
'max': 2000000, 'maxNotional': 2000000,
'mmr': 0.25, 'maintenanceMarginRate': 0.25,
'lev': 2, 'maxLeverage': 2,
'maintAmt': 154500.0 'maintAmt': 154500.0
}, },
{ {
'min': 2000000, 'minNotional': 2000000,
'max': 30000000, 'maxNotional': 30000000,
'mmr': 0.5, 'maintenanceMarginRate': 0.5,
'lev': 1, 'maxLeverage': 1,
'maintAmt': 654500.0 'maintAmt': 654500.0
}, },
] ]

View File

@ -1,4 +1,3 @@
from math import isclose
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock from unittest.mock import MagicMock
@ -269,7 +268,7 @@ def test_create_cum_profit(testdatadir):
"cum_profits", timeframe="5m") "cum_profits", timeframe="5m")
assert "cum_profits" in cum_profits.columns assert "cum_profits" in cum_profits.columns
assert cum_profits.iloc[0]['cum_profits'] == 0 assert cum_profits.iloc[0]['cum_profits'] == 0
assert isclose(cum_profits.iloc[-1]['cum_profits'], 8.723007518796964e-06) assert pytest.approx(cum_profits.iloc[-1]['cum_profits']) == 8.723007518796964e-06
def test_create_cum_profit1(testdatadir): def test_create_cum_profit1(testdatadir):
@ -287,7 +286,7 @@ def test_create_cum_profit1(testdatadir):
"cum_profits", timeframe="5m") "cum_profits", timeframe="5m")
assert "cum_profits" in cum_profits.columns assert "cum_profits" in cum_profits.columns
assert cum_profits.iloc[0]['cum_profits'] == 0 assert cum_profits.iloc[0]['cum_profits'] == 0
assert isclose(cum_profits.iloc[-1]['cum_profits'], 8.723007518796964e-06) assert pytest.approx(cum_profits.iloc[-1]['cum_profits']) == 8.723007518796964e-06
with pytest.raises(ValueError, match='Trade dataframe empty.'): with pytest.raises(ValueError, match='Trade dataframe empty.'):
create_cum_profit(df.set_index('date'), bt_data[bt_data["pair"] == 'NOTAPAIR'], create_cum_profit(df.set_index('date'), bt_data[bt_data["pair"] == 'NOTAPAIR'],

View File

@ -376,96 +376,96 @@ def test_fill_leverage_tiers_binance(default_conf, mocker):
assert exchange._leverage_tiers == { assert exchange._leverage_tiers == {
'ADA/BUSD': [ 'ADA/BUSD': [
{ {
"min": 0, "minNotional": 0,
"max": 100000, "maxNotional": 100000,
"mmr": 0.025, "maintenanceMarginRate": 0.025,
"lev": 20, "maxLeverage": 20,
"maintAmt": 0.0 "maintAmt": 0.0
}, },
{ {
"min": 100000, "minNotional": 100000,
"max": 500000, "maxNotional": 500000,
"mmr": 0.05, "maintenanceMarginRate": 0.05,
"lev": 10, "maxLeverage": 10,
"maintAmt": 2500.0 "maintAmt": 2500.0
}, },
{ {
"min": 500000, "minNotional": 500000,
"max": 1000000, "maxNotional": 1000000,
"mmr": 0.1, "maintenanceMarginRate": 0.1,
"lev": 5, "maxLeverage": 5,
"maintAmt": 27500.0 "maintAmt": 27500.0
}, },
{ {
"min": 1000000, "minNotional": 1000000,
"max": 2000000, "maxNotional": 2000000,
"mmr": 0.15, "maintenanceMarginRate": 0.15,
"lev": 3, "maxLeverage": 3,
"maintAmt": 77500.0 "maintAmt": 77500.0
}, },
{ {
"min": 2000000, "minNotional": 2000000,
"max": 5000000, "maxNotional": 5000000,
"mmr": 0.25, "maintenanceMarginRate": 0.25,
"lev": 2, "maxLeverage": 2,
"maintAmt": 277500.0 "maintAmt": 277500.0
}, },
{ {
"min": 5000000, "minNotional": 5000000,
"max": 30000000, "maxNotional": 30000000,
"mmr": 0.5, "maintenanceMarginRate": 0.5,
"lev": 1, "maxLeverage": 1,
"maintAmt": 1527500.0 "maintAmt": 1527500.0
} }
], ],
"ZEC/USDT": [ "ZEC/USDT": [
{ {
'min': 0, 'minNotional': 0,
'max': 50000, 'maxNotional': 50000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 50, 'maxLeverage': 50,
'maintAmt': 0.0 'maintAmt': 0.0
}, },
{ {
'min': 50000, 'minNotional': 50000,
'max': 150000, 'maxNotional': 150000,
'mmr': 0.025, 'maintenanceMarginRate': 0.025,
'lev': 20, 'maxLeverage': 20,
'maintAmt': 750.0 'maintAmt': 750.0
}, },
{ {
'min': 150000, 'minNotional': 150000,
'max': 250000, 'maxNotional': 250000,
'mmr': 0.05, 'maintenanceMarginRate': 0.05,
'lev': 10, 'maxLeverage': 10,
'maintAmt': 4500.0 'maintAmt': 4500.0
}, },
{ {
'min': 250000, 'minNotional': 250000,
'max': 500000, 'maxNotional': 500000,
'mmr': 0.1, 'maintenanceMarginRate': 0.1,
'lev': 5, 'maxLeverage': 5,
'maintAmt': 17000.0 'maintAmt': 17000.0
}, },
{ {
'min': 500000, 'minNotional': 500000,
'max': 1000000, 'maxNotional': 1000000,
'mmr': 0.125, 'maintenanceMarginRate': 0.125,
'lev': 4, 'maxLeverage': 4,
'maintAmt': 29500.0 'maintAmt': 29500.0
}, },
{ {
'min': 1000000, 'minNotional': 1000000,
'max': 2000000, 'maxNotional': 2000000,
'mmr': 0.25, 'maintenanceMarginRate': 0.25,
'lev': 2, 'maxLeverage': 2,
'maintAmt': 154500.0 'maintAmt': 154500.0
}, },
{ {
'min': 2000000, 'minNotional': 2000000,
'max': 30000000, 'maxNotional': 30000000,
'mmr': 0.5, 'maintenanceMarginRate': 0.5,
'lev': 1, 'maxLeverage': 1,
'maintAmt': 654500.0 'maintAmt': 654500.0
}, },
] ]

View File

@ -468,6 +468,7 @@ class TestCCXTExchange():
False, False,
100, 100,
100, 100,
100,
) )
assert (isinstance(liquidation_price, float)) assert (isinstance(liquidation_price, float))
assert liquidation_price >= 0.0 assert liquidation_price >= 0.0
@ -478,6 +479,7 @@ class TestCCXTExchange():
False, False,
100, 100,
100, 100,
100,
) )
assert (isinstance(liquidation_price, float)) assert (isinstance(liquidation_price, float))
assert liquidation_price >= 0.0 assert liquidation_price >= 0.0

View File

@ -2,7 +2,6 @@ import copy
import logging import logging
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from math import isclose
from random import randint from random import randint
from unittest.mock import MagicMock, Mock, PropertyMock, patch from unittest.mock import MagicMock, Mock, PropertyMock, patch
@ -275,7 +274,7 @@ def test_validate_order_time_in_force(default_conf, mocker, caplog):
ex.validate_order_time_in_force(tif2) ex.validate_order_time_in_force(tif2)
# Patch to see if this will pass if the values are in the ft dict # Patch to see if this will pass if the values are in the ft dict
ex._ft_has.update({"order_time_in_force": ["gtc", "fok", "ioc"]}) ex._ft_has.update({"order_time_in_force": ["GTC", "FOK", "IOC"]})
ex.validate_order_time_in_force(tif2) ex.validate_order_time_in_force(tif2)
@ -407,10 +406,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
# min # min
result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss)
expected_result = 2 * (1 + 0.05) / (1 - abs(stoploss)) expected_result = 2 * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss, 3.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss, 3.0)
assert isclose(result, expected_result / 3) assert pytest.approx(result) == expected_result / 3
# max # max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 10000 assert result == 10000
@ -426,10 +425,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss)
expected_result = 2 * 2 * (1 + 0.05) / (1 - abs(stoploss)) expected_result = 2 * 2 * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 5.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 5.0)
assert isclose(result, expected_result / 5) assert pytest.approx(result) == expected_result / 5
# max # max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 20000 assert result == 20000
@ -445,10 +444,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss)
expected_result = max(2, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss)) expected_result = max(2, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 10) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 10)
assert isclose(result, expected_result / 10) assert pytest.approx(result) == expected_result / 10
# min amount and cost are set (amount is minial) # min amount and cost are set (amount is minial)
markets["ETH/BTC"]["limits"] = { markets["ETH/BTC"]["limits"] = {
@ -461,20 +460,20 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss)
expected_result = max(8, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss)) expected_result = max(8, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 7.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 7.0)
assert isclose(result, expected_result / 7.0) assert pytest.approx(result) == expected_result / 7.0
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 1000 assert result == 1000
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4)
expected_result = max(8, 2 * 2) * 1.5 expected_result = max(8, 2 * 2) * 1.5
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4, 8.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4, 8.0)
assert isclose(result, expected_result / 8.0) assert pytest.approx(result) == expected_result / 8.0
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 1000 assert result == 1000
@ -482,10 +481,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
# Really big stoploss # Really big stoploss
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1)
expected_result = max(8, 2 * 2) * 1.5 expected_result = max(8, 2 * 2) * 1.5
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0)
assert isclose(result, expected_result / 12) assert pytest.approx(result) == expected_result / 12
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 1000 assert result == 1000
@ -501,7 +500,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
# Contract size 0.01 # Contract size 0.01
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1)
assert isclose(result, expected_result * 0.01) assert pytest.approx(result) == expected_result * 0.01
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 10 assert result == 10
@ -513,7 +512,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
# With Leverage, Contract size 10 # With Leverage, Contract size 10
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0)
assert isclose(result, (expected_result / 12) * 10.0) assert pytest.approx(result) == (expected_result / 12) * 10.0
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 10000 assert result == 10000
@ -1503,7 +1502,7 @@ def test_buy_considers_time_in_force(default_conf, mocker, exchange_name):
assert api_mock.create_order.call_args[0][3] == 1 assert api_mock.create_order.call_args[0][3] == 1
assert api_mock.create_order.call_args[0][4] == 200 assert api_mock.create_order.call_args[0][4] == 200
assert "timeInForce" in api_mock.create_order.call_args[0][5] assert "timeInForce" in api_mock.create_order.call_args[0][5]
assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force.upper()
order_type = 'market' order_type = 'market'
time_in_force = 'ioc' time_in_force = 'ioc'
@ -1642,10 +1641,10 @@ def test_sell_considers_time_in_force(default_conf, mocker, exchange_name):
assert api_mock.create_order.call_args[0][3] == 1 assert api_mock.create_order.call_args[0][3] == 1
assert api_mock.create_order.call_args[0][4] == 200 assert api_mock.create_order.call_args[0][4] == 200
assert "timeInForce" in api_mock.create_order.call_args[0][5] assert "timeInForce" in api_mock.create_order.call_args[0][5]
assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force.upper()
order_type = 'market' order_type = 'market'
time_in_force = 'ioc' time_in_force = 'IOC'
order = exchange.create_order(pair='ETH/BTC', ordertype=order_type, side="sell", order = exchange.create_order(pair='ETH/BTC', ordertype=order_type, side="sell",
amount=1, rate=200, leverage=1.0, amount=1, rate=200, leverage=1.0,
time_in_force=time_in_force) time_in_force=time_in_force)
@ -3239,7 +3238,7 @@ def test_get_trades_for_order(default_conf, mocker, exchange_name, trading_mode,
orders = exchange.get_trades_for_order(order_id, 'ETH/USDT:USDT', since) orders = exchange.get_trades_for_order(order_id, 'ETH/USDT:USDT', since)
assert len(orders) == 1 assert len(orders) == 1
assert orders[0]['price'] == 165 assert orders[0]['price'] == 165
assert isclose(orders[0]['amount'], amount) assert pytest.approx(orders[0]['amount']) == amount
assert api_mock.fetch_my_trades.call_count == 1 assert api_mock.fetch_my_trades.call_count == 1
# since argument should be # since argument should be
assert isinstance(api_mock.fetch_my_trades.call_args[0][1], int) assert isinstance(api_mock.fetch_my_trades.call_args[0][1], int)
@ -3319,7 +3318,7 @@ def test_merge_ft_has_dict(default_conf, mocker):
ex = Binance(default_conf) ex = Binance(default_conf)
assert ex._ft_has != Exchange._ft_has_default assert ex._ft_has != Exchange._ft_has_default
assert ex.get_option('stoploss_on_exchange') assert ex.get_option('stoploss_on_exchange')
assert ex.get_option('order_time_in_force') == ['gtc', 'fok', 'ioc'] assert ex.get_option('order_time_in_force') == ['GTC', 'FOK', 'IOC']
assert ex.get_option('trades_pagination') == 'id' assert ex.get_option('trades_pagination') == 'id'
assert ex.get_option('trades_pagination_arg') == 'fromId' assert ex.get_option('trades_pagination_arg') == 'fromId'
@ -3776,8 +3775,8 @@ def test__get_funding_fees_from_exchange(default_conf, mocker, exchange_name):
since=unix_time since=unix_time
) )
assert (isclose(expected_fees, fees_from_datetime)) assert pytest.approx(expected_fees) == fees_from_datetime
assert (isclose(expected_fees, fees_from_unix_time)) assert pytest.approx(expected_fees) == fees_from_unix_time
ccxt_exceptionhandlers( ccxt_exceptionhandlers(
mocker, mocker,
@ -4089,66 +4088,6 @@ def test_combine_funding_and_mark(
assert len(df) == 0 assert len(df) == 0
def test_get_or_calculate_liquidation_price(mocker, default_conf):
api_mock = MagicMock()
positions = [
{
'info': {},
'symbol': 'NEAR/USDT:USDT',
'timestamp': 1642164737148,
'datetime': '2022-01-14T12:52:17.148Z',
'initialMargin': 1.51072,
'initialMarginPercentage': 0.1,
'maintenanceMargin': 0.38916147,
'maintenanceMarginPercentage': 0.025,
'entryPrice': 18.884,
'notional': 15.1072,
'leverage': 9.97,
'unrealizedPnl': 0.0048,
'contracts': 8,
'contractSize': 0.1,
'marginRatio': None,
'liquidationPrice': 17.47,
'markPrice': 18.89,
'margin_mode': 1.52549075,
'marginType': 'isolated',
'side': 'buy',
'percentage': 0.003177292946409658
}
]
api_mock.fetch_positions = MagicMock(return_value=positions)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
exchange_has=MagicMock(return_value=True),
)
default_conf['dry_run'] = False
default_conf['trading_mode'] = 'futures'
default_conf['margin_mode'] = 'isolated'
default_conf['liquidation_buffer'] = 0.0
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_or_calculate_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
position=0.8,
wallet_balance=0.8,
)
assert liq_price == 17.47
default_conf['liquidation_buffer'] = 0.05
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_or_calculate_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
position=0.8,
wallet_balance=0.8,
)
assert liq_price == 17.540699999999998
@pytest.mark.parametrize('exchange,rate_start,rate_end,d1,d2,amount,expected_fees', [ @pytest.mark.parametrize('exchange,rate_start,rate_end,d1,d2,amount,expected_fees', [
('binance', 0, 2, "2021-09-01 01:00:00", "2021-09-01 04:00:00", 30.0, 0.0), ('binance', 0, 2, "2021-09-01 01:00:00", "2021-09-01 04:00:00", 30.0, 0.0),
('binance', 0, 2, "2021-09-01 00:00:00", "2021-09-01 08:00:00", 30.0, -0.00091409999), ('binance', 0, 2, "2021-09-01 00:00:00", "2021-09-01 08:00:00", 30.0, -0.00091409999),
@ -4539,11 +4478,12 @@ def test_liquidation_price_is_none(
default_conf['trading_mode'] = trading_mode default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = margin_mode default_conf['margin_mode'] = margin_mode
exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) exchange = get_patched_exchange(mocker, default_conf, id=exchange_name)
assert exchange.get_or_calculate_liquidation_price( assert exchange.get_liquidation_price(
pair='DOGE/USDT', pair='DOGE/USDT',
open_rate=open_rate, open_rate=open_rate,
is_short=is_short, is_short=is_short,
position=71200.81144, amount=71200.81144,
stake_amount=open_rate * 71200.81144,
wallet_balance=-56354.57, wallet_balance=-56354.57,
mm_ex_1=0.10, mm_ex_1=0.10,
upnl_ex_1=0.0 upnl_ex_1=0.0
@ -4552,7 +4492,7 @@ def test_liquidation_price_is_none(
@pytest.mark.parametrize( @pytest.mark.parametrize(
'exchange_name, is_short, trading_mode, margin_mode, wallet_balance, ' 'exchange_name, is_short, trading_mode, margin_mode, wallet_balance, '
'mm_ex_1, upnl_ex_1, maintenance_amt, position, open_rate, ' 'mm_ex_1, upnl_ex_1, maintenance_amt, amount, open_rate, '
'mm_ratio, expected', 'mm_ratio, expected',
[ [
("binance", False, 'futures', 'isolated', 1535443.01, 0.0, ("binance", False, 'futures', 'isolated', 1535443.01, 0.0,
@ -4566,22 +4506,23 @@ def test_liquidation_price_is_none(
]) ])
def test_liquidation_price( def test_liquidation_price(
mocker, default_conf, exchange_name, open_rate, is_short, trading_mode, mocker, default_conf, exchange_name, open_rate, is_short, trading_mode,
margin_mode, wallet_balance, mm_ex_1, upnl_ex_1, maintenance_amt, position, mm_ratio, expected margin_mode, wallet_balance, mm_ex_1, upnl_ex_1, maintenance_amt, amount, mm_ratio, expected
): ):
default_conf['trading_mode'] = trading_mode default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = margin_mode default_conf['margin_mode'] = margin_mode
default_conf['liquidation_buffer'] = 0.0 default_conf['liquidation_buffer'] = 0.0
exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) exchange = get_patched_exchange(mocker, default_conf, id=exchange_name)
exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(mm_ratio, maintenance_amt)) exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(mm_ratio, maintenance_amt))
assert isclose(round(exchange.get_or_calculate_liquidation_price( assert pytest.approx(round(exchange.get_liquidation_price(
pair='DOGE/USDT', pair='DOGE/USDT',
open_rate=open_rate, open_rate=open_rate,
is_short=is_short, is_short=is_short,
wallet_balance=wallet_balance, wallet_balance=wallet_balance,
mm_ex_1=mm_ex_1, mm_ex_1=mm_ex_1,
upnl_ex_1=upnl_ex_1, upnl_ex_1=upnl_ex_1,
position=position, amount=amount,
), 2), expected) stake_amount=open_rate * amount,
), 2)) == expected
def test_get_max_pair_stake_amount( def test_get_max_pair_stake_amount(
@ -4826,10 +4767,10 @@ def test_parse_leverage_tier(mocker, default_conf):
} }
assert exchange.parse_leverage_tier(tier) == { assert exchange.parse_leverage_tier(tier) == {
"min": 0, "minNotional": 0,
"max": 100000, "maxNotional": 100000,
"mmr": 0.025, "maintenanceMarginRate": 0.025,
"lev": 20, "maxLeverage": 20,
"maintAmt": 0.0, "maintAmt": 0.0,
} }
@ -4855,10 +4796,10 @@ def test_parse_leverage_tier(mocker, default_conf):
} }
assert exchange.parse_leverage_tier(tier2) == { assert exchange.parse_leverage_tier(tier2) == {
'min': 0, 'minNotional': 0,
'max': 2000, 'maxNotional': 2000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 75, 'maxLeverage': 75,
"maintAmt": None, "maintAmt": None,
} }
@ -4926,8 +4867,8 @@ def test_get_max_leverage_futures(default_conf, mocker, leverage_tiers):
assert exchange.get_max_leverage("BNB/BUSD", 1.0) == 20.0 assert exchange.get_max_leverage("BNB/BUSD", 1.0) == 20.0
assert exchange.get_max_leverage("BNB/USDT", 100.0) == 75.0 assert exchange.get_max_leverage("BNB/USDT", 100.0) == 75.0
assert exchange.get_max_leverage("BTC/USDT", 170.30) == 125.0 assert exchange.get_max_leverage("BTC/USDT", 170.30) == 125.0
assert isclose(exchange.get_max_leverage("BNB/BUSD", 99999.9), 5.000005) assert pytest.approx(exchange.get_max_leverage("BNB/BUSD", 99999.9)) == 5.000005
assert isclose(exchange.get_max_leverage("BNB/USDT", 1500), 33.333333333333333) assert pytest.approx(exchange.get_max_leverage("BNB/USDT", 1500)) == 33.333333333333333
assert exchange.get_max_leverage("BTC/USDT", 300000000) == 2.0 assert exchange.get_max_leverage("BTC/USDT", 300000000) == 2.0
assert exchange.get_max_leverage("BTC/USDT", 600000000) == 1.0 # Last tier assert exchange.get_max_leverage("BTC/USDT", 600000000) == 1.0 # Last tier
@ -4950,7 +4891,7 @@ def test__get_params(mocker, default_conf, exchange_name):
params1 = {'test': True} params1 = {'test': True}
params2 = { params2 = {
'test': True, 'test': True,
'timeInForce': 'ioc', 'timeInForce': 'IOC',
'reduceOnly': True, 'reduceOnly': True,
} }
@ -4965,7 +4906,7 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='market', ordertype='market',
reduceOnly=False, reduceOnly=False,
time_in_force='gtc', time_in_force='GTC',
leverage=1.0, leverage=1.0,
) == params1 ) == params1
@ -4973,7 +4914,7 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='market', ordertype='market',
reduceOnly=False, reduceOnly=False,
time_in_force='ioc', time_in_force='IOC',
leverage=1.0, leverage=1.0,
) == params1 ) == params1
@ -4981,7 +4922,7 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='limit', ordertype='limit',
reduceOnly=False, reduceOnly=False,
time_in_force='gtc', time_in_force='GTC',
leverage=1.0, leverage=1.0,
) == params1 ) == params1
@ -4994,11 +4935,97 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='limit', ordertype='limit',
reduceOnly=True, reduceOnly=True,
time_in_force='ioc', time_in_force='IOC',
leverage=3.0, leverage=3.0,
) == params2 ) == params2
def test_get_liquidation_price1(mocker, default_conf):
api_mock = MagicMock()
positions = [
{
'info': {},
'symbol': 'NEAR/USDT:USDT',
'timestamp': 1642164737148,
'datetime': '2022-01-14T12:52:17.148Z',
'initialMargin': 1.51072,
'initialMarginPercentage': 0.1,
'maintenanceMargin': 0.38916147,
'maintenanceMarginPercentage': 0.025,
'entryPrice': 18.884,
'notional': 15.1072,
'leverage': 9.97,
'unrealizedPnl': 0.0048,
'contracts': 8,
'contractSize': 0.1,
'marginRatio': None,
'liquidationPrice': 17.47,
'markPrice': 18.89,
'margin_mode': 1.52549075,
'marginType': 'isolated',
'side': 'buy',
'percentage': 0.003177292946409658
}
]
api_mock.fetch_positions = MagicMock(return_value=positions)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
exchange_has=MagicMock(return_value=True),
)
default_conf['dry_run'] = False
default_conf['trading_mode'] = 'futures'
default_conf['margin_mode'] = 'isolated'
default_conf['liquidation_buffer'] = 0.0
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
wallet_balance=18.884 * 0.8,
)
assert liq_price == 17.47
default_conf['liquidation_buffer'] = 0.05
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
wallet_balance=18.884 * 0.8,
)
assert liq_price == 17.540699999999998
api_mock.fetch_positions = MagicMock(return_value=[])
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
wallet_balance=18.884 * 0.8,
)
assert liq_price is None
default_conf['trading_mode'] = 'margin'
exchange = get_patched_exchange(mocker, default_conf, api_mock)
with pytest.raises(OperationalException, match=r'.*does not support .* margin'):
exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
wallet_balance=18.884 * 0.8,
)
@pytest.mark.parametrize('liquidation_buffer', [0.0, 0.05]) @pytest.mark.parametrize('liquidation_buffer', [0.0, 0.05])
@pytest.mark.parametrize( @pytest.mark.parametrize(
"is_short,trading_mode,exchange_name,margin_mode,leverage,open_rate,amount,expected_liq", [ "is_short,trading_mode,exchange_name,margin_mode,leverage,open_rate,amount,expected_liq", [
@ -5012,22 +5039,22 @@ def test__get_params(mocker, default_conf, exchange_name):
(True, 'futures', 'binance', 'isolated', 5.0, 10.0, 1.0, 11.89108910891089), (True, 'futures', 'binance', 'isolated', 5.0, 10.0, 1.0, 11.89108910891089),
(True, 'futures', 'binance', 'isolated', 3.0, 10.0, 1.0, 13.211221122079207), (True, 'futures', 'binance', 'isolated', 3.0, 10.0, 1.0, 13.211221122079207),
(True, 'futures', 'binance', 'isolated', 5.0, 8.0, 1.0, 9.514851485148514), (True, 'futures', 'binance', 'isolated', 5.0, 8.0, 1.0, 9.514851485148514),
(True, 'futures', 'binance', 'isolated', 5.0, 10.0, 0.6, 12.557755775577558), (True, 'futures', 'binance', 'isolated', 5.0, 10.0, 0.6, 11.897689768976898),
# Binance, long # Binance, long
(False, 'futures', 'binance', 'isolated', 5, 10, 1.0, 8.070707070707071), (False, 'futures', 'binance', 'isolated', 5, 10, 1.0, 8.070707070707071),
(False, 'futures', 'binance', 'isolated', 5, 8, 1.0, 6.454545454545454), (False, 'futures', 'binance', 'isolated', 5, 8, 1.0, 6.454545454545454),
(False, 'futures', 'binance', 'isolated', 3, 10, 1.0, 6.717171717171718), (False, 'futures', 'binance', 'isolated', 3, 10, 1.0, 6.723905723905723),
(False, 'futures', 'binance', 'isolated', 5, 10, 0.6, 7.39057239057239), (False, 'futures', 'binance', 'isolated', 5, 10, 0.6, 8.063973063973064),
# Gateio/okx, short # Gateio/okx, short
(True, 'futures', 'gateio', 'isolated', 5, 10, 1.0, 11.87413417771621), (True, 'futures', 'gateio', 'isolated', 5, 10, 1.0, 11.87413417771621),
(True, 'futures', 'gateio', 'isolated', 5, 10, 2.0, 11.87413417771621), (True, 'futures', 'gateio', 'isolated', 5, 10, 2.0, 11.87413417771621),
(True, 'futures', 'gateio', 'isolated', 3, 10, 1.0, 13.476180850346978), (True, 'futures', 'gateio', 'isolated', 3, 10, 1.0, 13.193482419684678),
(True, 'futures', 'gateio', 'isolated', 5, 8, 1.0, 9.499307342172967), (True, 'futures', 'gateio', 'isolated', 5, 8, 1.0, 9.499307342172967),
(True, 'futures', 'okx', 'isolated', 3, 10, 1.0, 13.193482419684678),
# Gateio/okx, long # Gateio/okx, long
(False, 'futures', 'gateio', 'isolated', 5.0, 10.0, 1.0, 8.085708510208207), (False, 'futures', 'gateio', 'isolated', 5.0, 10.0, 1.0, 8.085708510208207),
(False, 'futures', 'gateio', 'isolated', 3.0, 10.0, 1.0, 6.738090425173506), (False, 'futures', 'gateio', 'isolated', 3.0, 10.0, 1.0, 6.738090425173506),
# (True, 'futures', 'okx', 'isolated', 11.87413417771621), (False, 'futures', 'okx', 'isolated', 3.0, 10.0, 1.0, 6.738090425173506),
# (False, 'futures', 'okx', 'isolated', 8.085708510208207),
] ]
) )
def test_get_liquidation_price( def test_get_liquidation_price(
@ -5100,7 +5127,7 @@ def test_get_liquidation_price(
default_conf_usdt['exchange']['name'] = exchange_name default_conf_usdt['exchange']['name'] = exchange_name
default_conf_usdt['margin_mode'] = margin_mode default_conf_usdt['margin_mode'] = margin_mode
mocker.patch('freqtrade.exchange.Gateio.validate_ordertypes') mocker.patch('freqtrade.exchange.Gateio.validate_ordertypes')
exchange = get_patched_exchange(mocker, default_conf_usdt) exchange = get_patched_exchange(mocker, default_conf_usdt, id=exchange_name)
exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(0.01, 0.01)) exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(0.01, 0.01))
exchange.name = exchange_name exchange.name = exchange_name
@ -5111,7 +5138,9 @@ def test_get_liquidation_price(
pair='ETH/USDT:USDT', pair='ETH/USDT:USDT',
open_rate=open_rate, open_rate=open_rate,
amount=amount, amount=amount,
leverage=leverage, stake_amount=amount * open_rate / leverage,
wallet_balance=amount * open_rate / leverage,
# leverage=leverage,
is_short=is_short, is_short=is_short,
) )
if expected_liq is None: if expected_liq is None:
@ -5119,7 +5148,7 @@ def test_get_liquidation_price(
else: else:
buffer_amount = liquidation_buffer * abs(open_rate - expected_liq) buffer_amount = liquidation_buffer * abs(open_rate - expected_liq)
expected_liq = expected_liq - buffer_amount if is_short else expected_liq + buffer_amount expected_liq = expected_liq - buffer_amount if is_short else expected_liq + buffer_amount
isclose(expected_liq, liq) assert pytest.approx(expected_liq) == liq
@pytest.mark.parametrize('contract_size,order_amount', [ @pytest.mark.parametrize('contract_size,order_amount', [

View File

@ -50,7 +50,7 @@ def test_buy_kraken_trading_agreement(default_conf, mocker):
assert api_mock.create_order.call_args[0][2] == 'buy' assert api_mock.create_order.call_args[0][2] == 'buy'
assert api_mock.create_order.call_args[0][3] == 1 assert api_mock.create_order.call_args[0][3] == 1
assert api_mock.create_order.call_args[0][4] == 200 assert api_mock.create_order.call_args[0][4] == 200
assert api_mock.create_order.call_args[0][5] == {'timeInForce': 'ioc', assert api_mock.create_order.call_args[0][5] == {'timeInForce': 'IOC',
'trading_agreement': 'agree'} 'trading_agreement': 'agree'}

View File

@ -414,47 +414,47 @@ def test_load_leverage_tiers_okx(default_conf, mocker, markets, tmpdir, caplog,
assert exchange._leverage_tiers == { assert exchange._leverage_tiers == {
'ADA/USDT:USDT': [ 'ADA/USDT:USDT': [
{ {
'min': 0, 'minNotional': 0,
'max': 500, 'maxNotional': 500,
'mmr': 0.02, 'maintenanceMarginRate': 0.02,
'lev': 75, 'maxLeverage': 75,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 501, 'minNotional': 501,
'max': 1000, 'maxNotional': 1000,
'mmr': 0.025, 'maintenanceMarginRate': 0.025,
'lev': 50, 'maxLeverage': 50,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 1001, 'minNotional': 1001,
'max': 2000, 'maxNotional': 2000,
'mmr': 0.03, 'maintenanceMarginRate': 0.03,
'lev': 20, 'maxLeverage': 20,
'maintAmt': None 'maintAmt': None
}, },
], ],
'ETH/USDT:USDT': [ 'ETH/USDT:USDT': [
{ {
'min': 0, 'minNotional': 0,
'max': 2000, 'maxNotional': 2000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 75, 'maxLeverage': 75,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 2001, 'minNotional': 2001,
'max': 4000, 'maxNotional': 4000,
'mmr': 0.015, 'maintenanceMarginRate': 0.015,
'lev': 50, 'maxLeverage': 50,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 4001, 'minNotional': 4001,
'max': 8000, 'maxNotional': 8000,
'mmr': 0.02, 'maintenanceMarginRate': 0.02,
'lev': 20, 'maxLeverage': 20,
'maintAmt': None 'maintAmt': None
}, },
], ],

View File

@ -1,5 +1,6 @@
from copy import deepcopy from copy import deepcopy
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock
import pytest import pytest
@ -44,7 +45,6 @@ def freqai_conf(default_conf, tmpdir):
"principal_component_analysis": False, "principal_component_analysis": False,
"use_SVM_to_remove_outliers": True, "use_SVM_to_remove_outliers": True,
"stratify_training_data": 0, "stratify_training_data": 0,
"indicator_max_period_candles": 10,
"indicator_periods_candles": [10], "indicator_periods_candles": [10],
}, },
"data_split_parameters": {"test_size": 0.33, "random_state": 1}, "data_split_parameters": {"test_size": 0.33, "random_state": 1},
@ -81,6 +81,51 @@ def get_patched_freqaimodel(mocker, freqaiconf):
return freqaimodel return freqaimodel
def make_data_dictionary(mocker, freqai_conf):
freqai_conf.update({"timerange": "20180110-20180130"})
strategy = get_patched_freqai_strategy(mocker, freqai_conf)
exchange = get_patched_exchange(mocker, freqai_conf)
strategy.dp = DataProvider(freqai_conf, exchange)
strategy.freqai_info = freqai_conf.get("freqai", {})
freqai = strategy.freqai
freqai.live = True
freqai.dk = FreqaiDataKitchen(freqai_conf)
freqai.dk.pair = "ADA/BTC"
timerange = TimeRange.parse_timerange("20180110-20180130")
freqai.dd.load_all_pair_histories(timerange, freqai.dk)
freqai.dd.pair_dict = MagicMock()
data_load_timerange = TimeRange.parse_timerange("20180110-20180130")
new_timerange = TimeRange.parse_timerange("20180120-20180130")
corr_dataframes, base_dataframes = freqai.dd.get_base_and_corr_dataframes(
data_load_timerange, freqai.dk.pair, freqai.dk
)
unfiltered_dataframe = freqai.dk.use_strategy_to_populate_indicators(
strategy, corr_dataframes, base_dataframes, freqai.dk.pair
)
unfiltered_dataframe = freqai.dk.slice_dataframe(new_timerange, unfiltered_dataframe)
freqai.dk.find_features(unfiltered_dataframe)
features_filtered, labels_filtered = freqai.dk.filter_features(
unfiltered_dataframe,
freqai.dk.training_features_list,
freqai.dk.label_list,
training_filter=True,
)
data_dictionary = freqai.dk.make_train_test_datasets(features_filtered, labels_filtered)
data_dictionary = freqai.dk.normalize_data(data_dictionary)
return freqai
def get_freqai_live_analyzed_dataframe(mocker, freqaiconf): def get_freqai_live_analyzed_dataframe(mocker, freqaiconf):
strategy = get_patched_freqai_strategy(mocker, freqaiconf) strategy = get_patched_freqai_strategy(mocker, freqaiconf)
exchange = get_patched_exchange(mocker, freqaiconf) exchange = get_patched_exchange(mocker, freqaiconf)

View File

@ -48,10 +48,4 @@ def test_freqai_backtest_load_data(freqai_conf, mocker, caplog):
assert log_has_re('Increasing startup_candle_count for freqai to.*', caplog) assert log_has_re('Increasing startup_candle_count for freqai to.*', caplog)
del freqai_conf['freqai']['startup_candles']
backtesting = Backtesting(freqai_conf)
with pytest.raises(OperationalException,
match=r'FreqAI backtesting module.*startup_candles in config.'):
backtesting.load_bt_data()
Backtesting.cleanup() Backtesting.cleanup()

View File

@ -5,7 +5,8 @@ from pathlib import Path
import pytest import pytest
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from tests.freqai.conftest import get_patched_data_kitchen from tests.conftest import log_has_re
from tests.freqai.conftest import get_patched_data_kitchen, make_data_dictionary
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -66,3 +67,30 @@ def test_check_if_model_expired(mocker, freqai_conf, timestamp, expected):
dk = get_patched_data_kitchen(mocker, freqai_conf) dk = get_patched_data_kitchen(mocker, freqai_conf)
assert dk.check_if_model_expired(timestamp) == expected assert dk.check_if_model_expired(timestamp) == expected
shutil.rmtree(Path(dk.full_path)) shutil.rmtree(Path(dk.full_path))
def test_use_DBSCAN_to_remove_outliers(mocker, freqai_conf, caplog):
freqai = make_data_dictionary(mocker, freqai_conf)
# freqai_conf['freqai']['feature_parameters'].update({"outlier_protection_percentage": 1})
freqai.dk.use_DBSCAN_to_remove_outliers(predict=False)
assert log_has_re(
"DBSCAN found eps of 2.42.",
caplog,
)
def test_compute_distances(mocker, freqai_conf):
freqai = make_data_dictionary(mocker, freqai_conf)
freqai_conf['freqai']['feature_parameters'].update({"DI_threshold": 1})
avg_mean_dist = freqai.dk.compute_distances()
assert round(avg_mean_dist, 2) == 2.56
def test_use_SVM_to_remove_outliers_and_outlier_protection(mocker, freqai_conf, caplog):
freqai = make_data_dictionary(mocker, freqai_conf)
freqai_conf['freqai']['feature_parameters'].update({"outlier_protection_percentage": 0.1})
freqai.dk.use_SVM_to_remove_outliers(predict=False)
assert log_has_re(
"SVM detected 8.46%",
caplog,
)

View File

@ -174,6 +174,7 @@ def test_train_model_in_series_LightGBMClassifier(mocker, freqai_conf):
def test_start_backtesting(mocker, freqai_conf): def test_start_backtesting(mocker, freqai_conf):
freqai_conf.update({"timerange": "20180120-20180130"}) freqai_conf.update({"timerange": "20180120-20180130"})
freqai_conf.get("freqai", {}).update({"save_backtest_models": True})
strategy = get_patched_freqai_strategy(mocker, freqai_conf) strategy = get_patched_freqai_strategy(mocker, freqai_conf)
exchange = get_patched_exchange(mocker, freqai_conf) exchange = get_patched_exchange(mocker, freqai_conf)
strategy.dp = DataProvider(freqai_conf, exchange) strategy.dp = DataProvider(freqai_conf, exchange)
@ -192,7 +193,7 @@ def test_start_backtesting(mocker, freqai_conf):
freqai.start_backtesting(df, metadata, freqai.dk) freqai.start_backtesting(df, metadata, freqai.dk)
model_folders = [x for x in freqai.dd.full_path.iterdir() if x.is_dir()] model_folders = [x for x in freqai.dd.full_path.iterdir() if x.is_dir()]
assert len(model_folders) == 5 assert len(model_folders) == 6
shutil.rmtree(Path(freqai.dk.full_path)) shutil.rmtree(Path(freqai.dk.full_path))
@ -200,6 +201,7 @@ def test_start_backtesting(mocker, freqai_conf):
def test_start_backtesting_subdaily_backtest_period(mocker, freqai_conf): def test_start_backtesting_subdaily_backtest_period(mocker, freqai_conf):
freqai_conf.update({"timerange": "20180120-20180124"}) freqai_conf.update({"timerange": "20180120-20180124"})
freqai_conf.get("freqai", {}).update({"backtest_period_days": 0.5}) freqai_conf.get("freqai", {}).update({"backtest_period_days": 0.5})
freqai_conf.get("freqai", {}).update({"save_backtest_models": True})
strategy = get_patched_freqai_strategy(mocker, freqai_conf) strategy = get_patched_freqai_strategy(mocker, freqai_conf)
exchange = get_patched_exchange(mocker, freqai_conf) exchange = get_patched_exchange(mocker, freqai_conf)
strategy.dp = DataProvider(freqai_conf, exchange) strategy.dp = DataProvider(freqai_conf, exchange)
@ -217,13 +219,14 @@ def test_start_backtesting_subdaily_backtest_period(mocker, freqai_conf):
metadata = {"pair": "LTC/BTC"} metadata = {"pair": "LTC/BTC"}
freqai.start_backtesting(df, metadata, freqai.dk) freqai.start_backtesting(df, metadata, freqai.dk)
model_folders = [x for x in freqai.dd.full_path.iterdir() if x.is_dir()] model_folders = [x for x in freqai.dd.full_path.iterdir() if x.is_dir()]
assert len(model_folders) == 8 assert len(model_folders) == 9
shutil.rmtree(Path(freqai.dk.full_path)) shutil.rmtree(Path(freqai.dk.full_path))
def test_start_backtesting_from_existing_folder(mocker, freqai_conf, caplog): def test_start_backtesting_from_existing_folder(mocker, freqai_conf, caplog):
freqai_conf.update({"timerange": "20180120-20180130"}) freqai_conf.update({"timerange": "20180120-20180130"})
freqai_conf.get("freqai", {}).update({"save_backtest_models": True})
strategy = get_patched_freqai_strategy(mocker, freqai_conf) strategy = get_patched_freqai_strategy(mocker, freqai_conf)
exchange = get_patched_exchange(mocker, freqai_conf) exchange = get_patched_exchange(mocker, freqai_conf)
strategy.dp = DataProvider(freqai_conf, exchange) strategy.dp = DataProvider(freqai_conf, exchange)
@ -242,7 +245,7 @@ def test_start_backtesting_from_existing_folder(mocker, freqai_conf, caplog):
freqai.start_backtesting(df, metadata, freqai.dk) freqai.start_backtesting(df, metadata, freqai.dk)
model_folders = [x for x in freqai.dd.full_path.iterdir() if x.is_dir()] model_folders = [x for x in freqai.dd.full_path.iterdir() if x.is_dir()]
assert len(model_folders) == 5 assert len(model_folders) == 6
# without deleting the exiting folder structure, re-run # without deleting the exiting folder structure, re-run
@ -263,10 +266,14 @@ def test_start_backtesting_from_existing_folder(mocker, freqai_conf, caplog):
freqai.start_backtesting(df, metadata, freqai.dk) freqai.start_backtesting(df, metadata, freqai.dk)
assert log_has_re( assert log_has_re(
"Found model at ", "Found backtesting prediction file ",
caplog, caplog,
) )
path = (freqai.dd.full_path / freqai.dk.backtest_predictions_folder)
prediction_files = [x for x in path.iterdir() if x.is_file()]
assert len(prediction_files) == 5
shutil.rmtree(Path(freqai.dk.full_path)) shutil.rmtree(Path(freqai.dk.full_path))

View File

@ -1,5 +1,3 @@
from math import isclose
import pytest import pytest
from freqtrade.leverage import interest from freqtrade.leverage import interest
@ -30,9 +28,9 @@ twentyfive_hours = FtPrecise(25.0)
def test_interest(exchange, interest_rate, hours, expected): def test_interest(exchange, interest_rate, hours, expected):
borrowed = FtPrecise(60.0) borrowed = FtPrecise(60.0)
assert isclose(interest( assert pytest.approx(float(interest(
exchange_name=exchange, exchange_name=exchange,
borrowed=borrowed, borrowed=borrowed,
rate=FtPrecise(interest_rate), rate=FtPrecise(interest_rate),
hours=hours hours=hours
), expected) ))) == expected

View File

@ -550,6 +550,7 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001)
mocker.patch("freqtrade.exchange.Exchange.get_max_pair_stake_amount", return_value=float('inf')) mocker.patch("freqtrade.exchange.Exchange.get_max_pair_stake_amount", return_value=float('inf'))
mocker.patch("freqtrade.exchange.Exchange.get_max_leverage", return_value=100) mocker.patch("freqtrade.exchange.Exchange.get_max_leverage", return_value=100)
mocker.patch("freqtrade.optimize.backtesting.price_to_precision", lambda p, *args: p)
patch_exchange(mocker) patch_exchange(mocker)
default_conf_usdt['stake_amount'] = 300 default_conf_usdt['stake_amount'] = 300
default_conf_usdt['max_open_trades'] = 2 default_conf_usdt['max_open_trades'] = 2
@ -562,10 +563,10 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
pair = 'ETH/USDT:USDT' pair = 'ETH/USDT:USDT'
row = [ row = [
pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0), pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0),
0.001, # Open 0.1, # Open
0.0012, # High 0.12, # High
0.00099, # Low 0.099, # Low
0.0011, # Close 0.11, # Close
1, # enter_long 1, # enter_long
0, # exit_long 0, # exit_long
1, # enter_short 1, # enter_short
@ -580,8 +581,8 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
return_value=(0.01, 0.01)) return_value=(0.01, 0.01))
# leverage = 5 # leverage = 5
# ep1(trade.open_rate) = 0.001 # ep1(trade.open_rate) = 0.1
# position(trade.amount) = 1500000 # position(trade.amount) = 15000
# stake_amount = 300 -> wb = 300 / 5 = 60 # stake_amount = 300 -> wb = 300 / 5 = 60
# mmr = 0.01 # mmr = 0.01
# cum_b = 0.01 # cum_b = 0.01
@ -591,26 +592,26 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
# Binance, Long # Binance, Long
# liquidation_price # liquidation_price
# = ((wb + cum_b) - (side_1 * position * ep1)) / ((position * mmr_b) - (side_1 * position)) # = ((wb + cum_b) - (side_1 * position * ep1)) / ((position * mmr_b) - (side_1 * position))
# = ((300 + 0.01) - (1 * 1500000 * 0.001)) / ((1500000 * 0.01) - (1 * 1500000)) # = ((300 + 0.01) - (1 * 15000 * 0.1)) / ((15000 * 0.01) - (1 * 15000))
# = 0.0008080740740740741 # = 0.0008080740740740741
# freqtrade_liquidation_price = liq + (abs(open_rate - liq) * liq_buffer * side_1) # freqtrade_liquidation_price = liq + (abs(open_rate - liq) * liq_buffer * side_1)
# = 0.0008080740740740741 + ((0.001 - 0.0008080740740740741) * 0.05 * 1) # = 0.08080740740740741 + ((0.1 - 0.08080740740740741) * 0.05 * 1)
# = 0.0008176703703703704 # = 0.08176703703703704
trade = backtesting._enter_trade(pair, row=row, direction='long') trade = backtesting._enter_trade(pair, row=row, direction='long')
assert pytest.approx(trade.liquidation_price) == 0.00081767037 assert pytest.approx(trade.liquidation_price) == 0.081767037
# Binance, Short # Binance, Short
# liquidation_price # liquidation_price
# = ((wb + cum_b) - (side_1 * position * ep1)) / ((position * mmr_b) - (side_1 * position)) # = ((wb + cum_b) - (side_1 * position * ep1)) / ((position * mmr_b) - (side_1 * position))
# = ((300 + 0.01) - ((-1) * 1500000 * 0.001)) / ((1500000 * 0.01) - ((-1) * 1500000)) # = ((300 + 0.01) - ((-1) * 15000 * 0.1)) / ((15000 * 0.01) - ((-1) * 15000))
# = 0.0011881254125412541 # = 0.0011881254125412541
# freqtrade_liquidation_price = liq + (abs(open_rate - liq) * liq_buffer * side_1) # freqtrade_liquidation_price = liq + (abs(open_rate - liq) * liq_buffer * side_1)
# = 0.0011881254125412541 + (abs(0.001 - 0.0011881254125412541) * 0.05 * -1) # = 0.11881254125412541 + (abs(0.1 - 0.11881254125412541) * 0.05 * -1)
# = 0.0011787191419141915 # = 0.11787191419141915
trade = backtesting._enter_trade(pair, row=row, direction='short') trade = backtesting._enter_trade(pair, row=row, direction='short')
assert pytest.approx(trade.liquidation_price) == 0.0011787191 assert pytest.approx(trade.liquidation_price) == 0.11787191
# Stake-amount too high! # Stake-amount too high!
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=600.0) mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=600.0)

View File

@ -18,7 +18,8 @@ from tests.conftest import patch_exchange
def test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) -> None: def test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_exit_signal'] = False default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
mocker.patch('freqtrade.optimize.backtesting.amount_to_precision', lambda x, y, z: round(x, 8)) mocker.patch('freqtrade.optimize.backtesting.amount_to_contract_precision',
lambda x, *args, **kwargs: round(x, 8))
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001)
mocker.patch("freqtrade.exchange.Exchange.get_max_pair_stake_amount", return_value=float('inf')) mocker.patch("freqtrade.exchange.Exchange.get_max_pair_stake_amount", return_value=float('inf'))
patch_exchange(mocker) patch_exchange(mocker)

View File

@ -37,6 +37,7 @@ def generate_mock_trade(pair: str, fee: float, is_open: bool,
trade.orders.append(Order( trade.orders.append(Order(
ft_order_side=trade.entry_side, ft_order_side=trade.entry_side,
order_id=f'{pair}-{trade.entry_side}-{trade.open_date}', order_id=f'{pair}-{trade.entry_side}-{trade.open_date}',
ft_is_open=False,
ft_pair=pair, ft_pair=pair,
amount=trade.amount, amount=trade.amount,
filled=trade.amount, filled=trade.amount,
@ -51,6 +52,7 @@ def generate_mock_trade(pair: str, fee: float, is_open: bool,
trade.orders.append(Order( trade.orders.append(Order(
ft_order_side=trade.exit_side, ft_order_side=trade.exit_side,
order_id=f'{pair}-{trade.exit_side}-{trade.close_date}', order_id=f'{pair}-{trade.exit_side}-{trade.close_date}',
ft_is_open=False,
ft_pair=pair, ft_pair=pair,
amount=trade.amount, amount=trade.amount,
filled=trade.amount, filled=trade.amount,

View File

@ -663,7 +663,7 @@ def test_rpc_stop(mocker, default_conf) -> None:
assert freqtradebot.state == State.STOPPED assert freqtradebot.state == State.STOPPED
def test_rpc_stopbuy(mocker, default_conf) -> None: def test_rpc_stopentry(mocker, default_conf) -> None:
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock()) mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
mocker.patch.multiple( mocker.patch.multiple(
'freqtrade.exchange.Exchange', 'freqtrade.exchange.Exchange',
@ -676,8 +676,8 @@ def test_rpc_stopbuy(mocker, default_conf) -> None:
freqtradebot.state = State.RUNNING freqtradebot.state = State.RUNNING
assert freqtradebot.config['max_open_trades'] != 0 assert freqtradebot.config['max_open_trades'] != 0
result = rpc._rpc_stopbuy() result = rpc._rpc_stopentry()
assert {'status': 'No more buy will occur from now. Run /reload_config to reset.'} == result assert {'status': 'No more entries will occur from now. Run /reload_config to reset.'} == result
assert freqtradebot.config['max_open_trades'] == 0 assert freqtradebot.config['max_open_trades'] == 0

View File

@ -422,13 +422,20 @@ def test_api_reloadconf(botclient):
assert ftbot.state == State.RELOAD_CONFIG assert ftbot.state == State.RELOAD_CONFIG
def test_api_stopbuy(botclient): def test_api_stopentry(botclient):
ftbot, client = botclient ftbot, client = botclient
assert ftbot.config['max_open_trades'] != 0 assert ftbot.config['max_open_trades'] != 0
rc = client_post(client, f"{BASE_URI}/stopbuy") rc = client_post(client, f"{BASE_URI}/stopbuy")
assert_response(rc) assert_response(rc)
assert rc.json() == {'status': 'No more buy will occur from now. Run /reload_config to reset.'} assert rc.json() == {
'status': 'No more entries will occur from now. Run /reload_config to reset.'}
assert ftbot.config['max_open_trades'] == 0
rc = client_post(client, f"{BASE_URI}/stopentry")
assert_response(rc)
assert rc.json() == {
'status': 'No more entries will occur from now. Run /reload_config to reset.'}
assert ftbot.config['max_open_trades'] == 0 assert ftbot.config['max_open_trades'] == 0

View File

@ -103,7 +103,8 @@ def test_telegram_init(default_conf, mocker, caplog) -> None:
"['stats'], ['daily'], ['weekly'], ['monthly'], " "['stats'], ['daily'], ['weekly'], ['monthly'], "
"['count'], ['locks'], ['unlock', 'delete_locks'], " "['count'], ['locks'], ['unlock', 'delete_locks'], "
"['reload_config', 'reload_conf'], ['show_config', 'show_conf'], " "['reload_config', 'reload_conf'], ['show_config', 'show_conf'], "
"['stopbuy'], ['whitelist'], ['blacklist'], ['blacklist_delete', 'bl_delete'], " "['stopbuy', 'stopentry'], ['whitelist'], ['blacklist'], "
"['blacklist_delete', 'bl_delete'], "
"['logs'], ['edge'], ['health'], ['help'], ['version']" "['logs'], ['edge'], ['health'], ['help'], ['version']"
"]") "]")
@ -896,10 +897,10 @@ def test_stopbuy_handle(default_conf, update, mocker) -> None:
telegram, freqtradebot, msg_mock = get_telegram_testobject(mocker, default_conf) telegram, freqtradebot, msg_mock = get_telegram_testobject(mocker, default_conf)
assert freqtradebot.config['max_open_trades'] != 0 assert freqtradebot.config['max_open_trades'] != 0
telegram._stopbuy(update=update, context=MagicMock()) telegram._stopentry(update=update, context=MagicMock())
assert freqtradebot.config['max_open_trades'] == 0 assert freqtradebot.config['max_open_trades'] == 0
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert 'No more buy will occur from now. Run /reload_config to reset.' \ assert 'No more entries will occur from now. Run /reload_config to reset.' \
in msg_mock.call_args_list[0][0][0] in msg_mock.call_args_list[0][0][0]

View File

@ -12,7 +12,9 @@ from freqtrade.configuration import TimeRange
from freqtrade.data.dataprovider import DataProvider from freqtrade.data.dataprovider import DataProvider
from freqtrade.data.history import load_data from freqtrade.data.history import load_data
from freqtrade.enums import ExitCheckTuple, ExitType, SignalDirection from freqtrade.enums import ExitCheckTuple, ExitType, SignalDirection
from freqtrade.enums.hyperoptstate import HyperoptState
from freqtrade.exceptions import OperationalException, StrategyError from freqtrade.exceptions import OperationalException, StrategyError
from freqtrade.optimize.hyperopt_tools import HyperoptStateContainer
from freqtrade.optimize.space import SKDecimal from freqtrade.optimize.space import SKDecimal
from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence import PairLocks, Trade
from freqtrade.resolvers import StrategyResolver from freqtrade.resolvers import StrategyResolver
@ -859,7 +861,9 @@ def test_strategy_safe_wrapper_trade_copy(fee):
def test_hyperopt_parameters(): def test_hyperopt_parameters():
HyperoptStateContainer.set_state(HyperoptState.INDICATORS)
from skopt.space import Categorical, Integer, Real from skopt.space import Categorical, Integer, Real
with pytest.raises(OperationalException, match=r"Name is determined.*"): with pytest.raises(OperationalException, match=r"Name is determined.*"):
IntParameter(low=0, high=5, default=1, name='hello') IntParameter(low=0, high=5, default=1, name='hello')
@ -937,6 +941,12 @@ def test_hyperopt_parameters():
assert list(boolpar.range) == [True, False] assert list(boolpar.range) == [True, False]
HyperoptStateContainer.set_state(HyperoptState.OPTIMIZE)
assert len(list(intpar.range)) == 1
assert len(list(fltpar.range)) == 1
assert len(list(catpar.range)) == 1
assert len(list(boolpar.range)) == 1
def test_auto_hyperopt_interface(default_conf): def test_auto_hyperopt_interface(default_conf):
default_conf.update({'strategy': 'HyperoptableStrategyV2'}) default_conf.update({'strategy': 'HyperoptableStrategyV2'})

View File

@ -1,5 +1,3 @@
from math import isclose
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import pytest import pytest
@ -165,7 +163,7 @@ def test_stoploss_from_open():
or (side == 'short' and expected_stop_price < current_price)): or (side == 'short' and expected_stop_price < current_price)):
assert stoploss == 0 assert stoploss == 0
else: else:
assert isclose(stop_price, expected_stop_price, rel_tol=0.00001) assert pytest.approx(stop_price) == expected_stop_price
def test_stoploss_from_absolute(): def test_stoploss_from_absolute():

View File

@ -275,8 +275,8 @@ def test_strategy_override_order_tif(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
order_time_in_force = { order_time_in_force = {
'entry': 'fok', 'entry': 'FOK',
'exit': 'gtc', 'exit': 'GTC',
} }
default_conf.update({ default_conf.update({
@ -290,11 +290,11 @@ def test_strategy_override_order_tif(caplog, default_conf):
assert strategy.order_time_in_force[method] == order_time_in_force[method] assert strategy.order_time_in_force[method] == order_time_in_force[method]
assert log_has("Override strategy 'order_time_in_force' with value in config file:" assert log_has("Override strategy 'order_time_in_force' with value in config file:"
" {'entry': 'fok', 'exit': 'gtc'}.", caplog) " {'entry': 'FOK', 'exit': 'GTC'}.", caplog)
default_conf.update({ default_conf.update({
'strategy': CURRENT_TEST_STRATEGY, 'strategy': CURRENT_TEST_STRATEGY,
'order_time_in_force': {'entry': 'fok'} 'order_time_in_force': {'entry': 'FOK'}
}) })
# Raise error for invalid configuration # Raise error for invalid configuration
with pytest.raises(ImportError, with pytest.raises(ImportError,

View File

@ -973,17 +973,17 @@ def test_validate_time_in_force(default_conf, caplog) -> None:
conf = deepcopy(default_conf) conf = deepcopy(default_conf)
conf['order_time_in_force'] = { conf['order_time_in_force'] = {
'buy': 'gtc', 'buy': 'gtc',
'sell': 'gtc', 'sell': 'GTC',
} }
validate_config_consistency(conf) validate_config_consistency(conf)
assert log_has_re(r"DEPRECATED: Using 'buy' and 'sell' for time_in_force is.*", caplog) assert log_has_re(r"DEPRECATED: Using 'buy' and 'sell' for time_in_force is.*", caplog)
assert conf['order_time_in_force']['entry'] == 'gtc' assert conf['order_time_in_force']['entry'] == 'gtc'
assert conf['order_time_in_force']['exit'] == 'gtc' assert conf['order_time_in_force']['exit'] == 'GTC'
conf = deepcopy(default_conf) conf = deepcopy(default_conf)
conf['order_time_in_force'] = { conf['order_time_in_force'] = {
'buy': 'gtc', 'buy': 'GTC',
'sell': 'gtc', 'sell': 'GTC',
} }
conf['trading_mode'] = 'futures' conf['trading_mode'] = 'futures'
with pytest.raises(OperationalException, with pytest.raises(OperationalException,

View File

@ -1051,8 +1051,6 @@ def test_add_stoploss_on_exchange(mocker, default_conf_usdt, limit_order, is_sho
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True)) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True))
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order) mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[]) mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[])
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount',
return_value=order['amount'])
stoploss = MagicMock(return_value={'id': 13434334}) stoploss = MagicMock(return_value={'id': 13434334})
mocker.patch('freqtrade.exchange.Binance.stoploss', stoploss) mocker.patch('freqtrade.exchange.Binance.stoploss', stoploss)
@ -1875,8 +1873,6 @@ def test_exit_positions(mocker, default_conf_usdt, limit_order, is_short, caplog
mocker.patch('freqtrade.exchange.Exchange.fetch_order', mocker.patch('freqtrade.exchange.Exchange.fetch_order',
return_value=limit_order[entry_side(is_short)]) return_value=limit_order[entry_side(is_short)])
mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[]) mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[])
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount',
return_value=limit_order[entry_side(is_short)]['amount'])
trade = MagicMock() trade = MagicMock()
trade.is_short = is_short trade.is_short = is_short
@ -1886,14 +1882,13 @@ def test_exit_positions(mocker, default_conf_usdt, limit_order, is_short, caplog
n = freqtrade.exit_positions(trades) n = freqtrade.exit_positions(trades)
assert n == 0 assert n == 0
# Test amount not modified by fee-logic # Test amount not modified by fee-logic
assert not log_has( assert not log_has_re(r'Applying fee to amount for Trade .*', caplog)
'Applying fee to amount for Trade {} from 30.0 to 90.81'.format(trade), caplog
)
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=90.81) gra = mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=0.0)
# test amount modified by fee-logic # test amount modified by fee-logic
n = freqtrade.exit_positions(trades) n = freqtrade.exit_positions(trades)
assert n == 0 assert n == 0
assert gra.call_count == 0
@pytest.mark.parametrize("is_short", [False, True]) @pytest.mark.parametrize("is_short", [False, True])
@ -1927,8 +1922,7 @@ def test_update_trade_state(mocker, default_conf_usdt, limit_order, is_short, ca
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True)) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True))
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order) mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[]) mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[])
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=0.0)
return_value=order['amount'])
order_id = order['id'] order_id = order['id']
trade = Trade( trade = Trade(
@ -1960,11 +1954,11 @@ def test_update_trade_state(mocker, default_conf_usdt, limit_order, is_short, ca
assert trade.amount == order['amount'] assert trade.amount == order['amount']
trade.open_order_id = order_id trade.open_order_id = order_id
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=90.81) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=0.01)
assert trade.amount != 90.81 assert trade.amount == 30.0
# test amount modified by fee-logic # test amount modified by fee-logic
freqtrade.update_trade_state(trade, order_id) freqtrade.update_trade_state(trade, order_id)
assert trade.amount == 90.81 assert trade.amount == 29.99
assert trade.open_order_id is None assert trade.open_order_id is None
trade.is_open = True trade.is_open = True
@ -4268,10 +4262,10 @@ def test_get_real_amount_quote(default_conf_usdt, trades_for_order, buy_order_fe
caplog.clear() caplog.clear()
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount is reduced by "fee" # Amount is reduced by "fee"
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == amount - (amount * 0.001) assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == (amount * 0.001)
assert log_has( assert log_has(
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, is_short=False,' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, is_short=False,'
' leverage=1.0, open_rate=0.24544100, open_since=closed) (from 8.0 to 7.992).', ' leverage=1.0, open_rate=0.24544100, open_since=closed), fee=0.008.',
caplog caplog
) )
@ -4296,7 +4290,7 @@ def test_get_real_amount_quote_dust(default_conf_usdt, trades_for_order, buy_ord
walletmock.reset_mock() walletmock.reset_mock()
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount is kept as is # Amount is kept as is
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == amount assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) is None
assert walletmock.call_count == 1 assert walletmock.call_count == 1
assert log_has_re(r'Fee amount for Trade.* was in base currency ' assert log_has_re(r'Fee amount for Trade.* was in base currency '
'- Eating Fee 0.008 into dust', caplog) '- Eating Fee 0.008 into dust', caplog)
@ -4319,7 +4313,7 @@ def test_get_real_amount_no_trade(default_conf_usdt, buy_order_fee, caplog, mock
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount is reduced by "fee" # Amount is reduced by "fee"
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == amount assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) is None
assert log_has( assert log_has(
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, ' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, '
'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) failed: ' 'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) failed: '
@ -4343,8 +4337,7 @@ def test_get_real_amount_no_trade(default_conf_usdt, buy_order_fee, caplog, mock
# from order # from order
({'cost': 0.004, 'currency': 'LTC'}, 0.004, False, ( ({'cost': 0.004, 'currency': 'LTC'}, 0.004, False, (
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, ' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, '
'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) (from' 'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed), fee=0.004.'
' 8.0 to 7.996).'
)), )),
# invalid, no currency in from fee dict # invalid, no currency in from fee dict
({'cost': 0.008, 'currency': None}, 0, True, None), ({'cost': 0.008, 'currency': None}, 0, True, None),
@ -4376,7 +4369,11 @@ def test_get_real_amount(
caplog.clear() caplog.clear()
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, buy_order, order_obj) == amount - fee_reduction_amount res = freqtrade.get_real_amount(trade, buy_order, order_obj)
if fee_reduction_amount == 0:
assert res is None
else:
assert res == fee_reduction_amount
if expected_log: if expected_log:
assert log_has(expected_log, caplog) assert log_has(expected_log, caplog)
@ -4422,14 +4419,14 @@ def test_get_real_amount_multi(
return_value={'ask': 0.19, 'last': 0.2}) return_value={'ask': 0.19, 'last': 0.2})
# Amount is reduced by "fee" # Amount is reduced by "fee"
expected_amount = amount - (amount * fee_reduction_amount) expected_amount = amount * fee_reduction_amount
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == expected_amount assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == expected_amount
assert log_has( assert log_has(
( (
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, ' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, '
'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) ' 'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed), '
f'(from 8.0 to {expected_log_amount}).' f'fee={expected_amount}.'
), ),
caplog caplog
) )
@ -4462,7 +4459,7 @@ def test_get_real_amount_invalid_order(default_conf_usdt, trades_for_order, buy_
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount does not change # Amount does not change
assert freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) == amount assert freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) is None
def test_get_real_amount_fees_order(default_conf_usdt, market_buy_order_usdt_doublefee, def test_get_real_amount_fees_order(default_conf_usdt, market_buy_order_usdt_doublefee,
@ -4485,7 +4482,7 @@ def test_get_real_amount_fees_order(default_conf_usdt, market_buy_order_usdt_dou
# Amount does not change # Amount does not change
assert trade.fee_open == 0.0025 assert trade.fee_open == 0.0025
order_obj = Order.parse_from_ccxt_object(market_buy_order_usdt_doublefee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(market_buy_order_usdt_doublefee, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, market_buy_order_usdt_doublefee, order_obj) == 30.0 assert freqtrade.get_real_amount(trade, market_buy_order_usdt_doublefee, order_obj) is None
assert tfo_mock.call_count == 0 assert tfo_mock.call_count == 0
# Fetch fees from trades dict if available to get "proper" values # Fetch fees from trades dict if available to get "proper" values
assert round(trade.fee_open, 4) == 0.001 assert round(trade.fee_open, 4) == 0.001
@ -4537,7 +4534,7 @@ def test_get_real_amount_wrong_amount_rounding(default_conf_usdt, trades_for_ord
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount changes by fee amount. # Amount changes by fee amount.
assert pytest.approx(freqtrade.get_real_amount( assert pytest.approx(freqtrade.get_real_amount(
trade, limit_buy_order_usdt, order_obj)) == amount - (amount * 0.001) trade, limit_buy_order_usdt, order_obj)) == (amount * 0.001)
def test_get_real_amount_open_trade_usdt(default_conf_usdt, fee, mocker): def test_get_real_amount_open_trade_usdt(default_conf_usdt, fee, mocker):
@ -4559,7 +4556,7 @@ def test_get_real_amount_open_trade_usdt(default_conf_usdt, fee, mocker):
} }
freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt) freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt)
order_obj = Order.parse_from_ccxt_object(order, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(order, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, order, order_obj) == amount assert freqtrade.get_real_amount(trade, order, order_obj) is None
def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker, caplog): def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker, caplog):
@ -4616,7 +4613,7 @@ def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker,
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj)
assert res == amount assert res is None
assert trade.fee_open_currency is None assert trade.fee_open_currency is None
assert trade.fee_open_cost is None assert trade.fee_open_cost is None
message = "Not updating buy-fee - rate: None, POINT." message = "Not updating buy-fee - rate: None, POINT."
@ -4624,7 +4621,7 @@ def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker,
caplog.clear() caplog.clear()
freqtrade.config['exchange']['unknown_fee_rate'] = 1 freqtrade.config['exchange']['unknown_fee_rate'] = 1
res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj)
assert res == amount assert res is None
assert trade.fee_open_currency == 'POINT' assert trade.fee_open_currency == 'POINT'
assert pytest.approx(trade.fee_open_cost) == 0.3046651026 assert pytest.approx(trade.fee_open_cost) == 0.3046651026
assert trade.fee_open == 0.002 assert trade.fee_open == 0.002
@ -4633,12 +4630,12 @@ def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker,
@pytest.mark.parametrize('amount,fee_abs,wallet,amount_exp', [ @pytest.mark.parametrize('amount,fee_abs,wallet,amount_exp', [
(8.0, 0.0, 10, 8), (8.0, 0.0, 10, None),
(8.0, 0.0, 0, 8), (8.0, 0.0, 0, None),
(8.0, 0.1, 0, 7.9), (8.0, 0.1, 0, 0.1),
(8.0, 0.1, 10, 8), (8.0, 0.1, 10, None),
(8.0, 0.1, 8.0, 8.0), (8.0, 0.1, 8.0, None),
(8.0, 0.1, 7.9, 7.9), (8.0, 0.1, 7.9, 0.1),
]) ])
def test_apply_fee_conditional(default_conf_usdt, fee, mocker, def test_apply_fee_conditional(default_conf_usdt, fee, mocker,
amount, fee_abs, wallet, amount_exp): amount, fee_abs, wallet, amount_exp):
@ -4653,11 +4650,17 @@ def test_apply_fee_conditional(default_conf_usdt, fee, mocker,
fee_close=fee.return_value, fee_close=fee.return_value,
open_order_id="123456" open_order_id="123456"
) )
order = Order(
ft_order_side='buy',
order_id='100',
ft_pair=trade.pair,
ft_is_open=True,
)
freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt) freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt)
walletmock.reset_mock() walletmock.reset_mock()
# Amount is kept as is # Amount is kept as is
assert freqtrade.apply_fee_conditional(trade, 'LTC', amount, fee_abs) == amount_exp assert freqtrade.apply_fee_conditional(trade, 'LTC', amount, fee_abs, order) == amount_exp
assert walletmock.call_count == 1 assert walletmock.call_count == 1

View File

@ -1,7 +1,6 @@
# pragma pylint: disable=missing-docstring, C0103 # pragma pylint: disable=missing-docstring, C0103
import logging import logging
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from math import isclose
from pathlib import Path from pathlib import Path
from types import FunctionType from types import FunctionType
from unittest.mock import MagicMock from unittest.mock import MagicMock
@ -582,25 +581,25 @@ def test_update_market_order(market_buy_order_usdt, market_sell_order_usdt, fee,
@pytest.mark.parametrize( @pytest.mark.parametrize(
'exchange,is_short,lev,open_value,close_value,profit,profit_ratio,trading_mode,funding_fees', [ 'exchange,is_short,lev,open_value,close_value,profit,profit_ratio,trading_mode,funding_fees', [
("binance", False, 1, 60.15, 65.835, 5.685, 0.09451371, spot, 0.0), ("binance", False, 1, 60.15, 65.835, 5.685, 0.09451371, spot, 0.0),
("binance", True, 1, 59.850, 66.1663784375, -6.3163784375, -0.1055368, margin, 0.0), ("binance", True, 1, 65.835, 60.151253125, 5.68374687, 0.08633321, margin, 0.0),
("binance", False, 3, 60.15, 65.83416667, 5.68416667, 0.28349958, margin, 0.0), ("binance", False, 3, 60.15, 65.83416667, 5.68416667, 0.28349958, margin, 0.0),
("binance", True, 3, 59.85, 66.1663784375, -6.3163784375, -0.31661044, margin, 0.0), ("binance", True, 3, 65.835, 60.151253125, 5.68374687, 0.25899963, margin, 0.0),
("kraken", False, 1, 60.15, 65.835, 5.685, 0.09451371, spot, 0.0), ("kraken", False, 1, 60.15, 65.835, 5.685, 0.09451371, spot, 0.0),
("kraken", True, 1, 59.850, 66.231165, -6.381165, -0.1066192, margin, 0.0), ("kraken", True, 1, 65.835, 60.21015, 5.62485, 0.0854386, margin, 0.0),
("kraken", False, 3, 60.15, 65.795, 5.645, 0.28154613, margin, 0.0), ("kraken", False, 3, 60.15, 65.795, 5.645, 0.28154613, margin, 0.0),
("kraken", True, 3, 59.850, 66.231165, -6.381165, -0.3198578, margin, 0.0), ("kraken", True, 3, 65.835, 60.21015, 5.62485, 0.25631579, margin, 0.0),
("binance", False, 1, 60.15, 65.835, 5.685, 0.09451371, futures, 0.0), ("binance", False, 1, 60.15, 65.835, 5.685, 0.09451371, futures, 0.0),
("binance", False, 1, 60.15, 66.835, 6.685, 0.11113881, futures, 1.0), ("binance", False, 1, 60.15, 66.835, 6.685, 0.11113881, futures, 1.0),
("binance", True, 1, 59.85, 66.165, -6.315, -0.10551378, futures, 0.0), ("binance", True, 1, 65.835, 60.15, 5.685, 0.08635224, futures, 0.0),
("binance", True, 1, 59.85, 67.165, -7.315, -0.12222222, futures, -1.0), ("binance", True, 1, 65.835, 61.15, 4.685, 0.07116276, futures, -1.0),
("binance", True, 3, 65.835, 59.15, 6.685, 0.3046252, futures, 1.0),
("binance", False, 3, 60.15, 64.835, 4.685, 0.23366583, futures, -1.0), ("binance", False, 3, 60.15, 64.835, 4.685, 0.23366583, futures, -1.0),
("binance", True, 3, 59.85, 65.165, -5.315, -0.26641604, futures, 1.0),
]) ])
@pytest.mark.usefixtures("init_persistence") @pytest.mark.usefixtures("init_persistence")
def test_calc_open_close_trade_price( def test_calc_open_close_trade_price(
limit_buy_order_usdt, limit_sell_order_usdt, fee, exchange, is_short, lev, limit_order, fee, exchange, is_short, lev,
open_value, close_value, profit, profit_ratio, trading_mode, funding_fees open_value, close_value, profit, profit_ratio, trading_mode, funding_fees
): ):
trade: Trade = Trade( trade: Trade = Trade(
@ -618,22 +617,24 @@ def test_calc_open_close_trade_price(
trading_mode=trading_mode, trading_mode=trading_mode,
funding_fees=funding_fees funding_fees=funding_fees
) )
entry_order = limit_order[trade.entry_side]
exit_order = limit_order[trade.exit_side]
trade.open_order_id = f'something-{is_short}-{lev}-{exchange}' trade.open_order_id = f'something-{is_short}-{lev}-{exchange}'
oobj = Order.parse_from_ccxt_object(limit_buy_order_usdt, 'ADA/USDT', 'buy') oobj = Order.parse_from_ccxt_object(entry_order, 'ADA/USDT', trade.entry_side)
trade.orders.append(oobj)
trade.update_trade(oobj) trade.update_trade(oobj)
oobj = Order.parse_from_ccxt_object(limit_sell_order_usdt, 'ADA/USDT', 'sell') oobj = Order.parse_from_ccxt_object(exit_order, 'ADA/USDT', trade.exit_side)
trade.orders.append(oobj)
trade.update_trade(oobj) trade.update_trade(oobj)
trade.open_rate = 2.0 assert trade.is_open is False
trade.close_rate = 2.2
trade.recalc_open_trade_value() assert pytest.approx(trade._calc_open_trade_value(trade.amount, trade.open_rate)) == open_value
assert isclose(trade._calc_open_trade_value(trade.amount, trade.open_rate), open_value) assert pytest.approx(trade.calc_close_trade_value(trade.close_rate)) == close_value
assert isclose(trade.calc_close_trade_value(trade.close_rate), close_value) assert pytest.approx(trade.close_profit_abs) == profit
assert isclose(trade.calc_profit(trade.close_rate), round(profit, 8)) assert pytest.approx(trade.close_profit) == profit_ratio
assert pytest.approx(trade.calc_profit_ratio(trade.close_rate)) == profit_ratio
@pytest.mark.usefixtures("init_persistence") @pytest.mark.usefixtures("init_persistence")
@ -655,6 +656,7 @@ def test_trade_close(fee):
trade.orders.append(Order( trade.orders.append(Order(
ft_order_side=trade.entry_side, ft_order_side=trade.entry_side,
order_id=f'{trade.pair}-{trade.entry_side}-{trade.open_date}', order_id=f'{trade.pair}-{trade.entry_side}-{trade.open_date}',
ft_is_open=False,
ft_pair=trade.pair, ft_pair=trade.pair,
amount=trade.amount, amount=trade.amount,
filled=trade.amount, filled=trade.amount,
@ -668,6 +670,7 @@ def test_trade_close(fee):
trade.orders.append(Order( trade.orders.append(Order(
ft_order_side=trade.exit_side, ft_order_side=trade.exit_side,
order_id=f'{trade.pair}-{trade.exit_side}-{trade.open_date}', order_id=f'{trade.pair}-{trade.exit_side}-{trade.open_date}',
ft_is_open=False,
ft_pair=trade.pair, ft_pair=trade.pair,
amount=trade.amount, amount=trade.amount,
filled=trade.amount, filled=trade.amount,
@ -2894,8 +2897,8 @@ def test_order_to_ccxt(limit_buy_order_open):
(('buy', 100, 9), (200.0, 8.5, 1700.0, 0.0, None, None)), (('buy', 100, 9), (200.0, 8.5, 1700.0, 0.0, None, None)),
(('sell', 100, 10), (100.0, 8.5, 850.0, 150.0, 150.0, 0.17647059)), (('sell', 100, 10), (100.0, 8.5, 850.0, 150.0, 150.0, 0.17647059)),
(('buy', 150, 11), (250.0, 10, 2500.0, 150.0, 150.0, 0.17647059)), (('buy', 150, 11), (250.0, 10, 2500.0, 150.0, 150.0, 0.17647059)),
(('sell', 100, 12), (150.0, 10.0, 1500.0, 350.0, 350.0, 0.2)), (('sell', 100, 12), (150.0, 10.0, 1500.0, 350.0, 200.0, 0.2)),
(('sell', 150, 14), (150.0, 10.0, 1500.0, 950.0, 950.0, 0.40)), (('sell', 150, 14), (150.0, 10.0, 1500.0, 950.0, 600.0, 0.40)),
], ],
'end_profit': 950.0, 'end_profit': 950.0,
'end_profit_ratio': 0.283582, 'end_profit_ratio': 0.283582,
@ -2960,9 +2963,8 @@ def test_recalc_trade_from_orders_dca(data) -> None:
assert trade.amount == result[0] assert trade.amount == result[0]
assert trade.open_rate == result[1] assert trade.open_rate == result[1]
assert trade.stake_amount == result[2] assert trade.stake_amount == result[2]
# TODO: enable the below.
assert pytest.approx(trade.realized_profit) == result[3] assert pytest.approx(trade.realized_profit) == result[3]
# assert pytest.approx(trade.close_profit_abs) == result[4] assert pytest.approx(trade.close_profit_abs) == result[4]
assert pytest.approx(trade.close_profit) == result[5] assert pytest.approx(trade.close_profit) == result[5]
trade.close(price) trade.close(price)