diff --git a/docs/assets/freqai_DI.png b/docs/assets/freqai_DI.png new file mode 100644 index 000000000..d8c994f85 Binary files /dev/null and b/docs/assets/freqai_DI.png differ diff --git a/docs/assets/freqai_algo.png b/docs/assets/freqai_algo.png index 13813e129..e27829a53 100644 Binary files a/docs/assets/freqai_algo.png and b/docs/assets/freqai_algo.png differ diff --git a/docs/assets/freqai_dbscan.png b/docs/assets/freqai_dbscan.png new file mode 100644 index 000000000..63cfa1e8b Binary files /dev/null and b/docs/assets/freqai_dbscan.png differ diff --git a/docs/assets/freqai_moving-window.png b/docs/assets/freqai_moving-window.png new file mode 100644 index 000000000..ad5c872cc Binary files /dev/null and b/docs/assets/freqai_moving-window.png differ diff --git a/docs/assets/freqai_weight-factor.png b/docs/assets/freqai_weight-factor.png new file mode 100644 index 000000000..84943b438 Binary files /dev/null and b/docs/assets/freqai_weight-factor.png differ diff --git a/docs/data-download.md b/docs/data-download.md index 681fb717d..55c2ad738 100644 --- a/docs/data-download.md +++ b/docs/data-download.md @@ -374,6 +374,7 @@ usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--data-format-ohlcv {json,jsongz,hdf5}] [-p PAIRS [PAIRS ...]] [--trading-mode {spot,margin,futures}] + [--show-timerange] optional arguments: -h, --help show this help message and exit @@ -387,6 +388,8 @@ optional arguments: separated. --trading-mode {spot,margin,futures} Select Trading mode + --show-timerange Show timerange available for available data. (May take + a while to calculate). Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). diff --git a/docs/freqai.md b/docs/freqai.md index b22e1cd31..bba6faaea 100644 --- a/docs/freqai.md +++ b/docs/freqai.md @@ -2,67 +2,63 @@ # FreqAI -FreqAI is a module designed to automate a variety of tasks associated with training a predictive model to generate market forecasts given a set of input features. +FreqAI is a module designed to automate a variety of tasks associated with training a predictive machine learning model to generate market forecasts given a set of input features. -Among the the features included: +Features include: -* **Self-adaptive retraining**: retrain models during live deployments to self-adapt to the market in an unsupervised manner. -* **Rapid feature engineering**: create large rich feature sets (10k+ features) based on simple user created strategies. -* **High performance**: adaptive retraining occurs on separate thread (or on GPU if available) from inferencing and bot trade operations. Keep newest models and data in memory for rapid inferencing. -* **Realistic backtesting**: emulate self-adaptive retraining with backtesting module that automates past retraining. -* **Modifiable**: use the generalized and robust architecture for incorporating any machine learning library/method available in Python. Seven examples available. -* **Smart outlier removal**: remove outliers from training and prediction sets using a variety of outlier detection techniques. -* **Crash resilience**: model storage to disk to make reloading from a crash fast and easy (and purge obsolete files for sustained dry/live runs). -* **Automated data normalization**: normalize the data in a smart and statistically safe way. +* **Self-adaptive retraining**: retrain models during [live deployments](#running-the-model-live) to self-adapt to the market in an unsupervised manner. +* **Rapid feature engineering**: create large rich [feature sets](#feature-engineering) (10k+ features) based on simple user-created strategies. +* **High performance**: adaptive retraining occurs on a separate thread (or on GPU if available) from inferencing and bot trade operations. Newest models and data are kept in memory for rapid inferencing. +* **Realistic backtesting**: emulate self-adaptive retraining with a [backtesting module](#backtesting) that automates past retraining. +* **Modifiability**: use the generalized and robust architecture for incorporating any [machine learning library/method](#building-a-custom-prediction-model) available in Python. Eight examples are currently available, including classifiers, regressors, and a convolutional neural network. +* **Smart outlier removal**: remove outliers from training and prediction data sets using a variety of [outlier detection techniques](#outlier-removal). +* **Crash resilience**: store model to disk to make reloading from a crash fast and easy, and [purge obsolete files](#purging-old-model-data) for sustained dry/live runs. +* **Automatic data normalization**: [normalize the data](#feature-normalization) in a smart and statistically safe way. * **Automatic data download**: compute the data download timerange and update historic data (in live deployments). -* **Clean incoming data** safe NaN handling before training and prediction. -* **Dimensionality reduction**: reduce the size of the training data via Principal Component Analysis. -* **Deploy bot fleets**: set one bot to train models while a fleet of other bots inference into the models and handle trades. +* **Cleaning of incoming data**: handle NaNs safely before training and prediction. +* **Dimensionality reduction**: reduce the size of the training data via [Principal Component Analysis](#reducing-data-dimensionality-with-principal-component-analysis). +* **Deploying bot fleets**: set one bot to train models while a fleet of [follower bots](#setting-up-a-follower) inference the models and handle trades. ## Quick start -The easiest way to quickly test FreqAI is to run it in dry run with the following command +The easiest way to quickly test FreqAI is to run it in dry mode with the following command ```bash freqtrade trade --config config_examples/config_freqai.example.json --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates ``` -where the user will see the boot-up process of auto-data downloading, followed by simultaneous training and trading. +The user will see the boot-up process of automatic data downloading, followed by simultaneous training and trading. -The example strategy, example prediction model, and example config can all be found in -`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`, +The example strategy, example prediction model, and example config can be found in +`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`, and `config_examples/config_freqai.example.json`, respectively. ## General approach -The user provides FreqAI with a set of custom *base* indicators (created inside the strategy the same way -a typical Freqtrade strategy is created) as well as target values which look into the future. -FreqAI trains a model to predict the target value 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. In dry/live conditions, FreqAI can be set to constant retraining in a background thread in an effort to keep models as young as possible. +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. -An overview of the algorithm is shown here to help users understand 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) -## Background and vocabulary +### Important machine learning vocabulary -**Features** are the quantities with which a model is trained. $X_i$ represents the -vector of all features for a single candle. In FreqAI, the user -builds the features from anything they can construct in the strategy. +**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. -**Labels** are the target values with which the weights inside a model are trained -toward. Each set of features is associated with a single label, which is also -defined within the strategy by the user. These labels intentionally look into the -future, and are not available to the model during dryrun/live/backtesting. +**Labels** - the target values that a model is trained +toward. Each set of features is associated with a single label that is +defined by the user within the strategy. These labels intentionally look into the +future, and are not available to the model during dry/live/backtesting. -**Training** refers to the process of feeding individual feature sets into the -model with associated labels with the goal of matching input feature sets to associated labels. +**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. -**Train data** is a subset of the historic data which is fed to the model during -training to adjust weights. This data directly influences weight connections in the model. +**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. -**Test data** is a subset of the historic data which is used to evaluate the -intermediate performance of the model during training. This data does not -directly 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 @@ -81,72 +77,80 @@ For docker users, a dedicated tag with freqAI dependencies is available as `:fre As such - you can replace the image line in your docker-compose file with `image: freqtradeorg/freqtrade:develop_freqai`. This image contains the regular freqAI dependencies. Similar to native installs, Catboost will not be available on ARM based devices. -## Configuring FreqAI +## Setting up FreqAI ### Parameter table -The table below will list all configuration parameters available for FreqAI. +The table below will list all configuration parameters available for FreqAI, presented in the same order as `config_examples/config_freqai.example.json`. Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways. | Parameter | Description | |------------|-------------| -| `freqai` | **Required.** The parent dictionary containing all the parameters below for controlling FreqAI.
**Datatype:** dictionary. -| `identifier` | **Required.** A unique name for the current model. This can be reused to reload pre-trained models/data.
**Datatype:** string. -| `train_period_days` | **Required.** Number of days to use for the training data (width of the sliding window).
**Datatype:** positive integer. -| `backtest_period_days` | **Required.** Number of days to inference into the trained model before sliding the window and retraining. 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.
**Datatype:** Float. -| `live_retrain_hours` | Frequency of retraining during dry/live runs. Default set to 0, which means it will retrain as often as possible.
**Datatype:** Float > 0. -| `follow_mode` | If true, this instance of FreqAI will look for models associated with `identifier` and load those for inferencing. A `follower` will **not** train new models. `False` by default.
**Datatype:** boolean. -| `startup_candles` | Number of candles needed for *backtesting only* to ensure all indicators are non NaNs at the start of the first train period.
**Datatype:** positive integer. -| `fit_live_predictions_candles` | Computes target (label) statistics from prediction data, instead of from the training data set. Number of candles is the number of historical candles it uses to generate the statistics.
**Datatype:** positive integer. -| `purge_old_models` | Tell FreqAI to delete obsolete models. Otherwise, all historic models will remain on disk. Defaults to `False`.
**Datatype:** boolean. -| `expiration_hours` | Ask FreqAI to avoid making predictions if a model is more than `expiration_hours` old. Defaults to 0 which means models never expire.
**Datatype:** positive integer. -| | **Feature Parameters** -| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples shown [here](#feature-engineering)
**Datatype:** dictionary. -| `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` will be created for each coin in this list, and that set of features is added to the base asset feature set.
**Datatype:** list of assets (strings). -| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for and added as features to the base asset feature set.
**Datatype:** list of timeframes (strings). -| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators`, refer to `templates/FreqaiExampleStrategy.py` for detailed usage. The user can create custom labels, making use of this parameter not.
**Datatype:** positive integer. -| `include_shifted_candles` | Parameter used to add a sense of temporal recency to flattened regression type input data. `include_shifted_candles` takes all features, duplicates and shifts them by the number indicated by user.
**Datatype:** positive integer. -| `DI_threshold` | Activates the Dissimilarity Index for outlier detection when above 0, explained in detail [here](#removing-outliers-with-the-dissimilarity-index).
**Datatype:** positive float (typically below 1). -| `weight_factor` | Used to set weights for training data points according to their recency, see details and a figure of how it works [here](#controlling-the-model-learning-process).
**Datatype:** positive float (typically below 1). -| `principal_component_analysis` | Ask FreqAI to automatically reduce the dimensionality of the data set using PCA.
**Datatype:** boolean. -| `use_SVM_to_remove_outliers` | Ask FreqAI to train a support vector machine to detect and remove outliers from the training data set as well as from incoming data points.
**Datatype:** boolean. -| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. E.g. `nu` *Very* broadly, is the percentage of data points that should be considered outliers. `shuffle` is by default false to maintain reproducibility. But these and all others can be added/changed in this dictionary.
**Datatype:** dictionary. -| `stratify_training_data` | This value is used to indicate the stratification of the data. e.g. 2 would set every 2nd data point into a separate dataset to be pulled from during training/testing.
**Datatype:** positive integer. -| `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 it should download so that the first data point does not have a NaN
**Datatype:** positive integer. -| `indicator_periods_candles` | A list of integers used to duplicate all indicators according to a set of periods and add them to the feature set.
**Datatype:** list of positive integers. -| `use_DBSCAN_to_remove_outliers` | Inactive by default. If true, FreqAI clusters data using DBSCAN to identify and remove outliers from training and prediction data.
**Datatype:** float (fraction of 1). +| | **General configuration parameters** +| `freqai` | **Required.**
The parent dictionary containing all the parameters for controlling FreqAI.
**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.
**Datatype:** Positive integer. +| `purge_old_models` | Delete obsolete models (otherwise, all historic models will remain on disk).
**Datatype:** Boolean. Default: `False`. +| `train_period_days` | **Required.**
Number of days to use for the training data (width of the sliding window).
**Datatype:** Positive integer. +| `backtest_period_days` | **Required.**
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.
**Datatype:** Float. +| `identifier` | **Required.**
A unique name for the current model. This can be reused to reload pre-trained models/data.
**Datatype:** String. +| `live_retrain_hours` | Frequency of retraining during dry/live runs.
Default set to 0, which means the model will retrain as often as possible.
**Datatype:** Float > 0. +| `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old.
Defaults set to 0, which means models never expire.
**Datatype:** Positive integer. +| `fit_live_predictions_candles` | Number of historical candles to use for computing target (label) statistics from prediction data, instead of from the training data set.
**Datatype:** Positive integer. +| `follow_mode` | If true, this instance of FreqAI will look for models associated with `identifier` and load those for inferencing. A `follower` will **not** train new models.
**Datatype:** Boolean. Default: `False`. +| | **Feature parameters** +| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples are shown [here](#feature-engineering).
**Datatype:** Dictionary. +| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for. The list is added as features to the base asset feature set.
**Datatype:** List of timeframes (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.
**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.
**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.
**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).
**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.
**Datatype:** Positive integer. +| `indicator_periods_candles` | Calculate indicators for `indicator_periods_candles` time periods and add them to the feature set.
**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)
**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)
**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).
**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).
**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).
**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).
**Datatype:** Boolean. | | **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)
**Datatype:** dictionary. -| `test_size` | Fraction of data that should be used for testing instead of training.
**Datatype:** positive float below 1. -| `shuffle` | Shuffle the training data points during training. Typically for time-series forecasting, this is set to False.
**Datatype:** boolean. +| `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).
**Datatype:** Dictionary. +| `test_size` | Fraction of data that should be used for testing instead of training.
**Datatype:** Positive float < 1. +| `shuffle` | Shuffle the training data points during training. Typically, for time-series forecasting, this is set to `False`.
| | **Model training parameters** -| `model_training_parameters` | A flexible dictionary that includes all parameters available by the user selected library. For example, if the user uses `LightGBMRegressor`, then this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html). If the user selects a different model, then this dictionary can contain any parameter from that different model.
**Datatype:** dictionary. -| `n_estimators` | A common parameter among regressors which sets the number of boosted trees to fit
**Datatype:** integer. -| `learning_rate` | A common parameter among regressors which sets the boosting learning rate.
**Datatype:** float. -| `n_jobs`, `thread_count`, `task_type` | Different libraries use different parameter names to control the number of threads used for parallel processing or whether or not it is a `task_type` of `gpu` or `cpu`.
**Datatype:** float. +| `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, this dictionary can contain any parameter from that model.
**Datatype:** Dictionary.**Datatype:** Boolean. +| `n_estimators` | The number of boosted trees to fit in regression.
**Datatype:** Integer. +| `learning_rate` | Boosting learning rate during regression.
**Datatype:** Float. +| `n_jobs`, `thread_count`, `task_type` | Set the number of threads for parallel processing and the `task_type` (`gpu` or `cpu`). Different model libraries use different parameter names.
**Datatype:** Float. | | **Extraneous parameters** -| `keras` | If your model makes use of keras (typical of Tensorflow based prediction models), activate this flag so that the model save/loading follows keras standards. Default value `false`
**Datatype:** boolean. -| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for `shift` by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction. Default value, 2
**Datatype:** integer. +| `keras` | If your model makes use of Keras (typical for Tensorflow-based prediction models), activate this flag so that the model save/loading follows Keras standards.
**Datatype:** Boolean. Default: `False`. +| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for shifting candles (`include_shifted_candles`) by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction.
**Datatype:** Integer. Default: 2. -### Important FreqAI dataframe key patterns +### Important dataframe key patterns -Here are the values the user can expect to include/use inside the typical strategy dataframe (`df[]`): +Below are the values the user can expect to include/use inside a typical strategy dataframe (`df[]`): | DataFrame Key | Description | |------------|-------------| -| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target inside FreqAI (typically following the naming convention `&-s*`). These same dataframe columns names are fed back to the user as the predictions. For example, the user wishes to predict the price change in the next 40 candles (similar to `templates/FreqaiExampleStrategy.py`) by setting `df['&-s_close']`. FreqAI makes the predictions and gives them back to the user under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`.
**Datatype:** depends on the output of the model. -| `df['&*_std/mean']` | The standard deviation and mean values of the user defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand rarity of prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` to evaluate how often a particular prediction was observed during training (or historically with `fit_live_predictions_candles`)
**Datatype:** float. -| `df['do_predict']` | An indication of an outlier, this return value is integer between -1 and 2 which lets the user understand if the prediction is trustworthy or not. `do_predict==1` means the prediction is trustworthy. If the [Dissimilarity Index](#removing-outliers-with-the-dissimilarity-index) is above the user defined threshold, it will subtract 1 from `do_predict`. If `use_SVM_to_remove_outliers()` is active, then the Support Vector Machine (SVM) may also detect outliers in training and prediction data. In this case, the SVM will also subtract one from `do_predict`. A particular case is when `do_predict == 2`, it means that the model has expired due to `expired_hours`.
**Datatype:** integer between -1 and 2. -| `df['DI_values']` | The raw Dissimilarity Index values to give the user a sense of confidence in the prediction. Lower DI means the data point is closer to the trained parameter space.
**Datatype:** float. -| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature inside FreqAI. For example, the user can include the rsi in the training feature set (similar to `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](#building-the-feature-set).
**Note**: since the number of features prepended with `%` can multiply very quickly (10s of thousands of features is easily engineered using the multiplictative functionality described in the `feature_parameters` table.) these features are removed from the dataframe upon return from FreqAI. If the user wishes to keep a particular type of feature for plotting purposes, you can prepend it with `%%`.
**Datatype:** depends on the output of the model. +| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target (label) inside FreqAI (typically following the naming convention `&-s*`). The names of these dataframe columns are fed back to the user as the predictions. For example, if the user wishes to predict the price change in the next 40 candles (similar to `templates/FreqaiExampleStrategy.py`), they set `df['&-s_close']`. FreqAI makes the predictions and gives them back under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`.
**Datatype:** Depends on the output of the model. +| `df['&*_std/mean']` | Standard deviation and mean values of the user-defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand the rarity of a prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` to evaluate how often a particular prediction was observed during training or historically with `fit_live_predictions_candles`).
**Datatype:** Float. +| `df['do_predict']` | Indication of an outlier data point. The return value is integer between -1 and 2, which lets the user know if the prediction is trustworthy or not. `do_predict==1` means the prediction is trustworthy. If the Dissimilarity Index (DI, see details [here](#removing-outliers-with-the-dissimilarity-index)) of the input data point is above the user-defined threshold, FreqAI will subtract 1 from `do_predict`, resulting in `do_predict==0`. If `use_SVM_to_remove_outliers()` is active, the Support Vector Machine (SVM) may also detect outliers in training and prediction data. In this case, the SVM will also subtract 1 from `do_predict`. If the input data point was considered an outlier by the SVM but not by the DI, the result will be `do_predict==0`. If both the DI and the SVM considers the input data point to be an outlier, the result will be `do_predict==-1`. A particular case is when `do_predict == 2`, which means that the model has expired due to exceeding `expired_hours`.
**Datatype:** Integer between -1 and 2. +| `df['DI_values']` | Dissimilarity Index values are proxies to the level of confidence FreqAI has in the prediction. A lower DI means the prediction is close to the training data, i.e., higher prediction confidence.
**Datatype:** Float. +| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature. For example, the user can include the RSI in the training feature set (similar to in `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](#feature-engineering).
**Note**: Since the number of features prepended with `%` can multiply very quickly (10s of thousands of features is easily engineered using the multiplictative functionality described in the `feature_parameters` table shown above), these features are removed from the dataframe upon return from FreqAI. If the user wishes to keep a particular type of feature for plotting purposes, they can prepend it with `%%`.
**Datatype:** Depends on the output of the model. + +### File structure + +`user_data_dir/models/` contains all the data associated with the trainings and backtests. +This file structure is heavily controlled and inferenced by the `FreqaiDataKitchen()` +and should therefore not be modified. ### Example config file -The user interface is isolated to the typical config file. A typical FreqAI config setup could include: +The user interface is isolated to the typical Freqtrade config file. A FreqAI config should include: ```json "freqai": { + "enabled": true, "startup_candles": 10000, "purge_old_models": true, "train_period_days": 30, @@ -161,229 +165,21 @@ The user interface is isolated to the typical config file. A typical FreqAI conf ], "label_period_candles": 24, "include_shifted_candles": 2, - "weight_factor": 0, "indicator_max_period_candles": 20, "indicator_periods_candles": [10, 20] }, "data_split_parameters" : { - "test_size": 0.25, - "random_state": 42 + "test_size": 0.25 }, "model_training_parameters" : { - "n_estimators": 100, - "random_state": 42, - "learning_rate": 0.02, - "task_type": "CPU", + "n_estimators": 100 }, } ``` -### Feature engineering +## Building a FreqAI strategy -Features are added by the user inside the `populate_any_indicators()` method of the strategy -by prepending indicators with `%` and labels are added by prepending `&`. -There are some important components/structures that the user *must* include when building their feature set. -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 from -various configuration parameters which multiply the feature set such as `include_timeframes`. - -```python - def populate_any_indicators( - self, pair, df, tf, informative=None, set_generalized_indicators=False - ): - """ - Function designed to automatically generate, name and merge features - from user indicated timeframes in the configuration file. User controls the indicators - passed to the training/prediction by prepending indicators with `'%-' + coin ` - (see convention below). I.e. user should not prepend any supporting metrics - (e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the - model. - :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 - :param coin: the name of the coin which will modify the feature names. - """ - - coint = 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) - - bollinger = qtpylib.bollinger_bands( - qtpylib.typical_price(informative), window=t, stds=2.2 - ) - informative[f"{coin}bb_lowerband-period_{t}"] = bollinger["lower"] - informative[f"{coin}bb_middleband-period_{t}"] = bollinger["mid"] - informative[f"{coin}bb_upperband-period_{t}"] = bollinger["upper"] - - informative[f"%-{coin}bb_width-period_{t}"] = ( - informative[f"{coin}bb_upperband-period_{t}"] - - informative[f"{coin}bb_lowerband-period_{t}"] - ) / informative[f"{coin}bb_middleband-period_{t}"] - informative[f"%-{coin}close-bb_lower-period_{t}"] = ( - informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"] - ) - - informative[f"%-{coin}relative_volume-period_{t}"] = ( - informative["volume"] / informative["volume"].rolling(t).mean() - ) - - 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) - - # Add generalized indicators here (because in live, it will call this - # function to populate indicators during training). Notice how we ensure not to - # add them multiple times - if set_generalized_indicators: - df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7 - df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25 - - # user adds targets here by prepending them with &- (see convention below) - # If user wishes to use multiple targets, a multioutput prediction model - # needs to be used such as templates/CatboostPredictionMultiModel.py - df["&-s_close"] = ( - df["close"] - .shift(-self.freqai_info["feature_parameters"]["label_period_candles"]) - .rolling(self.freqai_info["feature_parameters"]["label_period_candles"]) - .mean() - / df["close"] - - 1 - ) - - return df -``` - -The user of the present example does not wish to pass the `bb_lowerband` as a feature to the model, -and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the -model for training/prediction and has therefore prepended it with `%`. - -The `include_timeframes` from the example config above are the timeframes (`tf`) of each call to `populate_any_indicators()` -included metric for inclusion in the feature set. In the present case, the user is asking for the -`5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set. - -In addition, the user can ask for each of these features to be included from -informative pairs using the `include_corr_pairlist`. This means that the present feature -set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of -`ETH/USD`, `LINK/USD`, and `BNB/USD`. - -`include_shifted_candles` is another user controlled parameter which indicates the number of previous -candles to include in the present feature set. In other words, `include_shifted_candles: 2`, tells -FreqAI to include the the past 2 candles for each of the features included in the dataset. - -In total, the number of features the present user has created is: - -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$. - -!!! Note - Features **must** be defined in `populate_any_indicators()`. Making features in `populate_indicators()` - will 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()` - (as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`: - - ```python - def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False): - - ... - - # 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 - # these generalized indicators to the basepair/timeframe - if set_generalized_indicators: - df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7 - df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25 - - # user adds targets here by prepending them with &- (see convention below) - # If user wishes to use multiple targets, a multioutput prediction model - # needs to be used such as templates/CatboostPredictionMultiModel.py - df["&-s_close"] = ( - df["close"] - .shift(-self.freqai_info["feature_parameters"]["label_period_candles"]) - .rolling(self.freqai_info["feature_parameters"]["label_period_candles"]) - .mean() - / df["close"] - - 1 - ) - ``` - - (Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`) - -### Deciding the sliding training window and backtesting duration - -Users define the backtesting timerange with the typical `--timerange` parameter in the user -configuration file. `train_period_days` is the duration of the sliding training window, while -`backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be -a float to indicate sub daily retraining in live/dry mode). In the present example, -the user is asking FreqAI to use a training period of 30 days and backtest the subsequent 7 days. -This means that if the user sets `--timerange 20210501-20210701`, -FreqAI will train 8 separate models (because the full range comprises 8 weeks), -and then backtest the subsequent week associated with each of the 8 training -data set timerange months. Users can think of this as a "sliding window" which -emulates FreqAI retraining itself once per week in live using the previous -month of data. - -In live, the required training data is automatically computed and downloaded. However, in backtesting -the user must manually enter the required number of `startup_candles` in the config. This value -is used to increase the available data to FreqAI and should be sufficient to enable all indicators -to be NaN free at the beginning of the first training timerange. This boils down to identifying the -highest timeframe (`4h` in present example) and the longest indicator period (25 in present example) -and adding this to the `train_period_days`. The units need to be in the base candle time frame: - -`startup_candles` = ( 4 hours * 25 max period * 60 minutes/hour + 30 day train_period_days * 1440 minutes per day ) / 5 min (base time frame) = 1488. - -!!! Note - In dry/live, this is all precomputed and handled automatically. Thus, `startup_candle` has no influence on dry/live. - -!!! Note - Although fractional `backtest_period_days` is allowed, the user should be ware 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. This is why it is physically impossible to truly backtest FreqAI adaptive training. 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. - -## Running FreqAI - -### Backtesting - -The FreqAI backtesting module can be executed with the following command: - -```bash -freqtrade backtesting --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701 -``` - -Backtesting mode requires the user to have the data pre-downloaded (unlike dry/live, where FreqAI automatically downloads the necessary data). The user should be careful to consider that the range of the downloaded data is more than the backtesting range. This is because FreqAI needs data prior to the desired backtesting range in order to train a model to be ready to make predictions on the first candle of the user set backtesting range. More details on how to calculate the data download timerange can be found [here](#deciding-the-sliding-training-window-and-backtesting-duration). - -If this command has never been executed with the existing config file, then it will train a new model -for each pair, for each backtesting window within the bigger `--timerange`. - -!!! Note "Model reuse" - Once the training is completed, the user can execute this again with the same config file and - FreqAI will find the trained models and load them instead of spending time training. This is useful - if the user wants to tweak (or even hyperopt) buy and sell criteria inside the strategy. IF the user - *wants* to retrain a new model with the same config file, then he/she should simply change the `identifier`. - This way, the user can return to using any model they wish by simply changing the `identifier`. - ---- - -### Building a freqai strategy - -The FreqAI strategy requires the user to include the following lines of code in the strategy: +The FreqAI strategy requires the user to include the following lines of code in the standard Freqtrade strategy: ```python @@ -402,9 +198,6 @@ The FreqAI strategy requires the user to include the following lines of code in def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - # All indicators must be populated by populate_any_indicators() for live functionality - # to work correctly. - # 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, # the target mean/std values for each of the labels created by user in @@ -480,160 +273,316 @@ 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 and labels ([more information](#feature-engineering)). 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 classifier targets +## Creating a dynamic target -FreqAI includes a the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. Typically, the user would set the targets using strings: +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. + +```python +dataframe["target_roi"] = dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * 1.25 +dataframe["sell_roi"] = dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * 1.25 +``` + +If the user wishes to consider the population +of *historical predictions* for creating the dynamic target instead of the trained labels, (as discussed above) the user +can do so by setting `fit_live_prediction_candles` in the config to the number of historical prediction candles +the user wishes to use to generate target statistics. + +```json + "freqai": { + "fit_live_prediction_candles": 300, + } +``` + +If the user sets this value, FreqAI will initially use the predictions from the training data +and subsequently begin introducing real prediction data as it is generated. FreqAI will save +this historical data to be reloaded if the user stops and restarts a model with the same `identifier`. + +## Building a custom prediction model + +FreqAI has multiple example prediction model libraries, such as `Catboost` regression (`freqai/prediction_models/CatboostRegressor.py`) and `LightGBM` regression. +However, the user can customize and create their own prediction models using the `IFreqaiModel` class. +The user is encouraged to inherit `train()` and `predict()` to let them customize various aspects of their training procedures. + +## Feature engineering + +Features are added by the user inside the `populate_any_indicators()` method of the strategy +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: + +```python + def populate_any_indicators( + self, pair, df, tf, informative=None, set_generalized_indicators=False + ): + """ + Function designed to automatically generate, name, and merge features + from user-indicated timeframes in the configuration file. The user controls the indicators + passed to the training/prediction by prepending indicators with `'%-' + coin ` + (see convention below). I.e., the user should not prepend any supporting metrics + (e.g., bb_lowerband below) with % unless they explicitly want to pass that metric to the + model. + :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 + :param coin: the name of the coin which will modify the feature names. + """ + + 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) + + bollinger = qtpylib.bollinger_bands( + qtpylib.typical_price(informative), window=t, stds=2.2 + ) + informative[f"{coin}bb_lowerband-period_{t}"] = bollinger["lower"] + informative[f"{coin}bb_middleband-period_{t}"] = bollinger["mid"] + informative[f"{coin}bb_upperband-period_{t}"] = bollinger["upper"] + + informative[f"%-{coin}bb_width-period_{t}"] = ( + informative[f"{coin}bb_upperband-period_{t}"] + - informative[f"{coin}bb_lowerband-period_{t}"] + ) / informative[f"{coin}bb_middleband-period_{t}"] + informative[f"%-{coin}close-bb_lower-period_{t}"] = ( + informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"] + ) + + informative[f"%-{coin}relative_volume-period_{t}"] = ( + informative["volume"] / informative["volume"].rolling(t).mean() + ) + + 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) + + # Add generalized indicators here (because in live, it will call this + # function to populate indicators during training). Notice how we ensure not to + # add them multiple times + if set_generalized_indicators: + df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7 + df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25 + + # user adds targets here by prepending them with &- (see convention below) + # If user wishes to use multiple targets, a multioutput prediction model + # needs to be used such as templates/CatboostPredictionMultiModel.py + df["&-s_close"] = ( + df["close"] + .shift(-self.freqai_info["feature_parameters"]["label_period_candles"]) + .rolling(self.freqai_info["feature_parameters"]["label_period_candles"]) + .mean() + / df["close"] + - 1 + ) + + return df +``` + +In the presented example strategy, the user does not wish to pass the `bb_lowerband` as a feature to the model, +and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the +model for training/prediction and has therefore prepended it with `%`. + +The `include_timeframes` in the example config above are the timeframes (`tf`) of each call to `populate_any_indicators()` in the strategy. In the present case, the user is asking for the +`5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set. + +The user can ask for each of the defined features to be included also from +informative pairs using the `include_corr_pairlist`. This means that the feature +set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of the correlated pairs defined in the config (`ETH/USD`, `LINK/USD`, and `BNB/USD`). + +`include_shifted_candles` indicates the number of previous +candles to include in the feature set. For example, `include_shifted_candles: 2` tells +FreqAI to include the past 2 candles for each of the features in the feature set. + +In total, the number of features the user of the presented example strat has created is: +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$. + +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 +various configuration parameters that multiply the feature set, such as `include_timeframes`. + +!!! Note + 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 + a specific pair or timeframe, they should use the following structure inside `populate_any_indicators()` + (as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`): + + ```python + def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False): + + ... + + # 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 + # these generalized indicators to the basepair/timeframe + if set_generalized_indicators: + df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7 + df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25 + + # user adds targets here by prepending them with &- (see convention below) + # If user wishes to use multiple targets, a multioutput prediction model + # needs to be used such as templates/CatboostPredictionMultiModel.py + df["&-s_close"] = ( + df["close"] + .shift(-self.freqai_info["feature_parameters"]["label_period_candles"]) + .rolling(self.freqai_info["feature_parameters"]["label_period_candles"]) + .mean() + / df["close"] + - 1 + ) + ``` + + (Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`.) + +## Setting classifier targets + +FreqAI includes the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. The user should take care to set the classes using strings: ```python df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down') ``` +Additionally, the example classifier models do not accommodate multiple labels, but they do allow multi-class classification within a single label column. + +## Running FreqAI + +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) + ### Running the model live -FreqAI can be run dry/live using the following command +FreqAI can be run dry/live using the following command: ```bash freqtrade trade --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor ``` By default, FreqAI will not find any existing models and will start by training a new one -given the user configuration settings. Following training, it will use that model to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the pairs to try and keep all models equally "young." FreqAI will always use the newest trained model to make predictions on incoming live data. If users do not want FreqAI to retrain new models as often as possible, they can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before retraining a new model. Additionally, users can set `expired_hours` to tell FreqAI to avoid making predictions on models aged over this number of hours. +based on the user's configuration settings. Following training, the model will be used to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the coin pairs to try to keep all models equally up to date. FreqAI will always use the most recently trained model to make predictions on incoming live data. If the user does not want FreqAI to retrain new models as often as possible, they can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before training a new model. Additionally, the user can set `expired_hours` to tell FreqAI to avoid making predictions on models that are older than that number of hours. -If the user wishes to start dry/live from a backtested saved model, the user only needs to reuse -the same `identifier` parameter +If the user wishes to start a dry/live run from a saved backtest model (or from a previously crashed dry/live session), the user only needs to reuse +the same `identifier` parameter: ```json "freqai": { "identifier": "example", - "live_retrain_hours": 1 + "live_retrain_hours": 0.5 } ``` In this case, although FreqAI will initiate with a pre-trained model, it will still check to see how much time has elapsed since the model was trained, -and if a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will self retrain. +and if a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will retrain. -## Data analysis techniques +### Backtesting -### Controlling the model learning process +The FreqAI backtesting module can be executed with the following command: -Model training parameters are unique to the ML library used by the user. FreqAI allows users to set any parameter for any library using the `model_training_parameters` dictionary in the user configuration file. The example configuration files show some of the example parameters associated with `Catboost` and `LightGBM`, but users can add any parameters available in those libraries. +```bash +freqtrade backtesting --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701 +``` -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 `weight_factor` which allows the user to weight more recent data more strongly -than past data via an exponential function: +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). -$$ W_i = \exp(\frac{-i}{\alpha*n}) $$ +If this command has never been executed with the existing config file, it will train a new model +for each pair, for each backtesting window within the expanded `--timerange`. -where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. +!!! Note "Model reuse" + Once the training is completed, the user can execute the backtesting again with the same config file and + FreqAI will find the trained models and load them instead of spending time training. This is useful + if the user wants to tweak (or even hyperopt) buy and sell criteria inside the strategy. If the user + *wants* to retrain a new model with the same config file, then they should simply change the `identifier`. + This way, the user can return to using any model they wish by simply specifying the `identifier`. -![weight-factor](assets/weights_factor.png) +--- -`train_test_split()` has a parameters called `shuffle`, which users also have access to in FreqAI, that allows them to keep the data unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data. +### Deciding the size of the sliding training window and backtesting duration -Finally, `label_period_candles` defines the offset used for the `labels`. In the present example, -the user is asking for `labels` that are 24 candles in the future. +The user defines the backtesting timerange with the typical `--timerange` parameter in the +configuration file. The duration of the sliding training window is set by `train_period_days`, whilst +`backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be +a float to indicate sub-daily retraining in live/dry mode). In the presented example config, +the user is asking FreqAI to use a training period of 30 days and backtest on the subsequent 7 days. +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`. -### Removing outliers with the Dissimilarity Index +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. -The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each -prediction by the model. To do so, FreqAI measures the distance between each training -data point and all other training data points: +!!! Note + In dry/live mode, this is all precomputed and handled automatically. Thus, `startup_candle` has no influence on dry/live mode. -$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$ +!!! 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. -where $d_{ab}$ is the distance between the normalized points $a$ and $b$. $p$ -is the number of features i.e. the length of the vector $X$. -The characteristic distance, $\overline{d}$ for a set of training data points is simply the mean -of the average distances: +### Defining model expirations -$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$ - -$\overline{d}$ quantifies the spread of the training data, which is compared to -the distance between the new prediction feature vectors, $X_k$ and all the training -data: - -$$ d_k = \arg \min d_{k,i} $$ - -which enables the estimation of a Dissimilarity Index: - -$$ DI_k = d_k/\overline{d} $$ - -Equity and crypto markets suffer from a high level of non-patterned noise in the -form of outlier data points. The dissimilarity index allows predictions which -are outliers and not existent in the model feature space, to be thrown out due -to low levels of certainty. Activating the Dissimilarity Index can be achieved with: +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: ```json "freqai": { - "feature_parameters" : { - "DI_threshold": 1 - } + "expiration_hours": 0.5, } ``` -The user can tweak the DI with `DI_threshold` to increase or decrease the extrapolation of the trained model. +In the presented example config, the user will only allow predictions on models that are less than 1/2 hours old. -### Reducing data dimensionality with Principal Component Analysis +### Purging old model data -Users can reduce the dimensionality of their features by activating the `principal_component_analysis`: +FreqAI stores new model files each time it retrains. These files become obsolete as new models are trained and FreqAI adapts to new market conditions. Users planning to leave FreqAI running for extended periods of time with high frequency retraining should enable `purge_old_models` in their config: ```json "freqai": { - "feature_parameters" : { - "principal_component_analysis": true - } + "purge_old_models": true, } ``` -Which will perform PCA on the features and reduce the dimensionality of the data so that the explained -variance of the data set is >= 0.999. +This will automatically purge all models older than the two most recently trained ones. -### Removing outliers using a Support Vector Machine (SVM) +### Returning additional info from training -The user can tell FreqAI to remove outlier data points from the training/test data sets by setting: +The user may find that there are some important metrics that they'd like to return to the strategy at the end of each model training. +The user can include these metrics by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside their custom prediction model class. FreqAI takes the `my_new_value` assigned in this dictionary and expands it to fit the return dataframe to the strategy. +The user can then use the value in the strategy with `dataframe['my_new_value']`. An example of how this is already used in FreqAI is +the `&*_mean` and `&*_std` values, which indicate the mean and standard deviation of the particular target (label) during the most recent training. +An example, where the user wants to use live metrics from the trade database, is shown below: ```json "freqai": { - "feature_parameters" : { - "use_SVM_to_remove_outliers": true - } + "extra_returns_per_train": {"total_profit": 4} } ``` -FreqAI will train an SVM on the training data (or components if the user activated -`principal_component_analysis`) and remove any data point that it deems to be sitting beyond the feature space. +The user needs to set the standard dictionary in the config so that FreqAI can return proper dataframe shapes. These values will likely be overridden by the prediction model, but in the case where the model has yet to set them, or needs a default initial value, this is the value that will be returned. -### Clustering the training data and removing outliers with DBSCAN - -The user can configure FreqAI to use DBSCAN to cluster training data and remove outliers from the training data set. The user activates `use_DBSCAN_to_remove_outliers` to cluster training data for identification of outliers. Also used to detect incoming outliers for prediction data points. - -```json - "freqai": { - "feature_parameters" : { - "use_DBSCAN_to_remove_outliers": true - } - } -``` - -### Stratifying the data - -The user can stratify the training/testing data using: - -```json - "freqai": { - "feature_parameters" : { - "stratify_training_data": 3 - } - } -``` - -which will split the data chronologically so that every Xth data points is a testing data point. In the -present example, the user is asking for every third data point in the dataframe to be used for -testing, the other points are used for training. - -## Setting up a follower +### Setting up a follower The user can define: @@ -644,112 +593,152 @@ The user can define: } ``` -to indicate to the bot that it should not train models, but instead should look for models trained -by a leader with the same `identifier`. In this example, the user has a leader bot with the -`identifier: "example"` already running or launching simultaneously as the present follower. +to indicate to the bot that it should not train models, but instead should look for models trained by a leader with the same `identifier`. In this example, the user has a leader bot with the `identifier: "example"`. The leader bot is already running or launching simultaneously as the follower. The follower will load models created by the leader and inference them to obtain predictions. -## Purging old model data +## Data manipulation techniques -FreqAI stores new model files each time it retrains. These files become obsolete as new models -are trained and FreqAI adapts to the new market conditions. Users planning to leave FreqAI running -for extended periods of time with high frequency retraining should set `purge_old_models` in their -config: +### Feature normalization + +The feature set created by the user is automatically normalized to the training data. This includes all test data and unseen prediction data (dry/live/backtest). + +### Reducing data dimensionality with Principal Component Analysis + +Users can reduce the dimensionality of their features by activating the `principal_component_analysis` in the config: ```json "freqai": { - "purge_old_models": true, + "feature_parameters" : { + "principal_component_analysis": true + } } ``` -which will automatically purge all models older than the two most recently trained ones. +This will perform PCA on the features and reduce the dimensionality of the data so that the explained variance of the data set is >= 0.999. -## Defining model expirations +### Stratifying the data for training and testing the model -During dry/live, FreqAI trains each pair sequentially (on separate threads/GPU from the main -Freqtrade bot). This means 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 (read trade duration target) for a strategy -is much less than 4 hours. The user can decide to only make trade entries if the model is less than -a certain number of hours in age by setting the `expiration_hours` in the config file: +The user can stratify (group) the training/testing data using: ```json "freqai": { - "expiration_hours": 0.5, + "feature_parameters" : { + "stratify_training_data": 3 + } } ``` -In the present example, the user will only allow predictions on models that are less than 1/2 hours -old. +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 +testing; the other points are used for training. -## Choosing the calculation of the `target_roi` +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. -As shown in `templates/FreqaiExampleStrategy.py`, the `target_roi` is based on two metrics computed -by FreqAI: `label_mean` and `label_std`. These are the statistics associated with the labels used -*during the most recent training*. -This allows the model to know what magnitude of a target to be expecting since it is directly stemming from the training data. -By default, FreqAI computes this based on training data and it assumes the labels are Gaussian distributed. -These are big assumptions that the user should consider when creating their labels. If the user wants to consider the population -of *historical predictions* for creating the dynamic target instead of the trained labels, the user -can do so by setting `fit_live_prediction_candles` to the number of historical prediction candles -the user wishes to use to generate target statistics. +### 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. + +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 +than past data via an exponential function: + +$$ 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. + +![weight-factor](assets/freqai_weight-factor.png) + +`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. + +Finally, `label_period_candles` defines the offset (number of candles into the future) used for the `labels`. In the presented example config, +the user is asking for `labels` that are 24 candles in the future. + +### Outlier removal + +#### Removing outliers with the Dissimilarity Index + +The user can tell FreqAI to remove outlier data points from the training/test data sets using a Dissimilarity Index by including the following statement in the config: ```json "freqai": { - "fit_live_prediction_candles": 300, + "feature_parameters" : { + "DI_threshold": 1 + } } ``` -If the user sets this value, FreqAI will initially use the predictions from the training data set -and then subsequently begin introducing real prediction data as it is generated. FreqAI will save -this historical data to be reloaded if the user stops and restarts with the same `identifier`. +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. -## Extra returns per train +To do so, FreqAI measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points: -Users may find that there are some important metrics that they'd like to return to the strategy at the end of each retrain. -Users can include these metrics by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside their custom prediction -model class. FreqAI takes the `my_new_value` assigned in this dictionary and expands it to fit the return dataframe to the strategy. -The user can then use the value in the strategy with `dataframe['my_new_value']`. An example of how this is already used in FreqAI is -the `&*_mean` and `&*_std` values, which indicate the mean and standard deviation of that particular label during the most recent training. -Another example is shown below if the user wants to use live metrics from the trade database. +$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$ -The user needs to set the standard dictionary in the config so FreqAI can return proper dataframe shapes: +where $d_{ab}$ is the distance between the normalized points $a$ and $b$. $p$ is the number of features, i.e., the length of the vector $X$. The characteristic distance, $\overline{d}$ for a set of training data points is simply the mean of the average distances: + +$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$ + +$\overline{d}$ quantifies the spread of the training data, which is compared to the distance between a new prediction feature vectors, $X_k$ and all the training data: + +$$ d_k = \arg \min d_{k,i} $$ + +which enables the estimation of the Dissimilarity Index as: + +$$ 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. + +Below is a figure that describes the DI for a 3D data set. + +![DI](assets/freqai_DI.png) + +#### Removing outliers using a Support Vector Machine (SVM) + +The user can tell FreqAI to remove outlier data points from the training/test data sets using a SVM by setting: ```json "freqai": { - "extra_returns_per_train": {"total_profit": 4} + "feature_parameters" : { + "use_SVM_to_remove_outliers": true + } } ``` -These values will likely be overridden by the user prediction model, but in the case where the user model has yet to set them, or needs -a default initial value - this is the value that will be returned. +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. -## Building an IFreqaiModel +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. -FreqAI has multiple example prediction model based libraries such as `Catboost` regression (`freqai/prediction_models/CatboostRegressor.py`) and `LightGBM` regression. -However, users can customize and create their own prediction models using the `IFreqaiModel` class. -Users are encouraged to inherit `train()` and `predict()` to let them customize various aspects of their training procedures. +The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers. + +#### Removing outliers with DBSCAN + +The user can configure FreqAI to use DBSCAN to cluster and remove outliers from the training/test data set or incoming outliers from predictions, by activating `use_DBSCAN_to_remove_outliers` in the config: + +```json + "freqai": { + "feature_parameters" : { + "use_DBSCAN_to_remove_outliers": true + } + } +``` + +DBSCAN is an unsupervised machine learning algorithm that clusters data without needing to know how many clusters there should be. + +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) + +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. ## Additional information ### Common pitfalls -FreqAI cannot be combined with `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically). +FreqAI cannot be combined with dynamic `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically). This is for performance reasons - FreqAI relies on making quick predictions/retrains. To do this effectively, it needs to download all the training data at the beginning of a dry/live instance. FreqAI stores and appends -new candles automatically for future retrains. But this means that if new pairs arrive later in the dry run due -to a volume pairlist, it will not have the data ready. FreqAI does work, however, with the `ShufflePairlist`. - -### Feature normalization - -The feature set created by the user is automatically normalized to the training data only. -This includes all test data and unseen prediction data (dry/live/backtest). - -### File structure - -`user_data_dir/models/` contains all the data associated with the trainings and backtests. -This file structure is heavily controlled and read by the `FreqaiDataKitchen()` -and should therefore not be modified. +new candles automatically for future retrains. This means that if new pairs arrive later in the dry run due to a volume pairlist, it will not have the data ready. However, FreqAI does work with the `ShufflePairlist` or a `VolumePairlist` which keeps the total pairlist constant (but reorders the pairs according to volume). ## Credits @@ -758,8 +747,8 @@ FreqAI was developed by a group of individuals who all contributed specific skil Conception and software development: Robert Caulk @robcaulk -Theoretical brainstorming: -Elin Törnquist @thorntwig +Theoretical brainstorming, data analysis: +Elin Törnquist @th0rntwig Code review, software architecture brainstorming: @xmatthias diff --git a/docs/strategy_analysis_example.md b/docs/strategy_analysis_example.md index fbfce37d1..1526ea038 100644 --- a/docs/strategy_analysis_example.md +++ b/docs/strategy_analysis_example.md @@ -14,7 +14,7 @@ from freqtrade.configuration import Configuration # Initialize empty configuration object config = Configuration.from_files([]) -# Optionally, use existing configuration file +# Optionally (recommended), use existing configuration file # config = Configuration.from_files(["config.json"]) # Define some constants @@ -22,7 +22,7 @@ config["timeframe"] = "5m" # Name of the strategy class config["strategy"] = "SampleStrategy" # Location of the data -data_location = Path(config['user_data_dir'], 'data', 'binance') +data_location = config['datadir'] # Pair to analyze - Only use one pair here pair = "BTC/USDT" ``` diff --git a/docs/utils.md b/docs/utils.md index 0dd88b242..5646365e4 100644 --- a/docs/utils.md +++ b/docs/utils.md @@ -611,6 +611,26 @@ Common arguments: ``` +### Webserver mode - docker + +You can also use webserver mode via docker. +Starting a one-off container requires the configuration of the port explicitly, as ports are not exposed by default. +You can use `docker-compose run --rm -p 127.0.0.1:8080:8080 freqtrade webserver` to start a one-off container that'll be removed once you stop it. This assumes that port 8080 is still available and no other bot is running on that port. + +Alternatively, you can reconfigure the docker-compose file to have the command updated: + +``` yml + command: > + webserver + --config /freqtrade/user_data/config.json +``` + +You can now use `docker-compose up` to start the webserver. +This assumes that the configuration has a webserver enabled and configured for docker (listening port = `0.0.0.0`). + +!!! Tip + Don't forget to reset the command back to the trade command if you want to start a live or dry-run bot. + ## Show previous Backtest results Allows you to show previous backtest results. diff --git a/freqtrade/commands/arguments.py b/freqtrade/commands/arguments.py index 48a423be4..266095cfa 100644 --- a/freqtrade/commands/arguments.py +++ b/freqtrade/commands/arguments.py @@ -69,7 +69,7 @@ ARGS_CONVERT_DATA_OHLCV = ARGS_CONVERT_DATA + ["timeframes", "exchange", "tradin ARGS_CONVERT_TRADES = ["pairs", "timeframes", "exchange", "dataformat_ohlcv", "dataformat_trades"] -ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode"] +ARGS_LIST_DATA = ["exchange", "dataformat_ohlcv", "pairs", "trading_mode", "show_timerange"] ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "new_pairs_days", "include_inactive", "timerange", "download_trades", "exchange", "timeframes", diff --git a/freqtrade/commands/cli_options.py b/freqtrade/commands/cli_options.py index f85b75af1..a458c1591 100644 --- a/freqtrade/commands/cli_options.py +++ b/freqtrade/commands/cli_options.py @@ -367,7 +367,7 @@ AVAILABLE_CLI_OPTIONS = { metavar='BASE_CURRENCY', ), "trading_mode": Arg( - '--trading-mode', + '--trading-mode', '--tradingmode', help='Select Trading mode', choices=constants.TRADING_MODES, ), @@ -434,6 +434,11 @@ AVAILABLE_CLI_OPTIONS = { help='Storage format for downloaded trades data. (default: `jsongz`).', choices=constants.AVAILABLE_DATAHANDLERS, ), + "show_timerange": Arg( + '--show-timerange', + help='Show timerange available for available data. (May take a while to calculate).', + action='store_true', + ), "exchange": Arg( '--exchange', help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). ' diff --git a/freqtrade/commands/data_commands.py b/freqtrade/commands/data_commands.py index 311590e64..36a86bece 100644 --- a/freqtrade/commands/data_commands.py +++ b/freqtrade/commands/data_commands.py @@ -5,6 +5,7 @@ from datetime import datetime, timedelta from typing import Any, Dict, List from freqtrade.configuration import TimeRange, setup_utils_configuration +from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.data.converter import convert_ohlcv_format, convert_trades_format from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data, refresh_backtest_trades_data) @@ -177,17 +178,31 @@ def start_list_data(args: Dict[str, Any]) -> None: paircombs = [comb for comb in paircombs if comb[0] in args['pairs']] print(f"Found {len(paircombs)} pair / timeframe combinations.") - groupedpair = defaultdict(list) - for pair, timeframe, candle_type in sorted( - paircombs, - key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2]) - ): - groupedpair[(pair, candle_type)].append(timeframe) + if not config.get('show_timerange'): + groupedpair = defaultdict(list) + for pair, timeframe, candle_type in sorted( + paircombs, + key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2]) + ): + groupedpair[(pair, candle_type)].append(timeframe) - if groupedpair: + if groupedpair: + print(tabulate([ + (pair, ', '.join(timeframes), candle_type) + for (pair, candle_type), timeframes in groupedpair.items() + ], + headers=("Pair", "Timeframe", "Type"), + tablefmt='psql', stralign='right')) + else: + paircombs1 = [( + pair, timeframe, candle_type, + *dhc.ohlcv_data_min_max(pair, timeframe, candle_type) + ) for pair, timeframe, candle_type in paircombs] print(tabulate([ - (pair, ', '.join(timeframes), candle_type) - for (pair, candle_type), timeframes in groupedpair.items() - ], - headers=("Pair", "Timeframe", "Type"), + (pair, timeframe, candle_type, + start.strftime(DATETIME_PRINT_FORMAT), + end.strftime(DATETIME_PRINT_FORMAT)) + for pair, timeframe, candle_type, start, end in paircombs1 + ], + headers=("Pair", "Timeframe", "Type", 'From', 'To'), tablefmt='psql', stralign='right')) diff --git a/freqtrade/configuration/configuration.py b/freqtrade/configuration/configuration.py index b4f36aa3c..0db585acc 100644 --- a/freqtrade/configuration/configuration.py +++ b/freqtrade/configuration/configuration.py @@ -426,6 +426,9 @@ class Configuration: self._args_to_config(config, argname='dataformat_trades', logstring='Using "{}" to store trades data.') + self._args_to_config(config, argname='show_timerange', + logstring='Detected --show-timerange') + def _process_data_options(self, config: Dict[str, Any]) -> None: self._args_to_config(config, argname='new_pairs_days', logstring='Detected --new-pairs-days: {}') diff --git a/freqtrade/data/history/hdf5datahandler.py b/freqtrade/data/history/hdf5datahandler.py index dadc9c7e6..135d97c79 100644 --- a/freqtrade/data/history/hdf5datahandler.py +++ b/freqtrade/data/history/hdf5datahandler.py @@ -7,9 +7,8 @@ import numpy as np import pandas as pd from freqtrade.configuration import TimeRange -from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, - ListPairsWithTimeframes, TradeList) -from freqtrade.enums import CandleType, TradingMode +from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList +from freqtrade.enums import CandleType from .idatahandler import IDataHandler @@ -21,29 +20,6 @@ class HDF5DataHandler(IDataHandler): _columns = DEFAULT_DATAFRAME_COLUMNS - @classmethod - def ohlcv_get_available_data( - cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes: - """ - Returns a list of all pairs with ohlcv data available in this datadir - :param datadir: Directory to search for ohlcv files - :param trading_mode: trading-mode to be used - :return: List of Tuples of (pair, timeframe) - """ - if trading_mode == TradingMode.FUTURES: - datadir = datadir.joinpath('futures') - _tmp = [ - re.search( - cls._OHLCV_REGEX, p.name - ) for p in datadir.glob("*.h5") - ] - return [ - ( - cls.rebuild_pair_from_filename(match[1]), - cls.rebuild_timeframe_from_filename(match[2]), - CandleType.from_string(match[3]) - ) for match in _tmp if match and len(match.groups()) > 1] - @classmethod def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]: """ diff --git a/freqtrade/data/history/history_utils.py b/freqtrade/data/history/history_utils.py index c972c841c..cba1b60db 100644 --- a/freqtrade/data/history/history_utils.py +++ b/freqtrade/data/history/history_utils.py @@ -56,7 +56,7 @@ def load_pair_history(pair: str, fill_missing=fill_up_missing, drop_incomplete=drop_incomplete, startup_candles=startup_candles, - candle_type=candle_type + candle_type=candle_type, ) @@ -97,14 +97,15 @@ def load_data(datadir: Path, fill_up_missing=fill_up_missing, startup_candles=startup_candles, data_handler=data_handler, - candle_type=candle_type + candle_type=candle_type, ) if not hist.empty: result[pair] = hist else: if candle_type is CandleType.FUNDING_RATE and user_futures_funding_rate is not None: logger.warn(f"{pair} using user specified [{user_futures_funding_rate}]") - result[pair] = DataFrame(columns=["open", "close", "high", "low", "volume"]) + elif candle_type not in (CandleType.SPOT, CandleType.FUTURES): + result[pair] = DataFrame(columns=["date", "open", "close", "high", "low", "volume"]) if fail_without_data and not result: raise OperationalException("No data found. Terminating.") diff --git a/freqtrade/data/history/idatahandler.py b/freqtrade/data/history/idatahandler.py index 07dc7c763..846bcc607 100644 --- a/freqtrade/data/history/idatahandler.py +++ b/freqtrade/data/history/idatahandler.py @@ -9,7 +9,7 @@ from abc import ABC, abstractmethod from copy import deepcopy from datetime import datetime, timezone from pathlib import Path -from typing import List, Optional, Type +from typing import List, Optional, Tuple, Type from pandas import DataFrame @@ -39,15 +39,26 @@ class IDataHandler(ABC): raise NotImplementedError() @classmethod - @abstractmethod def ohlcv_get_available_data( cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes: """ Returns a list of all pairs with ohlcv data available in this datadir :param datadir: Directory to search for ohlcv files :param trading_mode: trading-mode to be used - :return: List of Tuples of (pair, timeframe) + :return: List of Tuples of (pair, timeframe, CandleType) """ + if trading_mode == TradingMode.FUTURES: + datadir = datadir.joinpath('futures') + _tmp = [ + re.search( + cls._OHLCV_REGEX, p.name + ) for p in datadir.glob(f"*.{cls._get_file_extension()}")] + return [ + ( + cls.rebuild_pair_from_filename(match[1]), + cls.rebuild_timeframe_from_filename(match[2]), + CandleType.from_string(match[3]) + ) for match in _tmp if match and len(match.groups()) > 1] @classmethod @abstractmethod @@ -73,6 +84,18 @@ class IDataHandler(ABC): :return: None """ + def ohlcv_data_min_max(self, pair: str, timeframe: str, + candle_type: CandleType) -> Tuple[datetime, datetime]: + """ + Returns the min and max timestamp for the given pair and timeframe. + :param pair: Pair to get min/max for + :param timeframe: Timeframe to get min/max for + :param candle_type: Any of the enum CandleType (must match trading mode!) + :return: (min, max) + """ + data = self._ohlcv_load(pair, timeframe, None, candle_type) + return data.iloc[0]['date'].to_pydatetime(), data.iloc[-1]['date'].to_pydatetime() + @abstractmethod def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange], candle_type: CandleType diff --git a/freqtrade/data/history/jsondatahandler.py b/freqtrade/data/history/jsondatahandler.py index 83ec183df..a62e5e381 100644 --- a/freqtrade/data/history/jsondatahandler.py +++ b/freqtrade/data/history/jsondatahandler.py @@ -8,9 +8,9 @@ from pandas import DataFrame, read_json, to_datetime from freqtrade import misc from freqtrade.configuration import TimeRange -from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, ListPairsWithTimeframes, TradeList +from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, TradeList from freqtrade.data.converter import trades_dict_to_list -from freqtrade.enums import CandleType, TradingMode +from freqtrade.enums import CandleType from .idatahandler import IDataHandler @@ -23,28 +23,6 @@ class JsonDataHandler(IDataHandler): _use_zip = False _columns = DEFAULT_DATAFRAME_COLUMNS - @classmethod - def ohlcv_get_available_data( - cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes: - """ - Returns a list of all pairs with ohlcv data available in this datadir - :param datadir: Directory to search for ohlcv files - :param trading_mode: trading-mode to be used - :return: List of Tuples of (pair, timeframe) - """ - if trading_mode == 'futures': - datadir = datadir.joinpath('futures') - _tmp = [ - re.search( - cls._OHLCV_REGEX, p.name - ) for p in datadir.glob(f"*.{cls._get_file_extension()}")] - return [ - ( - cls.rebuild_pair_from_filename(match[1]), - cls.rebuild_timeframe_from_filename(match[2]), - CandleType.from_string(match[3]) - ) for match in _tmp if match and len(match.groups()) > 1] - @classmethod def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]: """ diff --git a/freqtrade/exchange/binance_leverage_tiers.json b/freqtrade/exchange/binance_leverage_tiers.json index 1cf6ba079..eace16c05 100644 --- a/freqtrade/exchange/binance_leverage_tiers.json +++ b/freqtrade/exchange/binance_leverage_tiers.json @@ -81,6 +81,88 @@ } } ], + "1000SHIB/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "1000SHIB/USDT": [ { "tier": 1.0, @@ -1991,6 +2073,88 @@ } } ], + "AUCTION/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "AUDIO/USDT": [ { "tier": 1.0, @@ -5333,6 +5497,88 @@ } } ], + "CVX/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "DAR/USDT": [ { "tier": 1.0, @@ -7013,6 +7259,88 @@ } } ], + "ETC/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "ETC/USDT": [ { "tier": 1.0, @@ -7164,13 +7492,13 @@ "tier": 1.0, "currency": "BUSD", "minNotional": 0.0, - "maxNotional": 25000.0, + "maxNotional": 50000.0, "maintenanceMarginRate": 0.004, "maxLeverage": 50.0, "info": { "bracket": "1", "initialLeverage": "50", - "notionalCap": "25000", + "notionalCap": "50000", "notionalFloor": "0", "maintMarginRatio": "0.004", "cum": "0.0" @@ -7179,7 +7507,7 @@ { "tier": 2.0, "currency": "BUSD", - "minNotional": 25000.0, + "minNotional": 50000.0, "maxNotional": 100000.0, "maintenanceMarginRate": 0.005, "maxLeverage": 25.0, @@ -7187,111 +7515,111 @@ "bracket": "2", "initialLeverage": "25", "notionalCap": "100000", - "notionalFloor": "25000", + "notionalFloor": "50000", "maintMarginRatio": "0.005", - "cum": "25.0" + "cum": "50.0" } }, { "tier": 3.0, "currency": "BUSD", "minNotional": 100000.0, - "maxNotional": 500000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.01, "maxLeverage": 20.0, "info": { "bracket": "3", "initialLeverage": "20", - "notionalCap": "500000", + "notionalCap": "1000000", "notionalFloor": "100000", "maintMarginRatio": "0.01", - "cum": "525.0" + "cum": "550.0" } }, { "tier": 4.0, "currency": "BUSD", - "minNotional": 500000.0, - "maxNotional": 1500000.0, + "minNotional": 1000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 10.0, "info": { "bracket": "4", "initialLeverage": "10", - "notionalCap": "1500000", - "notionalFloor": "500000", + "notionalCap": "5000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.025", - "cum": "8025.0" + "cum": "15550.0" } }, { "tier": 5.0, "currency": "BUSD", - "minNotional": 1500000.0, - "maxNotional": 4000000.0, + "minNotional": 5000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 6.0, "info": { "bracket": "5", "initialLeverage": "6", - "notionalCap": "4000000", - "notionalFloor": "1500000", + "notionalCap": "10000000", + "notionalFloor": "5000000", "maintMarginRatio": "0.05", - "cum": "45525.0" + "cum": "140550.0" } }, { "tier": 6.0, "currency": "BUSD", - "minNotional": 4000000.0, - "maxNotional": 10000000.0, + "minNotional": 10000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "6", "initialLeverage": "5", - "notionalCap": "10000000", - "notionalFloor": "4000000", + "notionalCap": "20000000", + "notionalFloor": "10000000", "maintMarginRatio": "0.1", - "cum": "245525.0" + "cum": "640550.0" } }, { "tier": 7.0, "currency": "BUSD", - "minNotional": 10000000.0, - "maxNotional": 20000000.0, + "minNotional": 20000000.0, + "maxNotional": 40000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "7", "initialLeverage": "4", - "notionalCap": "20000000", - "notionalFloor": "10000000", + "notionalCap": "40000000", + "notionalFloor": "20000000", "maintMarginRatio": "0.125", - "cum": "495525.0" + "cum": "1140550.0" } }, { "tier": 8.0, "currency": "BUSD", - "minNotional": 20000000.0, - "maxNotional": 40000000.0, + "minNotional": 40000000.0, + "maxNotional": 80000000.0, "maintenanceMarginRate": 0.15, "maxLeverage": 3.0, "info": { "bracket": "8", "initialLeverage": "3", - "notionalCap": "40000000", - "notionalFloor": "20000000", + "notionalCap": "80000000", + "notionalFloor": "40000000", "maintMarginRatio": "0.15", - "cum": "995525.0" + "cum": "2140550.0" } }, { "tier": 9.0, "currency": "BUSD", - "minNotional": 40000000.0, + "minNotional": 80000000.0, "maxNotional": 150000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, @@ -7299,25 +7627,25 @@ "bracket": "9", "initialLeverage": "2", "notionalCap": "150000000", - "notionalFloor": "40000000", + "notionalFloor": "80000000", "maintMarginRatio": "0.25", - "cum": "4995525.0" + "cum": "1.014055E7" } }, { "tier": 10.0, "currency": "BUSD", "minNotional": 150000000.0, - "maxNotional": 500000000.0, + "maxNotional": 300000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "10", "initialLeverage": "1", - "notionalCap": "500000000", + "notionalCap": "300000000", "notionalFloor": "150000000", "maintMarginRatio": "0.5", - "cum": "4.2495525E7" + "cum": "4.764055E7" } } ], @@ -7326,13 +7654,13 @@ "tier": 1.0, "currency": "USDT", "minNotional": 0.0, - "maxNotional": 10000.0, + "maxNotional": 100000.0, "maintenanceMarginRate": 0.005, "maxLeverage": 100.0, "info": { "bracket": "1", "initialLeverage": "100", - "notionalCap": "10000", + "notionalCap": "100000", "notionalFloor": "0", "maintMarginRatio": "0.005", "cum": "0.0" @@ -7341,119 +7669,119 @@ { "tier": 2.0, "currency": "USDT", - "minNotional": 10000.0, - "maxNotional": 100000.0, + "minNotional": 100000.0, + "maxNotional": 250000.0, "maintenanceMarginRate": 0.0065, "maxLeverage": 75.0, "info": { "bracket": "2", "initialLeverage": "75", - "notionalCap": "100000", - "notionalFloor": "10000", + "notionalCap": "250000", + "notionalFloor": "100000", "maintMarginRatio": "0.0065", - "cum": "15.0" + "cum": "150.0" } }, { "tier": 3.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 500000.0, + "minNotional": 250000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.01, "maxLeverage": 50.0, "info": { "bracket": "3", "initialLeverage": "50", - "notionalCap": "500000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "250000", "maintMarginRatio": "0.01", - "cum": "365.0" + "cum": "1025.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 500000.0, - "maxNotional": 1500000.0, + "minNotional": 1000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.02, "maxLeverage": 25.0, "info": { "bracket": "4", "initialLeverage": "25", - "notionalCap": "1500000", - "notionalFloor": "500000", + "notionalCap": "5000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.02", - "cum": "5365.0" + "cum": "11025.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 1500000.0, - "maxNotional": 4000000.0, + "minNotional": 5000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "5", "initialLeverage": "10", - "notionalCap": "4000000", - "notionalFloor": "1500000", + "notionalCap": "10000000", + "notionalFloor": "5000000", "maintMarginRatio": "0.05", - "cum": "50365.0" + "cum": "161025.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 4000000.0, - "maxNotional": 10000000.0, + "minNotional": 10000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "6", "initialLeverage": "5", - "notionalCap": "10000000", - "notionalFloor": "4000000", + "notionalCap": "20000000", + "notionalFloor": "10000000", "maintMarginRatio": "0.1", - "cum": "250365.0" + "cum": "661025.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 10000000.0, - "maxNotional": 20000000.0, + "minNotional": 20000000.0, + "maxNotional": 40000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "7", "initialLeverage": "4", - "notionalCap": "20000000", - "notionalFloor": "10000000", + "notionalCap": "40000000", + "notionalFloor": "20000000", "maintMarginRatio": "0.125", - "cum": "500365.0" + "cum": "1161025.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 20000000.0, - "maxNotional": 40000000.0, + "minNotional": 40000000.0, + "maxNotional": 80000000.0, "maintenanceMarginRate": 0.15, "maxLeverage": 3.0, "info": { "bracket": "8", "initialLeverage": "3", - "notionalCap": "40000000", - "notionalFloor": "20000000", + "notionalCap": "80000000", + "notionalFloor": "40000000", "maintMarginRatio": "0.15", - "cum": "1000365.0" + "cum": "2161025.0" } }, { "tier": 9.0, "currency": "USDT", - "minNotional": 40000000.0, + "minNotional": 80000000.0, "maxNotional": 150000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, @@ -7461,25 +7789,25 @@ "bracket": "9", "initialLeverage": "2", "notionalCap": "150000000", - "notionalFloor": "40000000", + "notionalFloor": "80000000", "maintMarginRatio": "0.25", - "cum": "5000365.0" + "cum": "1.0161025E7" } }, { "tier": 10.0, "currency": "USDT", "minNotional": 150000000.0, - "maxNotional": 500000000.0, + "maxNotional": 300000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "10", "initialLeverage": "1", - "notionalCap": "500000000", + "notionalCap": "300000000", "notionalFloor": "150000000", "maintMarginRatio": "0.5", - "cum": "4.2500365E7" + "cum": "4.7661025E7" } } ], @@ -7597,6 +7925,88 @@ } } ], + "FIL/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "FIL/USDT": [ { "tier": 1.0, @@ -9737,6 +10147,104 @@ } } ], + "INJ/USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, + "info": { + "bracket": "1", + "initialLeverage": "25", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.01", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "2", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "75.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "700.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5700.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "5", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11950.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "6", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386950.0" + } + } + ], "IOST/USDT": [ { "tier": 1.0, @@ -10521,6 +11029,170 @@ } } ], + "LDO/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], + "LEVER/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "LINA/USDT": [ { "tier": 1.0, @@ -11663,6 +12335,88 @@ } } ], + "MATIC/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "MATIC/USDT": [ { "tier": 1.0, @@ -16055,6 +16809,88 @@ } } ], + "UNI/BUSD": [ + { + "tier": 1.0, + "currency": "BUSD", + "minNotional": 0.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "0", + "maintMarginRatio": "0.025", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "BUSD", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "2", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "625.0" + } + }, + { + "tier": 3.0, + "currency": "BUSD", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "3", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5625.0" + } + }, + { + "tier": 4.0, + "currency": "BUSD", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "4", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11875.0" + } + }, + { + "tier": 5.0, + "currency": "BUSD", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "5", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386875.0" + } + } + ], "UNI/USDT": [ { "tier": 1.0, diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index dbc3447be..7ef6858a5 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -17,6 +17,7 @@ import ccxt import ccxt.async_support as ccxt_async from cachetools import TTLCache from ccxt import ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE, decimal_to_precision +from dateutil import parser from pandas import DataFrame from freqtrade.constants import (DEFAULT_AMOUNT_RESERVE_PERCENT, NON_OPEN_EXCHANGE_STATES, BuySell, @@ -30,7 +31,8 @@ from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, BAD_EXCHANGE EXCHANGE_HAS_OPTIONAL, EXCHANGE_HAS_REQUIRED, SUPPORTED_EXCHANGES, remove_credentials, retrier, retrier_async) -from freqtrade.misc import chunks, deep_merge_dicts, safe_value_fallback2 +from freqtrade.misc import (chunks, deep_merge_dicts, file_dump_json, file_load_json, + safe_value_fallback2) from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist from freqtrade.util import FtPrecise @@ -2207,6 +2209,7 @@ class Exchange: @retrier_async async def get_market_leverage_tiers(self, symbol: str) -> Tuple[str, List[Dict]]: + """ Leverage tiers per symbol """ try: tier = await self._api_async.fetch_market_leverage_tiers(symbol) return symbol, tier @@ -2238,12 +2241,21 @@ class Exchange: tiers: Dict[str, List[Dict]] = {} - # Be verbose here, as this delays startup by ~1 minute. - logger.info( - f"Initializing leverage_tiers for {len(symbols)} markets. " - "This will take about a minute.") + tiers_cached = self.load_cached_leverage_tiers(self._config['stake_currency']) + if tiers_cached: + tiers = tiers_cached - coros = [self.get_market_leverage_tiers(symbol) for symbol in sorted(symbols)] + coros = [ + self.get_market_leverage_tiers(symbol) + for symbol in sorted(symbols) if symbol not in tiers] + + # Be verbose here, as this delays startup by ~1 minute. + if coros: + logger.info( + f"Initializing leverage_tiers for {len(symbols)} markets. " + "This will take about a minute.") + else: + logger.info("Using cached leverage_tiers.") async def gather_results(): return await asyncio.gather(*input_coro, return_exceptions=True) @@ -2255,7 +2267,8 @@ class Exchange: for symbol, res in results: tiers[symbol] = res - + if len(coros) > 0: + self.cache_leverage_tiers(tiers, self._config['stake_currency']) logger.info(f"Done initializing {len(symbols)} markets.") return tiers @@ -2264,6 +2277,30 @@ class Exchange: else: return {} + def cache_leverage_tiers(self, tiers: Dict[str, List[Dict]], stake_currency: str) -> None: + + filename = self._config['datadir'] / "futures" / f"leverage_tiers_{stake_currency}.json" + if not filename.parent.is_dir(): + filename.parent.mkdir(parents=True) + data = { + "updated": datetime.now(timezone.utc), + "data": tiers, + } + file_dump_json(filename, data) + + def load_cached_leverage_tiers(self, stake_currency: str) -> Optional[Dict[str, List[Dict]]]: + filename = self._config['datadir'] / "futures" / f"leverage_tiers_{stake_currency}.json" + if filename.is_file(): + tiers = file_load_json(filename) + updated = tiers.get('updated') + if updated: + updated_dt = parser.parse(updated) + if updated_dt < datetime.now(timezone.utc) - timedelta(days=1): + logger.info("Cached leverage tiers are outdated. Will update.") + return None + return tiers['data'] + return None + def fill_leverage_tiers(self) -> None: """ Assigns property _leverage_tiers to a dictionary of information about the leverage @@ -2377,7 +2414,8 @@ class Exchange: return try: - self._api.set_leverage(symbol=pair, leverage=leverage) + res = self._api.set_leverage(symbol=pair, leverage=leverage) + self._log_exchange_response('set_leverage', res) except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: @@ -2405,7 +2443,6 @@ class Exchange: if self.trading_mode in TradingMode.SPOT: return None elif ( - self.margin_mode == MarginMode.ISOLATED and self.trading_mode == TradingMode.FUTURES ): wallet_balance = (amount * open_rate) / leverage @@ -2421,7 +2458,7 @@ class Exchange: return isolated_liq else: raise OperationalException( - "Freqtrade only supports isolated futures for leverage trading") + "Freqtrade currently only supports futures for leverage trading.") def funding_fee_cutoff(self, open_date: datetime): """ @@ -2441,7 +2478,8 @@ class Exchange: return try: - self._api.set_margin_mode(margin_mode.value, pair, params) + res = self._api.set_margin_mode(margin_mode.value, pair, params) + self._log_exchange_response('set_margin_mode', res) except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: @@ -2599,7 +2637,7 @@ class Exchange: """ if self.trading_mode == TradingMode.SPOT: return None - elif (self.trading_mode != TradingMode.FUTURES and self.margin_mode != MarginMode.ISOLATED): + elif (self.trading_mode != TradingMode.FUTURES): raise OperationalException( f"{self.name} does not support {self.margin_mode.value} {self.trading_mode.value}") diff --git a/freqtrade/exchange/gateio.py b/freqtrade/exchange/gateio.py index 6df3425d2..c6ed0c66c 100644 --- a/freqtrade/exchange/gateio.py +++ b/freqtrade/exchange/gateio.py @@ -34,6 +34,7 @@ class Gateio(Exchange): _ft_has_futures: Dict = { "needs_trading_fees": True, + "ohlcv_volume_currency": "base", "fee_cost_in_contracts": False, # Set explicitly to false for clarity "order_props_in_contracts": ['amount', 'filled', 'remaining'], } diff --git a/freqtrade/freqai/data_kitchen.py b/freqtrade/freqai/data_kitchen.py index 85041515a..421b30bf5 100644 --- a/freqtrade/freqai/data_kitchen.py +++ b/freqtrade/freqai/data_kitchen.py @@ -511,7 +511,6 @@ class FreqaiDataKitchen: pairwise = pairwise.reshape(-1, 1) avg_mean_dist = pairwise[~np.isnan(pairwise)].mean() - return avg_mean_dist def use_SVM_to_remove_outliers(self, predict: bool) -> None: diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index a214efd76..4e3af64ea 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -418,7 +418,7 @@ class FreqtradeBot(LoggingMixin): whitelist = copy.deepcopy(self.active_pair_whitelist) if not whitelist: - logger.info("Active pair whitelist is empty.") + self.log_once("Active pair whitelist is empty.", logger.info) return trades_created # Remove pairs for currently opened trades from the whitelist for trade in Trade.get_open_trades(): @@ -427,8 +427,8 @@ class FreqtradeBot(LoggingMixin): logger.debug('Ignoring %s in pair whitelist', trade.pair) if not whitelist: - logger.info("No currency pair in active pair whitelist, " - "but checking to exit open trades.") + self.log_once("No currency pair in active pair whitelist, " + "but checking to exit open trades.", logger.info) return trades_created if PairLocks.is_global_lock(side='*'): # This only checks for total locks (both sides). diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 6528481d5..12536c333 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -24,6 +24,7 @@ from freqtrade.enums import (BacktestState, CandleType, ExitCheckTuple, ExitType TradingMode) from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds +from freqtrade.exchange.exchange import amount_to_precision from freqtrade.mixins import LoggingMixin from freqtrade.optimize.backtest_caching import get_strategy_run_id from freqtrade.optimize.bt_progress import BTProgress @@ -821,7 +822,15 @@ class Backtesting: if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount): self.order_id_counter += 1 base_currency = self.exchange.get_pair_base_currency(pair) - amount = round((stake_amount / propose_rate) * leverage, 8) + amount_p = (stake_amount / propose_rate) * leverage + amount = self.exchange._contracts_to_amount( + pair, amount_to_precision( + self.exchange._amount_to_contracts(pair, amount_p), + self.exchange.get_precision_amount(pair), self.precision_mode) + ) + # Backcalculate actual stake amount. + stake_amount = amount * propose_rate / leverage + is_short = (direction == 'short') # Necessary for Margin trading. Disabled until support is enabled. # interest_rate = self.exchange.get_interest_rate() diff --git a/freqtrade/persistence/migrations.py b/freqtrade/persistence/migrations.py index e54675f16..311554359 100644 --- a/freqtrade/persistence/migrations.py +++ b/freqtrade/persistence/migrations.py @@ -307,7 +307,9 @@ def check_migrate(engine, decl_base, previous_tables) -> None: # Migrates both trades and orders table! # if ('orders' not in previous_tables # or not has_column(cols_orders, 'stop_price')): + migrating = False if not has_column(cols_trades, 'precision_mode'): + migrating = True logger.info(f"Running database migration for trades - " f"backup: {table_back_name}, {order_table_bak_name}") migrate_trades_and_orders_table( @@ -315,6 +317,7 @@ def check_migrate(engine, decl_base, previous_tables) -> None: order_table_bak_name, cols_orders) if not has_column(cols_pairlocks, 'side'): + migrating = True logger.info(f"Running database migration for pairlocks - " f"backup: {pairlock_table_bak_name}") @@ -329,3 +332,6 @@ def check_migrate(engine, decl_base, previous_tables) -> None: set_sqlite_to_wal(engine) fix_old_dry_orders(engine) + + if migrating: + logger.info("Database migration finished.") diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index f0fa05343..7f851322e 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -53,7 +53,7 @@ def init_db(db_url: str) -> None: # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # Scoped sessions proxy requests to the appropriate thread-local session. # We should use the scoped_session object - not a seperately initialized version - Trade._session = scoped_session(sessionmaker(bind=engine, autoflush=True)) + Trade._session = scoped_session(sessionmaker(bind=engine, autoflush=False)) Trade.query = Trade._session.query_property() Order.query = Trade._session.query_property() PairLock.query = Trade._session.query_property() diff --git a/freqtrade/plugins/pairlist/PrecisionFilter.py b/freqtrade/plugins/pairlist/PrecisionFilter.py index 521f38635..dcd153d8e 100644 --- a/freqtrade/plugins/pairlist/PrecisionFilter.py +++ b/freqtrade/plugins/pairlist/PrecisionFilter.py @@ -51,6 +51,11 @@ class PrecisionFilter(IPairList): :param ticker: ticker dict as returned from ccxt.fetch_tickers() :return: True if the pair can stay, false if it should be removed """ + if ticker.get('last', None) is None: + self.log_once(f"Removed {ticker['symbol']} from whitelist, because " + "ticker['last'] is empty (Usually no trade in the last 24h).", + logger.info) + return False stop_price = ticker['last'] * self._stoploss # Adjust stop-prices to precision diff --git a/freqtrade/templates/strategy_analysis_example.ipynb b/freqtrade/templates/strategy_analysis_example.ipynb index a7430c225..77444a023 100644 --- a/freqtrade/templates/strategy_analysis_example.ipynb +++ b/freqtrade/templates/strategy_analysis_example.ipynb @@ -30,7 +30,7 @@ "\n", "# Initialize empty configuration object\n", "config = Configuration.from_files([])\n", - "# Optionally, use existing configuration file\n", + "# Optionally (recommended), use existing configuration file\n", "# config = Configuration.from_files([\"config.json\"])\n", "\n", "# Define some constants\n", @@ -38,7 +38,7 @@ "# Name of the strategy class\n", "config[\"strategy\"] = \"SampleStrategy\"\n", "# Location of the data\n", - "data_location = Path(config['user_data_dir'], 'data', 'binance')\n", + "data_location = config['datadir']\n", "# Pair to analyze - Only use one pair here\n", "pair = \"BTC/USDT\"" ] @@ -365,7 +365,7 @@ "metadata": { "file_extension": ".py", "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3.9.7 64-bit ('trade_397')", "language": "python", "name": "python3" }, @@ -379,7 +379,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.5" + "version": "3.9.7" }, "mimetype": "text/x-python", "name": "python", @@ -427,7 +427,12 @@ ], "window_display": false }, - "version": 3 + "version": 3, + "vscode": { + "interpreter": { + "hash": "675f32a300d6d26767470181ad0b11dd4676bcce7ed1dd2ffe2fbc370c95fc7c" + } + } }, "nbformat": 4, "nbformat_minor": 4 diff --git a/freqtrade/wallets.py b/freqtrade/wallets.py index 14e5a6743..41115c72e 100644 --- a/freqtrade/wallets.py +++ b/freqtrade/wallets.py @@ -148,7 +148,7 @@ class Wallets: # Position is not open ... continue size = self._exchange._contracts_to_amount(symbol, position['contracts']) - collateral = position['collateral'] + collateral = position['collateral'] or 0.0 leverage = position['leverage'] self._positions[symbol] = PositionWallet( symbol, position=size, diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index 9df6acf75..28515a28a 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -1430,6 +1430,27 @@ def test_start_list_data(testdatadir, capsys): assert "\n| XRP/USDT | 1h | futures |\n" in captured.out assert "\n| XRP/USDT | 1h, 8h | mark |\n" in captured.out + args = [ + "list-data", + "--data-format-ohlcv", + "json", + "--pairs", "XRP/ETH", + "--datadir", + str(testdatadir), + "--show-timerange", + ] + pargs = get_args(args) + pargs['config'] = None + start_list_data(pargs) + captured = capsys.readouterr() + assert "Found 2 pair / timeframe combinations." in captured.out + assert ("\n| Pair | Timeframe | Type | From | To |\n" + in captured.out) + assert "UNITTEST/BTC" not in captured.out + assert ( + "\n| XRP/ETH | 1m | spot | 2019-10-11 00:00:00 | 2019-10-13 11:19:00 |\n" + in captured.out) + @pytest.mark.usefixtures("init_persistence") def test_show_trades(mocker, fee, capsys, caplog): diff --git a/tests/exchange/test_ccxt_compat.py b/tests/exchange/test_ccxt_compat.py index 7bb52ccaf..c3a5fe17f 100644 --- a/tests/exchange/test_ccxt_compat.py +++ b/tests/exchange/test_ccxt_compat.py @@ -137,6 +137,10 @@ def exchange_futures(request, exchange_conf, class_mocker): 'freqtrade.exchange.binance.Binance.fill_leverage_tiers') class_mocker.patch('freqtrade.exchange.exchange.Exchange.fetch_trading_fees') class_mocker.patch('freqtrade.exchange.okx.Okx.additional_exchange_init') + class_mocker.patch('freqtrade.exchange.exchange.Exchange.load_cached_leverage_tiers', + return_value=None) + class_mocker.patch('freqtrade.exchange.exchange.Exchange.cache_leverage_tiers') + exchange = ExchangeResolver.load_exchange( request.param, exchange_conf, validate=True, load_leverage_tiers=True) diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 6ad4a72c6..ec259d703 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -4791,6 +4791,20 @@ def test_load_leverage_tiers(mocker, default_conf, leverage_tiers, exchange_name ) +@pytest.mark.asyncio +@pytest.mark.parametrize('exchange_name', EXCHANGES) +async def test_get_market_leverage_tiers(mocker, default_conf, exchange_name): + default_conf['exchange']['name'] = exchange_name + await async_ccxt_exception( + mocker, + default_conf, + MagicMock(), + "get_market_leverage_tiers", + "fetch_market_leverage_tiers", + symbol='BTC/USDT:USDT' + ) + + def test_parse_leverage_tier(mocker, default_conf): exchange = get_patched_exchange(mocker, default_conf) diff --git a/tests/exchange/test_okx.py b/tests/exchange/test_okx.py index 91c4a3368..10e087ced 100644 --- a/tests/exchange/test_okx.py +++ b/tests/exchange/test_okx.py @@ -1,4 +1,5 @@ from datetime import datetime, timedelta, timezone +from pathlib import Path from unittest.mock import MagicMock, PropertyMock import pytest @@ -6,7 +7,7 @@ import pytest from freqtrade.enums import MarginMode, TradingMode from freqtrade.enums.candletype import CandleType from freqtrade.exchange.exchange import timeframe_to_minutes -from tests.conftest import get_mock_coro, get_patched_exchange +from tests.conftest import get_mock_coro, get_patched_exchange, log_has from tests.exchange.test_exchange import ccxt_exceptionhandlers @@ -267,7 +268,10 @@ def test_additional_exchange_init_okx(default_conf, mocker): "additional_exchange_init", "fetch_accounts") -def test_load_leverage_tiers_okx(default_conf, mocker, markets): +def test_load_leverage_tiers_okx(default_conf, mocker, markets, tmpdir, caplog, time_machine): + + default_conf['datadir'] = Path(tmpdir) + # fd_mock = mocker.patch('freqtrade.exchange.exchange.file_dump_json') api_mock = MagicMock() type(api_mock).has = PropertyMock(return_value={ 'fetchLeverageTiers': False, @@ -455,3 +459,21 @@ def test_load_leverage_tiers_okx(default_conf, mocker, markets): }, ], } + filename = (default_conf['datadir'] / + f"futures/leverage_tiers_{default_conf['stake_currency']}.json") + assert filename.is_file() + + logmsg = 'Cached leverage tiers are outdated. Will update.' + assert not log_has(logmsg, caplog) + + api_mock.fetch_market_leverage_tiers.reset_mock() + + exchange.load_leverage_tiers() + assert not log_has(logmsg, caplog) + + api_mock.fetch_market_leverage_tiers.call_count == 0 + # 2 day passes ... + time_machine.move_to(datetime.now() + timedelta(days=2)) + exchange.load_leverage_tiers() + + assert log_has(logmsg, caplog) diff --git a/tests/optimize/test_backtesting.py b/tests/optimize/test_backtesting.py index 0b964c54a..98d18c156 100644 --- a/tests/optimize/test_backtesting.py +++ b/tests/optimize/test_backtesting.py @@ -559,7 +559,7 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None: default_conf_usdt['exchange']['pair_whitelist'] = ['.*'] backtesting = Backtesting(default_conf_usdt) backtesting._set_strategy(backtesting.strategylist[0]) - pair = 'UNITTEST/USDT:USDT' + pair = 'ETH/USDT:USDT' row = [ pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0), 0.001, # Open diff --git a/tests/optimize/test_backtesting_adjust_position.py b/tests/optimize/test_backtesting_adjust_position.py index 2bb7de574..f0829ea1e 100644 --- a/tests/optimize/test_backtesting_adjust_position.py +++ b/tests/optimize/test_backtesting_adjust_position.py @@ -18,6 +18,7 @@ from tests.conftest import patch_exchange def test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) -> None: default_conf['use_exit_signal'] = False 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.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')) patch_exchange(mocker) diff --git a/tests/plugins/test_pairlist.py b/tests/plugins/test_pairlist.py index 5974bee89..48a0f81cb 100644 --- a/tests/plugins/test_pairlist.py +++ b/tests/plugins/test_pairlist.py @@ -366,6 +366,9 @@ def test_VolumePairList_refresh_empty(mocker, markets_empty, whitelist_conf): ([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"}, {"method": "PrecisionFilter"}], "BTC", ['ETH/BTC', 'TKN/BTC', 'LTC/BTC', 'XRP/BTC']), + ([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"}, + {"method": "PrecisionFilter"}], + "USDT", ['ETH/USDT', 'NANO/USDT']), # PriceFilter and VolumePairList ([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"}, {"method": "PriceFilter", "low_price_ratio": 0.03}], diff --git a/tests/plugins/test_protections.py b/tests/plugins/test_protections.py index 8a5356b3e..acfe124a8 100644 --- a/tests/plugins/test_protections.py +++ b/tests/plugins/test_protections.py @@ -67,6 +67,8 @@ def generate_mock_trade(pair: str, fee: float, is_open: bool, trade.close(open_rate * (2 - profit_rate if is_short else profit_rate)) trade.exit_reason = exit_reason + Trade.query.session.add(trade) + Trade.commit() return trade @@ -125,33 +127,33 @@ def test_stoploss_guard(mocker, default_conf, fee, caplog, is_short): assert not log_has_re(message, caplog) caplog.clear() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=200, min_ago_close=30, is_short=is_short, - )) + ) assert not freqtrade.protections.global_stop() assert not log_has_re(message, caplog) caplog.clear() # This trade does not count, as it's closed too long ago - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'BCH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=250, min_ago_close=100, is_short=is_short, - )) + ) - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=240, min_ago_close=30, is_short=is_short, - )) + ) # 3 Trades closed - but the 2nd has been closed too long ago. assert not freqtrade.protections.global_stop() assert not log_has_re(message, caplog) caplog.clear() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'LTC/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=180, min_ago_close=30, is_short=is_short, - )) + ) assert freqtrade.protections.global_stop() assert log_has_re(message, caplog) @@ -186,25 +188,25 @@ def test_stoploss_guard_perpair(mocker, default_conf, fee, caplog, only_per_pair assert not log_has_re(message, caplog) caplog.clear() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( pair, fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=200, min_ago_close=30, profit_rate=0.9, is_short=is_short - )) + ) assert not freqtrade.protections.stop_per_pair(pair) assert not freqtrade.protections.global_stop() assert not log_has_re(message, caplog) caplog.clear() # This trade does not count, as it's closed too long ago - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( pair, fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=250, min_ago_close=100, profit_rate=0.9, is_short=is_short - )) + ) # Trade does not count for per pair stop as it's the wrong pair. - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=240, min_ago_close=30, profit_rate=0.9, is_short=is_short - )) + ) # 3 Trades closed - but the 2nd has been closed too long ago. assert not freqtrade.protections.stop_per_pair(pair) assert freqtrade.protections.global_stop() != only_per_pair @@ -216,10 +218,10 @@ def test_stoploss_guard_perpair(mocker, default_conf, fee, caplog, only_per_pair caplog.clear() # Trade does not count potentially, as it's in the wrong direction - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( pair, fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=150, min_ago_close=25, profit_rate=0.9, is_short=not is_short - )) + ) freqtrade.protections.stop_per_pair(pair) assert freqtrade.protections.global_stop() != only_per_pair assert PairLocks.is_pair_locked(pair, side=check_side) != (only_per_side and only_per_pair) @@ -231,10 +233,10 @@ def test_stoploss_guard_perpair(mocker, default_conf, fee, caplog, only_per_pair caplog.clear() # 2nd Trade that counts with correct pair - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( pair, fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=180, min_ago_close=30, profit_rate=0.9, is_short=is_short - )) + ) freqtrade.protections.stop_per_pair(pair) assert freqtrade.protections.global_stop() != only_per_pair @@ -259,20 +261,20 @@ def test_CooldownPeriod(mocker, default_conf, fee, caplog): assert not log_has_re(message, caplog) caplog.clear() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=200, min_ago_close=30, - )) + ) assert not freqtrade.protections.global_stop() assert freqtrade.protections.stop_per_pair('XRP/BTC') assert PairLocks.is_pair_locked('XRP/BTC') assert not PairLocks.is_global_lock() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value, min_ago_open=205, min_ago_close=35, - )) + ) assert not freqtrade.protections.global_stop() assert not PairLocks.is_pair_locked('ETH/BTC') @@ -300,10 +302,10 @@ def test_LowProfitPairs(mocker, default_conf, fee, caplog, only_per_side): assert not log_has_re(message, caplog) caplog.clear() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=800, min_ago_close=450, profit_rate=0.9, - )) + ) Trade.commit() # Not locked with 1 trade @@ -312,10 +314,10 @@ def test_LowProfitPairs(mocker, default_conf, fee, caplog, only_per_side): assert not PairLocks.is_pair_locked('XRP/BTC') assert not PairLocks.is_global_lock() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=200, min_ago_close=120, profit_rate=0.9, - )) + ) Trade.commit() # Not locked with 1 trade (first trade is outside of lookback_period) @@ -325,19 +327,19 @@ def test_LowProfitPairs(mocker, default_conf, fee, caplog, only_per_side): assert not PairLocks.is_global_lock() # Add positive trade - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value, min_ago_open=20, min_ago_close=10, profit_rate=1.15, is_short=True - )) + ) Trade.commit() assert freqtrade.protections.stop_per_pair('XRP/BTC') != only_per_side assert not PairLocks.is_pair_locked('XRP/BTC', side='*') assert PairLocks.is_pair_locked('XRP/BTC', side='long') == only_per_side - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=110, min_ago_close=21, profit_rate=0.8, - )) + ) Trade.commit() # Locks due to 2nd trade @@ -365,36 +367,38 @@ def test_MaxDrawdown(mocker, default_conf, fee, caplog): assert not freqtrade.protections.stop_per_pair('XRP/BTC') caplog.clear() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=1000, min_ago_close=900, profit_rate=1.1, - )) - Trade.query.session.add(generate_mock_trade( + ) + generate_mock_trade( 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=1000, min_ago_close=900, profit_rate=1.1, - )) - Trade.query.session.add(generate_mock_trade( + ) + generate_mock_trade( 'NEO/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=1000, min_ago_close=900, profit_rate=1.1, - )) + ) + Trade.commit() # No losing trade yet ... so max_drawdown will raise exception assert not freqtrade.protections.global_stop() assert not freqtrade.protections.stop_per_pair('XRP/BTC') - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=500, min_ago_close=400, profit_rate=0.9, - )) + ) # Not locked with one trade assert not freqtrade.protections.global_stop() assert not freqtrade.protections.stop_per_pair('XRP/BTC') assert not PairLocks.is_pair_locked('XRP/BTC') assert not PairLocks.is_global_lock() - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, min_ago_open=1200, min_ago_close=1100, profit_rate=0.5, - )) + ) + Trade.commit() # Not locked with 1 trade (2nd trade is outside of lookback_period) assert not freqtrade.protections.global_stop() @@ -404,20 +408,22 @@ def test_MaxDrawdown(mocker, default_conf, fee, caplog): assert not log_has_re(message, caplog) # Winning trade ... (should not lock, does not change drawdown!) - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value, min_ago_open=320, min_ago_close=410, profit_rate=1.5, - )) + ) + Trade.commit() assert not freqtrade.protections.global_stop() assert not PairLocks.is_global_lock() caplog.clear() # Add additional negative trade, causing a loss of > 15% - Trade.query.session.add(generate_mock_trade( + generate_mock_trade( 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value, min_ago_open=20, min_ago_close=10, profit_rate=0.8, - )) + ) + Trade.commit() assert not freqtrade.protections.stop_per_pair('XRP/BTC') # local lock not supported assert not PairLocks.is_pair_locked('XRP/BTC') diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index ace77a3b6..a1a16c039 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -677,6 +677,7 @@ def test_process_trade_no_whitelist_pair(default_conf_usdt, ticker_usdt, limit_b open_rate=0.001, exchange='binance', )) + Trade.commit() assert pair not in freqtrade.active_pair_whitelist freqtrade.process() @@ -2414,6 +2415,7 @@ def test_manage_open_orders_entry_usercustom( open_trade.orders[0].side = 'sell' if is_short else 'buy' open_trade.orders[0].ft_order_side = 'sell' if is_short else 'buy' Trade.query.session.add(open_trade) + Trade.commit() # Ensure default is to return empty (so not mocked yet) freqtrade.manage_open_orders() @@ -2472,6 +2474,7 @@ def test_manage_open_orders_entry( open_trade.is_short = is_short Trade.query.session.add(open_trade) + Trade.commit() freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False) freqtrade.strategy.adjust_entry_price = MagicMock(return_value=1234) @@ -2509,6 +2512,7 @@ def test_adjust_entry_cancel( open_trade.is_short = is_short Trade.query.session.add(open_trade) + Trade.commit() # Timeout to not interfere freqtrade.strategy.ft_check_timed_out = MagicMock(return_value=False) @@ -2549,6 +2553,7 @@ def test_adjust_entry_maintain_replace( open_trade.is_short = is_short Trade.query.session.add(open_trade) + Trade.commit() # Timeout to not interfere freqtrade.strategy.ft_check_timed_out = MagicMock(return_value=False) @@ -2601,6 +2606,7 @@ def test_check_handle_cancelled_buy( open_trade.orders = [] open_trade.is_short = is_short Trade.query.session.add(open_trade) + Trade.commit() # check it does cancel buy orders over the time limit freqtrade.manage_open_orders() @@ -2631,6 +2637,7 @@ def test_manage_open_orders_buy_exception( open_trade.is_short = is_short Trade.query.session.add(open_trade) + Trade.commit() # check it does cancel buy orders over the time limit freqtrade.manage_open_orders() @@ -2672,6 +2679,7 @@ def test_manage_open_orders_exit_usercustom( open_trade_usdt.is_open = False Trade.query.session.add(open_trade_usdt) + Trade.commit() # Ensure default is false freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 @@ -2754,6 +2762,7 @@ def test_manage_open_orders_exit( open_trade_usdt.is_short = is_short Trade.query.session.add(open_trade_usdt) + Trade.commit() freqtrade.strategy.check_exit_timeout = MagicMock(return_value=False) freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False) @@ -2794,6 +2803,7 @@ def test_check_handle_cancelled_exit( open_trade_usdt.is_short = is_short Trade.query.session.add(open_trade_usdt) + Trade.commit() # check it does cancel sell orders over the time limit freqtrade.manage_open_orders() @@ -2830,6 +2840,7 @@ def test_manage_open_orders_partial( freqtrade = FreqtradeBot(default_conf_usdt) prior_stake = open_trade.stake_amount Trade.query.session.add(open_trade) + Trade.commit() # check it does cancel buy orders over the time limit # note this is for a partially-complete buy order @@ -2874,6 +2885,7 @@ def test_manage_open_orders_partial_fee( open_trade.fee_open = fee() open_trade.fee_close = fee() Trade.query.session.add(open_trade) + Trade.commit() # cancelling a half-filled order should update the amount to the bought amount # and apply fees if necessary. freqtrade.manage_open_orders() @@ -2923,6 +2935,7 @@ def test_manage_open_orders_partial_except( open_trade.fee_open = fee() open_trade.fee_close = fee() Trade.query.session.add(open_trade) + Trade.commit() # cancelling a half-filled order should update the amount to the bought amount # and apply fees if necessary. freqtrade.manage_open_orders() @@ -2961,6 +2974,7 @@ def test_manage_open_orders_exception(default_conf_usdt, ticker_usdt, open_trade freqtrade = FreqtradeBot(default_conf_usdt) Trade.query.session.add(open_trade_usdt) + Trade.commit() caplog.clear() freqtrade.manage_open_orders() diff --git a/tests/test_persistence.py b/tests/test_persistence.py index f68791b72..50d0788ca 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -1387,6 +1387,7 @@ def test_migrate_new(mocker, default_conf, fee, caplog): assert log_has("trying trades_bak2", caplog) assert log_has("Running database migration for trades - backup: trades_bak2, orders_bak0", caplog) + assert log_has("Database migration finished.", caplog) assert pytest.approx(trade.open_trade_value) == trade._calc_open_trade_value( trade.amount, trade.open_rate) assert trade.close_profit_abs is None @@ -1885,6 +1886,7 @@ def test_stoploss_reinitialization(default_conf, fee): assert trade.initial_stop_loss == 0.95 assert trade.initial_stop_loss_pct == -0.05 Trade.query.session.add(trade) + Trade.commit() # Lower stoploss Trade.stoploss_reinitialization(0.06) @@ -1946,6 +1948,7 @@ def test_stoploss_reinitialization_leverage(default_conf, fee): assert trade.initial_stop_loss == 0.98 assert trade.initial_stop_loss_pct == -0.1 Trade.query.session.add(trade) + Trade.commit() # Lower stoploss Trade.stoploss_reinitialization(0.15) @@ -2007,6 +2010,7 @@ def test_stoploss_reinitialization_short(default_conf, fee): assert trade.initial_stop_loss == 1.02 assert trade.initial_stop_loss_pct == -0.1 Trade.query.session.add(trade) + Trade.commit() # Lower stoploss Trade.stoploss_reinitialization(-0.15) trades = Trade.get_open_trades()