Merge branch 'develop' into move_datadownload

This commit is contained in:
Matthias 2022-08-31 10:23:45 +00:00
commit a88ffd2c9d
101 changed files with 3154 additions and 1523 deletions

View File

@ -15,7 +15,7 @@ repos:
additional_dependencies: additional_dependencies:
- types-cachetools==5.2.1 - types-cachetools==5.2.1
- types-filelock==3.2.7 - types-filelock==3.2.7
- types-requests==2.28.8 - types-requests==2.28.9
- types-tabulate==0.8.11 - types-tabulate==0.8.11
- types-python-dateutil==2.8.19 - types-python-dateutil==2.8.19
# stages: [push] # stages: [push]

View File

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

View File

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

View File

@ -75,7 +75,6 @@
"weight_factor": 0.9, "weight_factor": 0.9,
"principal_component_analysis": false, "principal_component_analysis": false,
"use_SVM_to_remove_outliers": true, "use_SVM_to_remove_outliers": true,
"stratify_training_data": 0,
"indicator_max_period_candles": 20, "indicator_max_period_candles": 20,
"indicator_periods_candles": [10, 20] "indicator_periods_candles": [10, 20]
}, },

View File

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

BIN
docs/assets/freqai_DI.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 KiB

BIN
docs/assets/freqai_algo.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 995 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

View File

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

View File

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

View File

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

View File

@ -63,7 +63,7 @@ optional arguments:
`jsongz`). `jsongz`).
--trading-mode {spot,margin,futures} --trading-mode {spot,margin,futures}
Select Trading mode Select Trading mode
--prepend Allow data prepending. --prepend Allow data prepending. (Data-appending is disabled)
Common arguments: Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages). -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).
@ -186,7 +186,7 @@ Freqtrade currently supports 3 data-formats for both OHLCV and trades data:
By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data. By default, OHLCV data is stored as `json` data, while trades data is stored as `jsongz` data.
This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively. This can be changed via the `--data-format-ohlcv` and `--data-format-trades` command line arguments respectively.
To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time: To persist this change, you should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:
``` jsonc ``` jsonc
// ... // ...
@ -374,6 +374,7 @@ usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]
[--data-format-ohlcv {json,jsongz,hdf5}] [--data-format-ohlcv {json,jsongz,hdf5}]
[-p PAIRS [PAIRS ...]] [-p PAIRS [PAIRS ...]]
[--trading-mode {spot,margin,futures}] [--trading-mode {spot,margin,futures}]
[--show-timerange]
optional arguments: optional arguments:
-h, --help show this help message and exit -h, --help show this help message and exit
@ -387,6 +388,8 @@ optional arguments:
separated. separated.
--trading-mode {spot,margin,futures} --trading-mode {spot,margin,futures}
Select Trading mode Select Trading mode
--show-timerange Show timerange available for available data. (May take
a while to calculate).
Common arguments: Common arguments:
-v, --verbose Verbose mode (-vv for more, -vvv to get all messages). -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).

View File

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

View File

@ -278,7 +278,7 @@ For example, to test the order type `FOK` with Kraken, and modify candle limit t
"exchange": { "exchange": {
"name": "kraken", "name": "kraken",
"_ft_has_params": { "_ft_has_params": {
"order_time_in_force": ["gtc", "fok"], "order_time_in_force": ["GTC", "FOK"],
"ohlcv_candle_limit": 200 "ohlcv_candle_limit": 200
} }
//... //...

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -163,6 +163,8 @@ python3 scripts/rest_client.py --config rest_config.json <command> [optional par
| `strategy <strategy>` | Get specific Strategy content. **Alpha** | `strategy <strategy>` | Get specific Strategy content. **Alpha**
| `available_pairs` | List available backtest data. **Alpha** | `available_pairs` | List available backtest data. **Alpha**
| `version` | Show version. | `version` | Show version.
| `sysinfo` | Show informations about the system load.
| `health` | Show bot health (last bot loop).
!!! Warning "Alpha status" !!! Warning "Alpha status"
Endpoints labeled with *Alpha status* above may change at any time without notice. Endpoints labeled with *Alpha status* above may change at any time without notice.
@ -227,6 +229,11 @@ forceexit
Force-exit a trade. Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command) :param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
health
Provides a quick health check of the running bot.
locks locks
Return current locks Return current locks
@ -312,12 +319,13 @@ version
whitelist whitelist
Show the current whitelist. Show the current whitelist.
``` ```
### OpenAPI interface ### OpenAPI interface
To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration. To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration.
This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings. This will enable the Swagger UI at the `/docs` endpoint. By default, that's running at http://localhost:8080/docs - but it'll depend on your settings.
### Advanced API usage using JWT tokens ### Advanced API usage using JWT tokens

View File

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

View File

@ -14,7 +14,7 @@ from freqtrade.configuration import Configuration
# Initialize empty configuration object # Initialize empty configuration object
config = Configuration.from_files([]) config = Configuration.from_files([])
# Optionally, use existing configuration file # Optionally (recommended), use existing configuration file
# config = Configuration.from_files(["config.json"]) # config = Configuration.from_files(["config.json"])
# Define some constants # Define some constants
@ -22,7 +22,7 @@ config["timeframe"] = "5m"
# Name of the strategy class # Name of the strategy class
config["strategy"] = "SampleStrategy" config["strategy"] = "SampleStrategy"
# Location of the data # 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 to analyze - Only use one pair here
pair = "BTC/USDT" pair = "BTC/USDT"
``` ```

View File

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

View File

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

View File

@ -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 ## Show previous Backtest results
Allows you to show previous backtest results. Allows you to show previous backtest results.

View File

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

View File

@ -34,7 +34,7 @@ ARGS_HYPEROPT = ARGS_COMMON_OPTIMIZE + ["hyperopt", "hyperopt_path",
"print_colorized", "print_json", "hyperopt_jobs", "print_colorized", "print_json", "hyperopt_jobs",
"hyperopt_random_state", "hyperopt_min_trades", "hyperopt_random_state", "hyperopt_min_trades",
"hyperopt_loss", "disableparamexport", "hyperopt_loss", "disableparamexport",
"hyperopt_ignore_missing_space"] "hyperopt_ignore_missing_space", "analyze_per_epoch"]
ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"] ARGS_EDGE = ARGS_COMMON_OPTIMIZE + ["stoploss_range"]
@ -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_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", ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "new_pairs_days", "include_inactive",
"timerange", "download_trades", "exchange", "timeframes", "timerange", "download_trades", "exchange", "timeframes",

View File

@ -255,6 +255,13 @@ AVAILABLE_CLI_OPTIONS = {
nargs='+', nargs='+',
default='default', default='default',
), ),
"analyze_per_epoch": Arg(
'--analyze-per-epoch',
help='Run populate_indicators once per epoch.',
action='store_true',
default=False,
),
"print_all": Arg( "print_all": Arg(
'--print-all', '--print-all',
help='Print all results, not only the best ones.', help='Print all results, not only the best ones.',
@ -367,7 +374,7 @@ AVAILABLE_CLI_OPTIONS = {
metavar='BASE_CURRENCY', metavar='BASE_CURRENCY',
), ),
"trading_mode": Arg( "trading_mode": Arg(
'--trading-mode', '--trading-mode', '--tradingmode',
help='Select Trading mode', help='Select Trading mode',
choices=constants.TRADING_MODES, choices=constants.TRADING_MODES,
), ),
@ -434,6 +441,11 @@ AVAILABLE_CLI_OPTIONS = {
help='Storage format for downloaded trades data. (default: `jsongz`).', help='Storage format for downloaded trades data. (default: `jsongz`).',
choices=constants.AVAILABLE_DATAHANDLERS, 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": Arg(
'--exchange', '--exchange',
help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). ' help=f'Exchange name (default: `{constants.DEFAULT_EXCHANGE}`). '
@ -450,7 +462,7 @@ AVAILABLE_CLI_OPTIONS = {
), ),
"prepend_data": Arg( "prepend_data": Arg(
'--prepend', '--prepend',
help='Allow data prepending.', help='Allow data prepending. (Data-appending is disabled)',
action='store_true', action='store_true',
), ),
"erase": Arg( "erase": Arg(

View File

@ -5,13 +5,13 @@ from datetime import datetime, timedelta
from typing import Any, Dict, List from typing import Any, Dict, List
from freqtrade.configuration import TimeRange, setup_utils_configuration 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.converter import convert_ohlcv_format, convert_trades_format
from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data, from freqtrade.data.history import (convert_trades_to_ohlcv, refresh_backtest_ohlcv_data,
refresh_backtest_trades_data) refresh_backtest_trades_data)
from freqtrade.enums import CandleType, RunMode, TradingMode from freqtrade.enums import CandleType, RunMode, TradingMode
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import market_is_active, timeframe_to_minutes
from freqtrade.exchange.exchange import market_is_active
from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist, expand_pairlist
from freqtrade.resolvers import ExchangeResolver from freqtrade.resolvers import ExchangeResolver
@ -80,7 +80,7 @@ def start_download_data(args: Dict[str, Any]) -> None:
data_format_trades=config['dataformat_trades'], data_format_trades=config['dataformat_trades'],
) )
else: else:
if not exchange._ft_has.get('ohlcv_has_history', True): if not exchange.get_option('ohlcv_has_history', True):
raise OperationalException( raise OperationalException(
f"Historic klines not available for {exchange.name}. " f"Historic klines not available for {exchange.name}. "
"Please use `--dl-trades` instead for this exchange " "Please use `--dl-trades` instead for this exchange "
@ -177,17 +177,31 @@ def start_list_data(args: Dict[str, Any]) -> None:
paircombs = [comb for comb in paircombs if comb[0] in args['pairs']] paircombs = [comb for comb in paircombs if comb[0] in args['pairs']]
print(f"Found {len(paircombs)} pair / timeframe combinations.") print(f"Found {len(paircombs)} pair / timeframe combinations.")
groupedpair = defaultdict(list) if not config.get('show_timerange'):
for pair, timeframe, candle_type in sorted( groupedpair = defaultdict(list)
paircombs, for pair, timeframe, candle_type in sorted(
key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2]) paircombs,
): key=lambda x: (x[0], timeframe_to_minutes(x[1]), x[2])
groupedpair[(pair, candle_type)].append(timeframe) ):
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([ print(tabulate([
(pair, ', '.join(timeframes), candle_type) (pair, timeframe, candle_type,
for (pair, candle_type), timeframes in groupedpair.items() start.strftime(DATETIME_PRINT_FORMAT),
], end.strftime(DATETIME_PRINT_FORMAT))
headers=("Pair", "Timeframe", "Type"), for pair, timeframe, candle_type, start, end in paircombs1
],
headers=("Pair", "Timeframe", "Type", 'From', 'To'),
tablefmt='psql', stralign='right')) tablefmt='psql', stralign='right'))

View File

@ -302,6 +302,9 @@ class Configuration:
self._args_to_config(config, argname='spaces', self._args_to_config(config, argname='spaces',
logstring='Parameter -s/--spaces detected: {}') logstring='Parameter -s/--spaces detected: {}')
self._args_to_config(config, argname='analyze_per_epoch',
logstring='Parameter --analyze-per-epoch detected.')
self._args_to_config(config, argname='print_all', self._args_to_config(config, argname='print_all',
logstring='Parameter --print-all detected ...') logstring='Parameter --print-all detected ...')
@ -426,6 +429,9 @@ class Configuration:
self._args_to_config(config, argname='dataformat_trades', self._args_to_config(config, argname='dataformat_trades',
logstring='Using "{}" to store trades data.') 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: def _process_data_options(self, config: Dict[str, Any]) -> None:
self._args_to_config(config, argname='new_pairs_days', self._args_to_config(config, argname='new_pairs_days',
logstring='Detected --new-pairs-days: {}') logstring='Detected --new-pairs-days: {}')

View File

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

View File

@ -7,9 +7,8 @@ import numpy as np
import pandas as pd import pandas as pd
from freqtrade.configuration import TimeRange from freqtrade.configuration import TimeRange
from freqtrade.constants import (DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList
ListPairsWithTimeframes, TradeList) from freqtrade.enums import CandleType
from freqtrade.enums import CandleType, TradingMode
from .idatahandler import IDataHandler from .idatahandler import IDataHandler
@ -21,29 +20,6 @@ class HDF5DataHandler(IDataHandler):
_columns = DEFAULT_DATAFRAME_COLUMNS _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 @classmethod
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]: def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
""" """

View File

@ -56,7 +56,7 @@ def load_pair_history(pair: str,
fill_missing=fill_up_missing, fill_missing=fill_up_missing,
drop_incomplete=drop_incomplete, drop_incomplete=drop_incomplete,
startup_candles=startup_candles, 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, fill_up_missing=fill_up_missing,
startup_candles=startup_candles, startup_candles=startup_candles,
data_handler=data_handler, data_handler=data_handler,
candle_type=candle_type candle_type=candle_type,
) )
if not hist.empty: if not hist.empty:
result[pair] = hist result[pair] = hist
else: else:
if candle_type is CandleType.FUNDING_RATE and user_futures_funding_rate is not None: 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}]") 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: if fail_without_data and not result:
raise OperationalException("No data found. Terminating.") raise OperationalException("No data found. Terminating.")
@ -301,8 +302,8 @@ def refresh_backtest_ohlcv_data(exchange: Exchange, pairs: List[str], timeframes
if trading_mode == 'futures': if trading_mode == 'futures':
# Predefined candletype (and timeframe) depending on exchange # Predefined candletype (and timeframe) depending on exchange
# Downloads what is necessary to backtest based on futures data. # Downloads what is necessary to backtest based on futures data.
tf_mark = exchange._ft_has['mark_ohlcv_timeframe'] tf_mark = exchange.get_option('mark_ohlcv_timeframe')
fr_candle_type = CandleType.from_string(exchange._ft_has['mark_ohlcv_price']) fr_candle_type = CandleType.from_string(exchange.get_option('mark_ohlcv_price'))
# All exchanges need FundingRate for futures trading. # All exchanges need FundingRate for futures trading.
# The timeframe is aligned to the mark-price timeframe. # The timeframe is aligned to the mark-price timeframe.
for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type): for funding_candle_type in (CandleType.FUNDING_RATE, fr_candle_type):
@ -329,13 +330,12 @@ def _download_trades_history(exchange: Exchange,
try: try:
until = None until = None
since = 0
if timerange: if timerange:
if timerange.starttype == 'date': if timerange.starttype == 'date':
since = timerange.startts * 1000 since = timerange.startts * 1000
if timerange.stoptype == 'date': if timerange.stoptype == 'date':
until = timerange.stopts * 1000 until = timerange.stopts * 1000
else:
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
trades = data_handler.trades_load(pair) trades = data_handler.trades_load(pair)
@ -348,6 +348,9 @@ def _download_trades_history(exchange: Exchange,
logger.info(f"Start earlier than available data. Redownloading trades for {pair}...") logger.info(f"Start earlier than available data. Redownloading trades for {pair}...")
trades = [] trades = []
if not since:
since = arrow.utcnow().shift(days=-new_pairs_days).int_timestamp * 1000
from_id = trades[-1][1] if trades else None from_id = trades[-1][1] if trades else None
if trades and since < trades[-1][0]: if trades and since < trades[-1][0]:
# Reset since to the last available point # Reset since to the last available point

View File

@ -9,7 +9,7 @@ from abc import ABC, abstractmethod
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import List, Optional, Type from typing import List, Optional, Tuple, Type
from pandas import DataFrame from pandas import DataFrame
@ -39,15 +39,26 @@ class IDataHandler(ABC):
raise NotImplementedError() raise NotImplementedError()
@classmethod @classmethod
@abstractmethod
def ohlcv_get_available_data( def ohlcv_get_available_data(
cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes: cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes:
""" """
Returns a list of all pairs with ohlcv data available in this datadir Returns a list of all pairs with ohlcv data available in this datadir
:param datadir: Directory to search for ohlcv files :param datadir: Directory to search for ohlcv files
:param trading_mode: trading-mode to be used :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 @classmethod
@abstractmethod @abstractmethod
@ -73,6 +84,18 @@ class IDataHandler(ABC):
:return: None :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 @abstractmethod
def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange], def _ohlcv_load(self, pair: str, timeframe: str, timerange: Optional[TimeRange],
candle_type: CandleType candle_type: CandleType

View File

@ -8,9 +8,9 @@ from pandas import DataFrame, read_json, to_datetime
from freqtrade import misc from freqtrade import misc
from freqtrade.configuration import TimeRange 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.data.converter import trades_dict_to_list
from freqtrade.enums import CandleType, TradingMode from freqtrade.enums import CandleType
from .idatahandler import IDataHandler from .idatahandler import IDataHandler
@ -23,28 +23,6 @@ class JsonDataHandler(IDataHandler):
_use_zip = False _use_zip = False
_columns = DEFAULT_DATAFRAME_COLUMNS _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 @classmethod
def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]: def ohlcv_get_pairs(cls, datadir: Path, timeframe: str, candle_type: CandleType) -> List[str]:
""" """

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -17,6 +17,7 @@ import ccxt
import ccxt.async_support as ccxt_async import ccxt.async_support as ccxt_async
from cachetools import TTLCache from cachetools import TTLCache
from ccxt import ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE, decimal_to_precision from ccxt import ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE, decimal_to_precision
from dateutil import parser
from pandas import DataFrame from pandas import DataFrame
from freqtrade.constants import (DEFAULT_AMOUNT_RESERVE_PERCENT, NON_OPEN_EXCHANGE_STATES, BuySell, 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, EXCHANGE_HAS_OPTIONAL, EXCHANGE_HAS_REQUIRED,
SUPPORTED_EXCHANGES, remove_credentials, retrier, SUPPORTED_EXCHANGES, remove_credentials, retrier,
retrier_async) 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.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.util import FtPrecise from freqtrade.util import FtPrecise
@ -52,15 +54,15 @@ class Exchange:
# Parameters to add directly to buy/sell calls (like agreeing to trading agreement) # Parameters to add directly to buy/sell calls (like agreeing to trading agreement)
_params: Dict = {} _params: Dict = {}
# Additional headers - added to the ccxt object # Additional parameters - added to the ccxt object
_headers: Dict = {} _ccxt_params: Dict = {}
# Dict to specify which options each exchange implements # Dict to specify which options each exchange implements
# This defines defaults, which can be selectively overridden by subclasses using _ft_has # This defines defaults, which can be selectively overridden by subclasses using _ft_has
# or by specifying them in the configuration. # or by specifying them in the configuration.
_ft_has_default: Dict = { _ft_has_default: Dict = {
"stoploss_on_exchange": False, "stoploss_on_exchange": False,
"order_time_in_force": ["gtc"], "order_time_in_force": ["GTC"],
"time_in_force_parameter": "timeInForce", "time_in_force_parameter": "timeInForce",
"ohlcv_params": {}, "ohlcv_params": {},
"ohlcv_candle_limit": 500, "ohlcv_candle_limit": 500,
@ -240,9 +242,9 @@ class Exchange:
} }
if ccxt_kwargs: if ccxt_kwargs:
logger.info('Applying additional ccxt config: %s', ccxt_kwargs) logger.info('Applying additional ccxt config: %s', ccxt_kwargs)
if self._headers: if self._ccxt_params:
# Inject static headers after the above output to not confuse users. # Inject static options after the above output to not confuse users.
ccxt_kwargs = deep_merge_dicts({'headers': self._headers}, ccxt_kwargs) ccxt_kwargs = deep_merge_dicts(self._ccxt_params, ccxt_kwargs)
if ccxt_kwargs: if ccxt_kwargs:
ex_config.update(ccxt_kwargs) ex_config.update(ccxt_kwargs)
try: try:
@ -406,7 +408,7 @@ class Exchange:
else: else:
return DataFrame() return DataFrame()
def _get_contract_size(self, pair: str) -> float: def get_contract_size(self, pair: str) -> float:
if self.trading_mode == TradingMode.FUTURES: if self.trading_mode == TradingMode.FUTURES:
market = self.markets[pair] market = self.markets[pair]
contract_size: float = 1.0 contract_size: float = 1.0
@ -419,7 +421,7 @@ class Exchange:
def _trades_contracts_to_amount(self, trades: List) -> List: def _trades_contracts_to_amount(self, trades: List) -> List:
if len(trades) > 0 and 'symbol' in trades[0]: if len(trades) > 0 and 'symbol' in trades[0]:
contract_size = self._get_contract_size(trades[0]['symbol']) contract_size = self.get_contract_size(trades[0]['symbol'])
if contract_size != 1: if contract_size != 1:
for trade in trades: for trade in trades:
trade['amount'] = trade['amount'] * contract_size trade['amount'] = trade['amount'] * contract_size
@ -427,7 +429,7 @@ class Exchange:
def _order_contracts_to_amount(self, order: Dict) -> Dict: def _order_contracts_to_amount(self, order: Dict) -> Dict:
if 'symbol' in order and order['symbol'] is not None: if 'symbol' in order and order['symbol'] is not None:
contract_size = self._get_contract_size(order['symbol']) contract_size = self.get_contract_size(order['symbol'])
if contract_size != 1: if contract_size != 1:
for prop in self._ft_has.get('order_props_in_contracts', []): for prop in self._ft_has.get('order_props_in_contracts', []):
if prop in order and order[prop] is not None: if prop in order and order[prop] is not None:
@ -436,19 +438,13 @@ class Exchange:
def _amount_to_contracts(self, pair: str, amount: float) -> float: def _amount_to_contracts(self, pair: str, amount: float) -> float:
contract_size = self._get_contract_size(pair) contract_size = self.get_contract_size(pair)
if contract_size and contract_size != 1: return amount_to_contracts(amount, contract_size)
return amount / contract_size
else:
return amount
def _contracts_to_amount(self, pair: str, num_contracts: float) -> float: def _contracts_to_amount(self, pair: str, num_contracts: float) -> float:
contract_size = self._get_contract_size(pair) contract_size = self.get_contract_size(pair)
if contract_size and contract_size != 1: return contracts_to_amount(num_contracts, contract_size)
return num_contracts * contract_size
else:
return num_contracts
def set_sandbox(self, api: ccxt.Exchange, exchange_config: dict, name: str) -> None: def set_sandbox(self, api: ccxt.Exchange, exchange_config: dict, name: str) -> None:
if exchange_config.get('sandbox'): if exchange_config.get('sandbox'):
@ -615,7 +611,7 @@ class Exchange:
""" """
Checks if order time in force configured in strategy/config are supported Checks if order time in force configured in strategy/config are supported
""" """
if any(v not in self._ft_has["order_time_in_force"] if any(v.upper() not in self._ft_has["order_time_in_force"]
for k, v in order_time_in_force.items()): for k, v in order_time_in_force.items()):
raise OperationalException( raise OperationalException(
f'Time in force policies are not supported for {self.name} yet.') f'Time in force policies are not supported for {self.name} yet.')
@ -672,6 +668,12 @@ class Exchange:
f"Freqtrade does not support {mm_value} {trading_mode.value} on {self.name}" f"Freqtrade does not support {mm_value} {trading_mode.value} on {self.name}"
) )
def get_option(self, param: str, default: Any = None) -> Any:
"""
Get parameter value from _ft_has
"""
return self._ft_has.get(param, default)
def exchange_has(self, endpoint: str) -> bool: def exchange_has(self, endpoint: str) -> bool:
""" """
Checks if exchange implements a specific API endpoint. Checks if exchange implements a specific API endpoint.
@ -987,12 +989,12 @@ class Exchange:
ordertype: str, ordertype: str,
leverage: float, leverage: float,
reduceOnly: bool, reduceOnly: bool,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
params = self._params.copy() params = self._params.copy()
if time_in_force != 'gtc' and ordertype != 'market': if time_in_force != 'GTC' and ordertype != 'market':
param = self._ft_has.get('time_in_force_parameter', '') param = self._ft_has.get('time_in_force_parameter', '')
params.update({param: time_in_force}) params.update({param: time_in_force.upper()})
if reduceOnly: if reduceOnly:
params.update({'reduceOnly': True}) params.update({'reduceOnly': True})
return params return params
@ -1007,7 +1009,7 @@ class Exchange:
rate: float, rate: float,
leverage: float, leverage: float,
reduceOnly: bool = False, reduceOnly: bool = False,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
if self._config['dry_run']: if self._config['dry_run']:
dry_order = self.create_dry_run_order( dry_order = self.create_dry_run_order(
@ -2207,6 +2209,7 @@ class Exchange:
@retrier_async @retrier_async
async def get_market_leverage_tiers(self, symbol: str) -> Tuple[str, List[Dict]]: async def get_market_leverage_tiers(self, symbol: str) -> Tuple[str, List[Dict]]:
""" Leverage tiers per symbol """
try: try:
tier = await self._api_async.fetch_market_leverage_tiers(symbol) tier = await self._api_async.fetch_market_leverage_tiers(symbol)
return symbol, tier return symbol, tier
@ -2238,12 +2241,21 @@ class Exchange:
tiers: Dict[str, List[Dict]] = {} tiers: Dict[str, List[Dict]] = {}
# Be verbose here, as this delays startup by ~1 minute. tiers_cached = self.load_cached_leverage_tiers(self._config['stake_currency'])
logger.info( if tiers_cached:
f"Initializing leverage_tiers for {len(symbols)} markets. " tiers = tiers_cached
"This will take about a minute.")
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(): async def gather_results():
return await asyncio.gather(*input_coro, return_exceptions=True) return await asyncio.gather(*input_coro, return_exceptions=True)
@ -2255,7 +2267,8 @@ class Exchange:
for symbol, res in results: for symbol, res in results:
tiers[symbol] = res tiers[symbol] = res
if len(coros) > 0:
self.cache_leverage_tiers(tiers, self._config['stake_currency'])
logger.info(f"Done initializing {len(symbols)} markets.") logger.info(f"Done initializing {len(symbols)} markets.")
return tiers return tiers
@ -2264,6 +2277,30 @@ class Exchange:
else: else:
return {} 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: def fill_leverage_tiers(self) -> None:
""" """
Assigns property _leverage_tiers to a dictionary of information about the leverage Assigns property _leverage_tiers to a dictionary of information about the leverage
@ -2279,10 +2316,10 @@ class Exchange:
def parse_leverage_tier(self, tier) -> Dict: def parse_leverage_tier(self, tier) -> Dict:
info = tier.get('info', {}) info = tier.get('info', {})
return { return {
'min': tier['minNotional'], 'minNotional': tier['minNotional'],
'max': tier['maxNotional'], 'maxNotional': tier['maxNotional'],
'mmr': tier['maintenanceMarginRate'], 'maintenanceMarginRate': tier['maintenanceMarginRate'],
'lev': tier['maxLeverage'], 'maxLeverage': tier['maxLeverage'],
'maintAmt': float(info['cum']) if 'cum' in info else None, 'maintAmt': float(info['cum']) if 'cum' in info else None,
} }
@ -2311,18 +2348,18 @@ class Exchange:
pair_tiers = self._leverage_tiers[pair] pair_tiers = self._leverage_tiers[pair]
if stake_amount == 0: if stake_amount == 0:
return self._leverage_tiers[pair][0]['lev'] # Max lev for lowest amount return self._leverage_tiers[pair][0]['maxLeverage'] # Max lev for lowest amount
for tier_index in range(len(pair_tiers)): for tier_index in range(len(pair_tiers)):
tier = pair_tiers[tier_index] tier = pair_tiers[tier_index]
lev = tier['lev'] lev = tier['maxLeverage']
if tier_index < len(pair_tiers) - 1: if tier_index < len(pair_tiers) - 1:
next_tier = pair_tiers[tier_index + 1] next_tier = pair_tiers[tier_index + 1]
next_floor = next_tier['min'] / next_tier['lev'] next_floor = next_tier['minNotional'] / next_tier['maxLeverage']
if next_floor > stake_amount: # Next tier min too high for stake amount if next_floor > stake_amount: # Next tier min too high for stake amount
return min((tier['max'] / stake_amount), lev) return min((tier['maxNotional'] / stake_amount), lev)
# #
# With the two leverage tiers below, # With the two leverage tiers below,
# - a stake amount of 150 would mean a max leverage of (10000 / 150) = 66.66 # - a stake amount of 150 would mean a max leverage of (10000 / 150) = 66.66
@ -2343,10 +2380,11 @@ class Exchange:
# #
else: # if on the last tier else: # if on the last tier
if stake_amount > tier['max']: # If stake is > than max tradeable amount if stake_amount > tier['maxNotional']:
# If stake is > than max tradeable amount
raise InvalidOrderException(f'Amount {stake_amount} too high for {pair}') raise InvalidOrderException(f'Amount {stake_amount} too high for {pair}')
else: else:
return tier['lev'] return tier['maxLeverage']
raise OperationalException( raise OperationalException(
'Looped through all tiers without finding a max leverage. Should never be reached' 'Looped through all tiers without finding a max leverage. Should never be reached'
@ -2377,7 +2415,8 @@ class Exchange:
return return
try: 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: except ccxt.DDoSProtection as e:
raise DDosProtection(e) from e raise DDosProtection(e) from e
except (ccxt.NetworkError, ccxt.ExchangeError) as e: except (ccxt.NetworkError, ccxt.ExchangeError) as e:
@ -2393,36 +2432,6 @@ class Exchange:
""" """
return 0.0 return 0.0
def get_liquidation_price(
self,
pair: str,
open_rate: float,
amount: float, # quote currency, includes leverage
leverage: float,
is_short: bool
) -> Optional[float]:
if self.trading_mode in TradingMode.SPOT:
return None
elif (
self.margin_mode == MarginMode.ISOLATED and
self.trading_mode == TradingMode.FUTURES
):
wallet_balance = (amount * open_rate) / leverage
isolated_liq = self.get_or_calculate_liquidation_price(
pair=pair,
open_rate=open_rate,
is_short=is_short,
position=amount,
wallet_balance=wallet_balance,
mm_ex_1=0.0,
upnl_ex_1=0.0,
)
return isolated_liq
else:
raise OperationalException(
"Freqtrade only supports isolated futures for leverage trading")
def funding_fee_cutoff(self, open_date: datetime): def funding_fee_cutoff(self, open_date: datetime):
""" """
:param open_date: The open date for a trade :param open_date: The open date for a trade
@ -2441,7 +2450,8 @@ class Exchange:
return return
try: 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: except ccxt.DDoSProtection as e:
raise DDosProtection(e) from e raise DDosProtection(e) from e
except (ccxt.NetworkError, ccxt.ExchangeError) as e: except (ccxt.NetworkError, ccxt.ExchangeError) as e:
@ -2582,34 +2592,36 @@ class Exchange:
else: else:
return 0.0 return 0.0
def get_or_calculate_liquidation_price( def get_liquidation_price(
self, self,
pair: str, pair: str,
# Dry-run # Dry-run
open_rate: float, # Entry price of position open_rate: float, # Entry price of position
is_short: bool, is_short: bool,
position: float, # Absolute value of position size amount: float, # Absolute value of position size
wallet_balance: float, # Or margin balance stake_amount: float,
wallet_balance: float = 0.0,
mm_ex_1: float = 0.0, # (Binance) Cross only mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]: ) -> Optional[float]:
""" """
Set's the margin mode on the exchange to cross or isolated for a specific pair Set's the margin mode on the exchange to cross or isolated for a specific pair
:param pair: base/quote currency pair (e.g. "ADA/USDT")
""" """
if self.trading_mode == TradingMode.SPOT: if self.trading_mode == TradingMode.SPOT:
return None return None
elif (self.trading_mode != TradingMode.FUTURES and self.margin_mode != MarginMode.ISOLATED): elif (self.trading_mode != TradingMode.FUTURES):
raise OperationalException( raise OperationalException(
f"{self.name} does not support {self.margin_mode.value} {self.trading_mode.value}") f"{self.name} does not support {self.margin_mode} {self.trading_mode}")
isolated_liq = None
if self._config['dry_run'] or not self.exchange_has("fetchPositions"): if self._config['dry_run'] or not self.exchange_has("fetchPositions"):
isolated_liq = self.dry_run_liquidation_price( isolated_liq = self.dry_run_liquidation_price(
pair=pair, pair=pair,
open_rate=open_rate, open_rate=open_rate,
is_short=is_short, is_short=is_short,
position=position, amount=amount,
stake_amount=stake_amount,
wallet_balance=wallet_balance, wallet_balance=wallet_balance,
mm_ex_1=mm_ex_1, mm_ex_1=mm_ex_1,
upnl_ex_1=upnl_ex_1 upnl_ex_1=upnl_ex_1
@ -2619,8 +2631,6 @@ class Exchange:
if len(positions) > 0: if len(positions) > 0:
pos = positions[0] pos = positions[0]
isolated_liq = pos['liquidationPrice'] isolated_liq = pos['liquidationPrice']
else:
return None
if isolated_liq: if isolated_liq:
buffer_amount = abs(open_rate - isolated_liq) * self.liquidation_buffer buffer_amount = abs(open_rate - isolated_liq) * self.liquidation_buffer
@ -2638,22 +2648,24 @@ class Exchange:
pair: str, pair: str,
open_rate: float, # Entry price of position open_rate: float, # Entry price of position
is_short: bool, is_short: bool,
position: float, # Absolute value of position size amount: float,
stake_amount: float,
wallet_balance: float, # Or margin balance wallet_balance: float, # Or margin balance
mm_ex_1: float = 0.0, # (Binance) Cross only mm_ex_1: float = 0.0, # (Binance) Cross only
upnl_ex_1: float = 0.0, # (Binance) Cross only upnl_ex_1: float = 0.0, # (Binance) Cross only
) -> Optional[float]: ) -> Optional[float]:
""" """
Important: Must be fetching data from cached values as this is used by backtesting!
PERPETUAL: PERPETUAL:
gateio: https://www.gate.io/help/futures/perpetual/22160/calculation-of-liquidation-price gateio: https://www.gate.io/help/futures/perpetual/22160/calculation-of-liquidation-price
okex: https://www.okex.com/support/hc/en-us/articles/ okex: https://www.okex.com/support/hc/en-us/articles/
360053909592-VI-Introduction-to-the-isolated-mode-of-Single-Multi-currency-Portfolio-margin 360053909592-VI-Introduction-to-the-isolated-mode-of-Single-Multi-currency-Portfolio-margin
Important: Must be fetching data from cached values as this is used by backtesting!
:param exchange_name: :param exchange_name:
:param open_rate: Entry price of position :param open_rate: Entry price of position
:param is_short: True if the trade is a short, false otherwise :param is_short: True if the trade is a short, false otherwise
:param position: Absolute value of position size incl. leverage (in base currency) :param amount: Absolute value of position size incl. leverage (in base currency)
:param stake_amount: Stake amount - Collateral in settle currency.
:param trading_mode: SPOT, MARGIN, FUTURES, etc. :param trading_mode: SPOT, MARGIN, FUTURES, etc.
:param margin_mode: Either ISOLATED or CROSS :param margin_mode: Either ISOLATED or CROSS
:param wallet_balance: Amount of margin_mode in the wallet being used to trade :param wallet_balance: Amount of margin_mode in the wallet being used to trade
@ -2667,7 +2679,7 @@ class Exchange:
market = self.markets[pair] market = self.markets[pair]
taker_fee_rate = market['taker'] taker_fee_rate = market['taker']
mm_ratio, _ = self.get_maintenance_ratio_and_amt(pair, position) mm_ratio, _ = self.get_maintenance_ratio_and_amt(pair, stake_amount)
if self.trading_mode == TradingMode.FUTURES and self.margin_mode == MarginMode.ISOLATED: if self.trading_mode == TradingMode.FUTURES and self.margin_mode == MarginMode.ISOLATED:
@ -2675,7 +2687,7 @@ class Exchange:
raise OperationalException( raise OperationalException(
"Freqtrade does not yet support inverse contracts") "Freqtrade does not yet support inverse contracts")
value = wallet_balance / position value = wallet_balance / amount
mm_ratio_taker = (mm_ratio + taker_fee_rate) mm_ratio_taker = (mm_ratio + taker_fee_rate)
if is_short: if is_short:
@ -2711,8 +2723,8 @@ class Exchange:
pair_tiers = self._leverage_tiers[pair] pair_tiers = self._leverage_tiers[pair]
for tier in reversed(pair_tiers): for tier in reversed(pair_tiers):
if nominal_value >= tier['min']: if nominal_value >= tier['minNotional']:
return (tier['mmr'], tier['maintAmt']) return (tier['maintenanceMarginRate'], tier['maintAmt'])
raise OperationalException("nominal value can not be lower than 0") raise OperationalException("nominal value can not be lower than 0")
# The lowest notional_floor for any pair in fetch_leverage_tiers is always 0 because it # The lowest notional_floor for any pair in fetch_leverage_tiers is always 0 because it
@ -2854,6 +2866,33 @@ def market_is_active(market: Dict) -> bool:
return market.get('active', True) is not False return market.get('active', True) is not False
def amount_to_contracts(amount: float, contract_size: Optional[float]) -> float:
"""
Convert amount to contracts.
:param amount: amount to convert
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: num-contracts
"""
if contract_size and contract_size != 1:
return amount / contract_size
else:
return amount
def contracts_to_amount(num_contracts: float, contract_size: Optional[float]) -> float:
"""
Takes num-contracts and converts it to contract size
:param num_contracts: number of contracts
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: Amount
"""
if contract_size and contract_size != 1:
return num_contracts * contract_size
else:
return num_contracts
def amount_to_precision(amount: float, amount_precision: Optional[float], def amount_to_precision(amount: float, amount_precision: Optional[float],
precisionMode: Optional[int]) -> float: precisionMode: Optional[int]) -> float:
""" """
@ -2878,6 +2917,29 @@ def amount_to_precision(amount: float, amount_precision: Optional[float],
return amount return amount
def amount_to_contract_precision(
amount, amount_precision: Optional[float], precisionMode: Optional[int],
contract_size: Optional[float]) -> float:
"""
Returns the amount to buy or sell to a precision the Exchange accepts
including calculation to and from contracts.
Re-implementation of ccxt internal methods - ensuring we can test the result is correct
based on our definitions.
:param amount: amount to truncate
:param amount_precision: amount precision to use.
should be retrieved from markets[pair]['precision']['amount']
:param precisionMode: precision mode to use. Should be used from precisionMode
one of ccxt's DECIMAL_PLACES, SIGNIFICANT_DIGITS, or TICK_SIZE
:param contract_size: contract size - taken from exchange.get_contract_size(pair)
:return: truncated amount
"""
if amount_precision is not None and precisionMode is not None:
contracts = amount_to_contracts(amount, contract_size)
amount_p = amount_to_precision(contracts, amount_precision, precisionMode)
return contracts_to_amount(amount_p, contract_size)
return amount
def price_to_precision(price: float, price_precision: Optional[float], def price_to_precision(price: float, price_precision: Optional[float],
precisionMode: Optional[int]) -> float: precisionMode: Optional[int]) -> float:
""" """

View File

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

View File

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

View File

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

View File

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

View File

@ -39,6 +39,8 @@ class Okx(Exchange):
net_only = True net_only = True
_ccxt_params: Dict = {'options': {'brokerId': 'ffb5405ad327SUDE'}}
def ohlcv_candle_limit( def ohlcv_candle_limit(
self, timeframe: str, candle_type: CandleType, since_ms: Optional[int] = None) -> int: self, timeframe: str, candle_type: CandleType, since_ms: Optional[int] = None) -> int:
""" """
@ -96,7 +98,7 @@ class Okx(Exchange):
ordertype: str, ordertype: str,
leverage: float, leverage: float,
reduceOnly: bool, reduceOnly: bool,
time_in_force: str = 'gtc', time_in_force: str = 'GTC',
) -> Dict: ) -> Dict:
params = super()._get_params( params = super()._get_params(
side=side, side=side,
@ -144,4 +146,4 @@ class Okx(Exchange):
return float('inf') return float('inf')
pair_tiers = self._leverage_tiers[pair] pair_tiers = self._leverage_tiers[pair]
return pair_tiers[-1]['max'] / leverage return pair_tiers[-1]['maxNotional'] / leverage

View File

@ -421,7 +421,7 @@ class FreqaiDataDrawer:
) )
# if self.live: # if self.live:
self.model_dictionary[dk.model_filename] = model self.model_dictionary[coin] = model
self.pair_dict[coin]["model_filename"] = dk.model_filename self.pair_dict[coin]["model_filename"] = dk.model_filename
self.pair_dict[coin]["data_path"] = str(dk.data_path) self.pair_dict[coin]["data_path"] = str(dk.data_path)
self.save_drawer_to_disk() self.save_drawer_to_disk()
@ -460,8 +460,8 @@ class FreqaiDataDrawer:
) )
# try to access model in memory instead of loading object from disk to save time # try to access model in memory instead of loading object from disk to save time
if dk.live and dk.model_filename in self.model_dictionary: if dk.live and coin in self.model_dictionary:
model = self.model_dictionary[dk.model_filename] model = self.model_dictionary[coin]
elif not dk.keras: elif not dk.keras:
model = load(dk.data_path / f"{dk.model_filename}_model.joblib") model = load(dk.data_path / f"{dk.model_filename}_model.joblib")
else: else:
@ -566,7 +566,6 @@ class FreqaiDataDrawer:
for training according to user defined train_period_days for training according to user defined train_period_days
metadata: dict = strategy furnished pair metadata metadata: dict = strategy furnished pair metadata
""" """
with self.history_lock: with self.history_lock:
corr_dataframes: Dict[Any, Any] = {} corr_dataframes: Dict[Any, Any] = {}
base_dataframes: Dict[Any, Any] = {} base_dataframes: Dict[Any, Any] = {}

View File

@ -166,9 +166,17 @@ class FreqaiDataKitchen:
train_labels = labels train_labels = labels
train_weights = weights train_weights = weights
return self.build_data_dictionary( # Simplest way to reverse the order of training and test data:
train_features, test_features, train_labels, test_labels, train_weights, test_weights if self.freqai_config['feature_parameters'].get('reverse_train_test_order', False):
) return self.build_data_dictionary(
test_features, train_features, test_labels,
train_labels, test_weights, train_weights
)
else:
return self.build_data_dictionary(
train_features, test_features, train_labels,
test_labels, train_weights, test_weights
)
def filter_features( def filter_features(
self, self,
@ -452,7 +460,6 @@ class FreqaiDataKitchen:
logger.info("reduced feature dimension by %s", n_components - n_keep_components) logger.info("reduced feature dimension by %s", n_components - n_keep_components)
logger.info("explained variance %f", np.sum(pca2.explained_variance_ratio_)) logger.info("explained variance %f", np.sum(pca2.explained_variance_ratio_))
train_components = pca2.transform(self.data_dictionary["train_features"]) train_components = pca2.transform(self.data_dictionary["train_features"])
test_components = pca2.transform(self.data_dictionary["test_features"])
self.data_dictionary["train_features"] = pd.DataFrame( self.data_dictionary["train_features"] = pd.DataFrame(
data=train_components, data=train_components,
@ -466,6 +473,7 @@ class FreqaiDataKitchen:
self.training_features_list = self.data_dictionary["train_features"].columns self.training_features_list = self.data_dictionary["train_features"].columns
if self.freqai_config.get('data_split_parameters', {}).get('test_size', 0.1) != 0: if self.freqai_config.get('data_split_parameters', {}).get('test_size', 0.1) != 0:
test_components = pca2.transform(self.data_dictionary["test_features"])
self.data_dictionary["test_features"] = pd.DataFrame( self.data_dictionary["test_features"] = pd.DataFrame(
data=test_components, data=test_components,
columns=["PC" + str(i) for i in range(0, n_keep_components)], columns=["PC" + str(i) for i in range(0, n_keep_components)],
@ -504,10 +512,25 @@ class FreqaiDataKitchen:
# logger.info("computing average mean distance for all training points") # logger.info("computing average mean distance for all training points")
pairwise = pairwise_distances( pairwise = pairwise_distances(
self.data_dictionary["train_features"], n_jobs=self.thread_count) self.data_dictionary["train_features"], n_jobs=self.thread_count)
avg_mean_dist = pairwise.mean(axis=1).mean() # remove the diagonal distances which are itself distances ~0
np.fill_diagonal(pairwise, np.NaN)
pairwise = pairwise.reshape(-1, 1)
avg_mean_dist = pairwise[~np.isnan(pairwise)].mean()
return avg_mean_dist return avg_mean_dist
def get_outlier_percentage(self, dropped_pts: npt.NDArray) -> float:
"""
Check if more than X% of points werer dropped during outlier detection.
"""
outlier_protection_pct = self.freqai_config["feature_parameters"].get(
"outlier_protection_percentage", 30)
outlier_pct = (dropped_pts.sum() / len(dropped_pts)) * 100
if outlier_pct >= outlier_protection_pct:
return outlier_pct
else:
return 0.0
def use_SVM_to_remove_outliers(self, predict: bool) -> None: def use_SVM_to_remove_outliers(self, predict: bool) -> None:
""" """
Build/inference a Support Vector Machine to detect outliers Build/inference a Support Vector Machine to detect outliers
@ -545,8 +568,17 @@ class FreqaiDataKitchen:
self.data_dictionary["train_features"] self.data_dictionary["train_features"]
) )
y_pred = self.svm_model.predict(self.data_dictionary["train_features"]) y_pred = self.svm_model.predict(self.data_dictionary["train_features"])
dropped_points = np.where(y_pred == -1, 0, y_pred) kept_points = np.where(y_pred == -1, 0, y_pred)
# keep_index = np.where(y_pred == 1) # keep_index = np.where(y_pred == 1)
outlier_pct = self.get_outlier_percentage(1 - kept_points)
if outlier_pct:
logger.warning(
f"SVM detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
self.svm_model = None
return
self.data_dictionary["train_features"] = self.data_dictionary["train_features"][ self.data_dictionary["train_features"] = self.data_dictionary["train_features"][
(y_pred == 1) (y_pred == 1)
] ]
@ -558,7 +590,7 @@ class FreqaiDataKitchen:
] ]
logger.info( logger.info(
f"SVM tossed {len(y_pred) - dropped_points.sum()}" f"SVM tossed {len(y_pred) - kept_points.sum()}"
f" train points from {len(y_pred)} total points." f" train points from {len(y_pred)} total points."
) )
@ -567,7 +599,7 @@ class FreqaiDataKitchen:
# to reduce code duplication # to reduce code duplication
if self.freqai_config['data_split_parameters'].get('test_size', 0.1) != 0: if self.freqai_config['data_split_parameters'].get('test_size', 0.1) != 0:
y_pred = self.svm_model.predict(self.data_dictionary["test_features"]) y_pred = self.svm_model.predict(self.data_dictionary["test_features"])
dropped_points = np.where(y_pred == -1, 0, y_pred) kept_points = np.where(y_pred == -1, 0, y_pred)
self.data_dictionary["test_features"] = self.data_dictionary["test_features"][ self.data_dictionary["test_features"] = self.data_dictionary["test_features"][
(y_pred == 1) (y_pred == 1)
] ]
@ -578,7 +610,7 @@ class FreqaiDataKitchen:
] ]
logger.info( logger.info(
f"SVM tossed {len(y_pred) - dropped_points.sum()}" f"SVM tossed {len(y_pred) - kept_points.sum()}"
f" test points from {len(y_pred)} total points." f" test points from {len(y_pred)} total points."
) )
@ -596,7 +628,11 @@ class FreqaiDataKitchen:
is an outlier. is an outlier.
""" """
from math import cos, sin
if predict: if predict:
if not self.data['DBSCAN_eps']:
return
train_ft_df = self.data_dictionary['train_features'] train_ft_df = self.data_dictionary['train_features']
pred_ft_df = self.data_dictionary['prediction_features'] pred_ft_df = self.data_dictionary['prediction_features']
num_preds = len(pred_ft_df) num_preds = len(pred_ft_df)
@ -614,28 +650,61 @@ class FreqaiDataKitchen:
else: else:
MinPts = len(self.data_dictionary['train_features'].columns) * 2 def normalise_distances(distances):
# measure pairwise distances to train_features.shape[1]*2 nearest neighbours normalised_distances = (distances - distances.min()) / \
(distances.max() - distances.min())
return normalised_distances
def rotate_point(origin, point, angle):
# rotate a point counterclockwise by a given angle (in radians)
# around a given origin
x = origin[0] + cos(angle) * (point[0] - origin[0]) - \
sin(angle) * (point[1] - origin[1])
y = origin[1] + sin(angle) * (point[0] - origin[0]) + \
cos(angle) * (point[1] - origin[1])
return (x, y)
MinPts = int(len(self.data_dictionary['train_features'].index) * 0.25)
# measure pairwise distances to nearest neighbours
neighbors = NearestNeighbors( neighbors = NearestNeighbors(
n_neighbors=MinPts, n_jobs=self.thread_count) n_neighbors=MinPts, n_jobs=self.thread_count)
neighbors_fit = neighbors.fit(self.data_dictionary['train_features']) neighbors_fit = neighbors.fit(self.data_dictionary['train_features'])
distances, _ = neighbors_fit.kneighbors(self.data_dictionary['train_features']) distances, _ = neighbors_fit.kneighbors(self.data_dictionary['train_features'])
distances = np.sort(distances, axis=0) distances = np.sort(distances, axis=0).mean(axis=1)
index_ten_pct = int(len(distances[:, 1]) * 0.1)
distances = distances[index_ten_pct:, 1] normalised_distances = normalise_distances(distances)
epsilon = distances[-1] x_range = np.linspace(0, 1, len(distances))
line = np.linspace(normalised_distances[0],
normalised_distances[-1], len(normalised_distances))
deflection = np.abs(normalised_distances - line)
max_deflection_loc = np.where(deflection == deflection.max())[0][0]
origin = x_range[max_deflection_loc], line[max_deflection_loc]
point = x_range[max_deflection_loc], normalised_distances[max_deflection_loc]
rot_angle = np.pi / 4
elbow_loc = rotate_point(origin, point, rot_angle)
epsilon = elbow_loc[1] * (distances[-1] - distances[0]) + distances[0]
clustering = DBSCAN(eps=epsilon, min_samples=MinPts, clustering = DBSCAN(eps=epsilon, min_samples=MinPts,
n_jobs=int(self.thread_count)).fit( n_jobs=int(self.thread_count)).fit(
self.data_dictionary['train_features'] self.data_dictionary['train_features']
) )
logger.info(f'DBSCAN found eps of {epsilon}.') logger.info(f'DBSCAN found eps of {epsilon:.2f}.')
self.data['DBSCAN_eps'] = epsilon self.data['DBSCAN_eps'] = epsilon
self.data['DBSCAN_min_samples'] = MinPts self.data['DBSCAN_min_samples'] = MinPts
dropped_points = np.where(clustering.labels_ == -1, 1, 0) dropped_points = np.where(clustering.labels_ == -1, 1, 0)
outlier_pct = self.get_outlier_percentage(dropped_points)
if outlier_pct:
logger.warning(
f"DBSCAN detected {outlier_pct:.2f}% of the points as outliers. "
f"Keeping original dataset."
)
self.data['DBSCAN_eps'] = 0
return
self.data_dictionary['train_features'] = self.data_dictionary['train_features'][ self.data_dictionary['train_features'] = self.data_dictionary['train_features'][
(clustering.labels_ != -1) (clustering.labels_ != -1)
] ]
@ -693,8 +762,8 @@ class FreqaiDataKitchen:
if (len(do_predict) - do_predict.sum()) > 0: if (len(do_predict) - do_predict.sum()) > 0:
logger.info( logger.info(
f"DI tossed {len(do_predict) - do_predict.sum():.2f} predictions for " f"DI tossed {len(do_predict) - do_predict.sum()} predictions for "
"being too far from training data" "being too far from training data."
) )
self.do_predict += do_predict self.do_predict += do_predict
@ -866,13 +935,6 @@ class FreqaiDataKitchen:
data_load_timerange.stopts = int(time) data_load_timerange.stopts = int(time)
retrain = True retrain = True
# logger.info(
# f"downloading data for "
# f"{(data_load_timerange.stopts-data_load_timerange.startts)/SECONDS_IN_DAY:.2f} "
# " days. "
# f"Extension of {additional_seconds/SECONDS_IN_DAY:.2f} days"
# )
return retrain, trained_timerange, data_load_timerange return retrain, trained_timerange, data_load_timerange
def set_new_model_names(self, pair: str, trained_timerange: TimeRange): def set_new_model_names(self, pair: str, trained_timerange: TimeRange):

View File

@ -80,12 +80,15 @@ class IFreqaiModel(ABC):
logger.warning("DI threshold is not configured for Keras models yet. Deactivating.") logger.warning("DI threshold is not configured for Keras models yet. Deactivating.")
self.CONV_WIDTH = self.freqai_info.get("conv_width", 2) self.CONV_WIDTH = self.freqai_info.get("conv_width", 2)
self.pair_it = 0 self.pair_it = 0
self.pair_it_train = 0
self.total_pairs = len(self.config.get("exchange", {}).get("pair_whitelist")) self.total_pairs = len(self.config.get("exchange", {}).get("pair_whitelist"))
self.last_trade_database_summary: DataFrame = {} self.last_trade_database_summary: DataFrame = {}
self.current_trade_database_summary: DataFrame = {} self.current_trade_database_summary: DataFrame = {}
self.analysis_lock = Lock() self.analysis_lock = Lock()
self.inference_time: float = 0 self.inference_time: float = 0
self.train_time: float = 0
self.begin_time: float = 0 self.begin_time: float = 0
self.begin_time_train: float = 0
self.base_tf_seconds = timeframe_to_seconds(self.config['timeframe']) self.base_tf_seconds = timeframe_to_seconds(self.config['timeframe'])
def assert_config(self, config: Dict[str, Any]) -> None: def assert_config(self, config: Dict[str, Any]) -> None:
@ -128,11 +131,20 @@ class IFreqaiModel(ABC):
dk = self.start_backtesting(dataframe, metadata, self.dk) dk = self.start_backtesting(dataframe, metadata, self.dk)
dataframe = dk.remove_features_from_df(dk.return_dataframe) dataframe = dk.remove_features_from_df(dk.return_dataframe)
del dk self.clean_up()
if self.live: if self.live:
self.inference_timer('stop') self.inference_timer('stop')
return dataframe return dataframe
def clean_up(self):
"""
Objects that should be handled by GC already between coins, but
are explicitly shown here to help demonstrate the non-persistence of these
objects.
"""
self.model = None
self.dk = None
@threaded @threaded
def start_scanning(self, strategy: IStrategy) -> None: def start_scanning(self, strategy: IStrategy) -> None:
""" """
@ -159,9 +171,11 @@ class IFreqaiModel(ABC):
dk.set_paths(pair, new_trained_timerange.stopts) dk.set_paths(pair, new_trained_timerange.stopts)
if retrain: if retrain:
self.train_timer('start')
self.train_model_in_series( self.train_model_in_series(
new_trained_timerange, pair, strategy, dk, data_load_timerange new_trained_timerange, pair, strategy, dk, data_load_timerange
) )
self.train_timer('stop')
self.dd.save_historic_predictions_to_disk() self.dd.save_historic_predictions_to_disk()
@ -474,8 +488,7 @@ class IFreqaiModel(ABC):
data_load_timerange: TimeRange, data_load_timerange: TimeRange,
): ):
""" """
Retrieve data and train model in single threaded mode (only used if model directory is empty Retrieve data and train model.
upon startup for dry/live )
:param new_trained_timerange: TimeRange = the timerange to train the model on :param new_trained_timerange: TimeRange = the timerange to train the model on
:param metadata: dict = strategy provided metadata :param metadata: dict = strategy provided metadata
:param strategy: IStrategy = user defined strategy object :param strategy: IStrategy = user defined strategy object
@ -606,6 +619,24 @@ class IFreqaiModel(ABC):
self.inference_time = 0 self.inference_time = 0
return return
def train_timer(self, do='start'):
"""
Timer designed to track the cumulative time spent training the full pairlist in
FreqAI.
"""
if do == 'start':
self.pair_it_train += 1
self.begin_time_train = time.time()
elif do == 'stop':
end = time.time()
self.train_time += (end - self.begin_time_train)
if self.pair_it_train == self.total_pairs:
logger.info(
f'Total time spent training pairlist {self.train_time:.2f} seconds')
self.pair_it_train = 0
self.train_time = 0
return
# Following methods which are overridden by user made prediction models. # Following methods which are overridden by user made prediction models.
# See freqai/prediction_models/CatboostPredictionModel.py for an example. # See freqai/prediction_models/CatboostPredictionModel.py for an example.

View File

@ -21,8 +21,7 @@ from freqtrade.enums import (ExitCheckTuple, ExitType, RPCMessageType, RunMode,
State, TradingMode) State, TradingMode)
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError, from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
InvalidOrderException, PricingError) InvalidOrderException, PricingError)
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds
from freqtrade.exchange.exchange import timeframe_to_next_date
from freqtrade.misc import safe_value_fallback, safe_value_fallback2 from freqtrade.misc import safe_value_fallback, safe_value_fallback2
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.persistence import Order, PairLocks, Trade, init_db from freqtrade.persistence import Order, PairLocks, Trade, init_db
@ -240,7 +239,7 @@ class FreqtradeBot(LoggingMixin):
'status': 'status':
f"{len(open_trades)} open trades active.\n\n" f"{len(open_trades)} open trades active.\n\n"
f"Handle these trades manually on {self.exchange.name}, " f"Handle these trades manually on {self.exchange.name}, "
f"or '/start' the bot again and use '/stopbuy' " f"or '/start' the bot again and use '/stopentry' "
f"to handle open trades gracefully. \n" f"to handle open trades gracefully. \n"
f"{'Note: Trades are simulated (dry run).' if self.config['dry_run'] else ''}", f"{'Note: Trades are simulated (dry run).' if self.config['dry_run'] else ''}",
} }
@ -271,7 +270,7 @@ class FreqtradeBot(LoggingMixin):
Return the number of free open trades slots or 0 if Return the number of free open trades slots or 0 if
max number of open trades reached max number of open trades reached
""" """
open_trades = len(Trade.get_open_trades()) open_trades = Trade.get_open_trade_count()
return max(0, self.config['max_open_trades'] - open_trades) return max(0, self.config['max_open_trades'] - open_trades)
def update_funding_fees(self): def update_funding_fees(self):
@ -290,13 +289,14 @@ class FreqtradeBot(LoggingMixin):
def startup_backpopulate_precision(self): def startup_backpopulate_precision(self):
trades = Trade.get_trades([Trade.precision_mode.is_(None)]) trades = Trade.get_trades([Trade.contract_size.is_(None)])
for trade in trades: for trade in trades:
if trade.exchange != self.exchange.id: if trade.exchange != self.exchange.id:
continue continue
trade.precision_mode = self.exchange.precisionMode trade.precision_mode = self.exchange.precisionMode
trade.amount_precision = self.exchange.get_precision_amount(trade.pair) trade.amount_precision = self.exchange.get_precision_amount(trade.pair)
trade.price_precision = self.exchange.get_precision_price(trade.pair) trade.price_precision = self.exchange.get_precision_price(trade.pair)
trade.contract_size = self.exchange.get_contract_size(trade.pair)
Trade.commit() Trade.commit()
def startup_update_open_orders(self): def startup_update_open_orders(self):
@ -418,7 +418,7 @@ class FreqtradeBot(LoggingMixin):
whitelist = copy.deepcopy(self.active_pair_whitelist) whitelist = copy.deepcopy(self.active_pair_whitelist)
if not whitelist: if not whitelist:
logger.info("Active pair whitelist is empty.") self.log_once("Active pair whitelist is empty.", logger.info)
return trades_created return trades_created
# Remove pairs for currently opened trades from the whitelist # Remove pairs for currently opened trades from the whitelist
for trade in Trade.get_open_trades(): for trade in Trade.get_open_trades():
@ -427,8 +427,8 @@ class FreqtradeBot(LoggingMixin):
logger.debug('Ignoring %s in pair whitelist', trade.pair) logger.debug('Ignoring %s in pair whitelist', trade.pair)
if not whitelist: if not whitelist:
logger.info("No currency pair in active pair whitelist, " self.log_once("No currency pair in active pair whitelist, "
"but checking to exit open trades.") "but checking to exit open trades.", logger.info)
return trades_created return trades_created
if PairLocks.is_global_lock(side='*'): if PairLocks.is_global_lock(side='*'):
# This only checks for total locks (both sides). # This only checks for total locks (both sides).
@ -755,6 +755,7 @@ class FreqtradeBot(LoggingMixin):
amount_precision=self.exchange.get_precision_amount(pair), amount_precision=self.exchange.get_precision_amount(pair),
price_precision=self.exchange.get_precision_price(pair), price_precision=self.exchange.get_precision_price(pair),
precision_mode=self.exchange.precisionMode, precision_mode=self.exchange.precisionMode,
contract_size=self.exchange.get_contract_size(pair),
) )
else: else:
# This is additional buy, we reset fee_open_currency so timeout checking can work # This is additional buy, we reset fee_open_currency so timeout checking can work
@ -1551,9 +1552,10 @@ class FreqtradeBot(LoggingMixin):
trade.close_rate_requested = limit trade.close_rate_requested = limit
trade.exit_reason = exit_reason trade.exit_reason = exit_reason
# Lock pair for one candle to prevent immediate re-trading if not sub_trade_amt:
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc), # Lock pair for one candle to prevent immediate re-trading
reason='Auto lock') self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),
reason='Auto lock')
self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj) self._notify_exit(trade, order_type, sub_trade=bool(sub_trade_amt), order=order_obj)
# In case of market sell orders the order can be closed immediately # In case of market sell orders the order can be closed immediately
@ -1730,11 +1732,12 @@ class FreqtradeBot(LoggingMixin):
# TODO: Margin will need to use interest_rate as well. # TODO: Margin will need to use interest_rate as well.
# interest_rate = self.exchange.get_interest_rate() # interest_rate = self.exchange.get_interest_rate()
trade.set_liquidation_price(self.exchange.get_liquidation_price( trade.set_liquidation_price(self.exchange.get_liquidation_price(
leverage=trade.leverage,
pair=trade.pair, pair=trade.pair,
amount=trade.amount,
open_rate=trade.open_rate, open_rate=trade.open_rate,
is_short=trade.is_short is_short=trade.is_short,
amount=trade.amount,
stake_amount=trade.stake_amount,
wallet_balance=trade.stake_amount,
)) ))
# Updating wallets when order is closed # Updating wallets when order is closed
@ -1775,7 +1778,7 @@ class FreqtradeBot(LoggingMixin):
self.rpc.send_msg(msg) self.rpc.send_msg(msg)
def apply_fee_conditional(self, trade: Trade, trade_base_currency: str, def apply_fee_conditional(self, trade: Trade, trade_base_currency: str,
amount: float, fee_abs: float) -> float: amount: float, fee_abs: float) -> Optional[float]:
""" """
Applies the fee to amount (either from Order or from Trades). Applies the fee to amount (either from Order or from Trades).
Can eat into dust if more than the required asset is available. Can eat into dust if more than the required asset is available.
@ -1788,35 +1791,32 @@ class FreqtradeBot(LoggingMixin):
logger.info(f"Fee amount for {trade} was in base currency - " logger.info(f"Fee amount for {trade} was in base currency - "
f"Eating Fee {fee_abs} into dust.") f"Eating Fee {fee_abs} into dust.")
elif fee_abs != 0: elif fee_abs != 0:
real_amount = self.exchange.amount_to_precision(trade.pair, amount - fee_abs) logger.info(f"Applying fee on amount for {trade}, fee={fee_abs}.")
logger.info(f"Applying fee on amount for {trade} " return fee_abs
f"(from {amount} to {real_amount}).") return None
return real_amount
return amount
def handle_order_fee(self, trade: Trade, order_obj: Order, order: Dict[str, Any]) -> None: def handle_order_fee(self, trade: Trade, order_obj: Order, order: Dict[str, Any]) -> None:
# Try update amount (binance-fix) # Try update amount (binance-fix)
try: try:
new_amount = self.get_real_amount(trade, order, order_obj) fee_abs = self.get_real_amount(trade, order, order_obj)
if not isclose(safe_value_fallback(order, 'filled', 'amount'), new_amount, if fee_abs is not None:
abs_tol=constants.MATH_CLOSE_PREC): order_obj.ft_fee_base = fee_abs
order_obj.ft_fee_base = trade.amount - new_amount
except DependencyException as exception: except DependencyException as exception:
logger.warning("Could not update trade amount: %s", exception) logger.warning("Could not update trade amount: %s", exception)
def get_real_amount(self, trade: Trade, order: Dict, order_obj: Order) -> float: def get_real_amount(self, trade: Trade, order: Dict, order_obj: Order) -> Optional[float]:
""" """
Detect and update trade fee. Detect and update trade fee.
Calls trade.update_fee() upon correct detection. Calls trade.update_fee() upon correct detection.
Returns modified amount if the fee was taken from the destination currency. Returns modified amount if the fee was taken from the destination currency.
Necessary for exchanges which charge fees in base currency (e.g. binance) Necessary for exchanges which charge fees in base currency (e.g. binance)
:return: identical (or new) amount for the trade :return: Absolute fee to apply for this order or None
""" """
# Init variables # Init variables
order_amount = safe_value_fallback(order, 'filled', 'amount') order_amount = safe_value_fallback(order, 'filled', 'amount')
# Only run for closed orders # Only run for closed orders
if trade.fee_updated(order.get('side', '')) or order['status'] == 'open': if trade.fee_updated(order.get('side', '')) or order['status'] == 'open':
return order_amount return None
trade_base_currency = self.exchange.get_pair_base_currency(trade.pair) trade_base_currency = self.exchange.get_pair_base_currency(trade.pair)
# use fee from order-dict if possible # use fee from order-dict if possible
@ -1834,12 +1834,12 @@ class FreqtradeBot(LoggingMixin):
# Apply fee to amount # Apply fee to amount
return self.apply_fee_conditional(trade, trade_base_currency, return self.apply_fee_conditional(trade, trade_base_currency,
amount=order_amount, fee_abs=fee_cost) amount=order_amount, fee_abs=fee_cost)
return order_amount return None
return self.fee_detection_from_trades( return self.fee_detection_from_trades(
trade, order, order_obj, order_amount, order.get('trades', [])) trade, order, order_obj, order_amount, order.get('trades', []))
def fee_detection_from_trades(self, trade: Trade, order: Dict, order_obj: Order, def fee_detection_from_trades(self, trade: Trade, order: Dict, order_obj: Order,
order_amount: float, trades: List) -> float: order_amount: float, trades: List) -> Optional[float]:
""" """
fee-detection fallback to Trades. fee-detection fallback to Trades.
Either uses provided trades list or the result of fetch_my_trades to get correct fee. Either uses provided trades list or the result of fetch_my_trades to get correct fee.
@ -1850,7 +1850,7 @@ class FreqtradeBot(LoggingMixin):
if len(trades) == 0: if len(trades) == 0:
logger.info("Applying fee on amount for %s failed: myTrade-Dict empty found", trade) logger.info("Applying fee on amount for %s failed: myTrade-Dict empty found", trade)
return order_amount return None
fee_currency = None fee_currency = None
amount = 0 amount = 0
fee_abs = 0.0 fee_abs = 0.0
@ -1894,8 +1894,7 @@ class FreqtradeBot(LoggingMixin):
if fee_abs != 0: if fee_abs != 0:
return self.apply_fee_conditional(trade, trade_base_currency, return self.apply_fee_conditional(trade, trade_base_currency,
amount=amount, fee_abs=fee_abs) amount=amount, fee_abs=fee_abs)
else: return None
return amount
def get_valid_price(self, custom_price: float, proposed_price: float) -> float: def get_valid_price(self, custom_price: float, proposed_price: float) -> float:
""" """

View File

@ -23,7 +23,8 @@ from freqtrade.data.dataprovider import DataProvider
from freqtrade.enums import (BacktestState, CandleType, ExitCheckTuple, ExitType, RunMode, from freqtrade.enums import (BacktestState, CandleType, ExitCheckTuple, ExitType, RunMode,
TradingMode) TradingMode)
from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange import (amount_to_contract_precision, price_to_precision,
timeframe_to_minutes, timeframe_to_seconds)
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.optimize.backtest_caching import get_strategy_run_id from freqtrade.optimize.backtest_caching import get_strategy_run_id
from freqtrade.optimize.bt_progress import BTProgress from freqtrade.optimize.bt_progress import BTProgress
@ -257,7 +258,7 @@ class Backtesting:
funding_rates_dict = history.load_data( funding_rates_dict = history.load_data(
datadir=self.config['datadir'], datadir=self.config['datadir'],
pairs=self.pairlists.whitelist, pairs=self.pairlists.whitelist,
timeframe=self.exchange._ft_has['mark_ohlcv_timeframe'], timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
timerange=self.timerange, timerange=self.timerange,
startup_candles=0, startup_candles=0,
fail_without_data=True, fail_without_data=True,
@ -269,12 +270,12 @@ class Backtesting:
mark_rates_dict = history.load_data( mark_rates_dict = history.load_data(
datadir=self.config['datadir'], datadir=self.config['datadir'],
pairs=self.pairlists.whitelist, pairs=self.pairlists.whitelist,
timeframe=self.exchange._ft_has['mark_ohlcv_timeframe'], timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
timerange=self.timerange, timerange=self.timerange,
startup_candles=0, startup_candles=0,
fail_without_data=True, fail_without_data=True,
data_format=self.config.get('dataformat_ohlcv', 'json'), data_format=self.config.get('dataformat_ohlcv', 'json'),
candle_type=CandleType.from_string(self.exchange._ft_has["mark_ohlcv_price"]) candle_type=CandleType.from_string(self.exchange.get_option("mark_ohlcv_price"))
) )
# Combine data to avoid combining the data per trade. # Combine data to avoid combining the data per trade.
unavailable_pairs = [] unavailable_pairs = []
@ -524,12 +525,16 @@ class Backtesting:
# Check if we should increase our position # Check if we should increase our position
if stake_amount is not None and stake_amount > 0.0: if stake_amount is not None and stake_amount > 0.0:
check_adjust_entry = True
pos_trade = self._enter_trade( if self.strategy.max_entry_position_adjustment > -1:
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade) entry_count = trade.nr_of_successful_entries
if pos_trade is not None: check_adjust_entry = (entry_count <= self.strategy.max_entry_position_adjustment)
self.wallets.update() if check_adjust_entry:
return pos_trade pos_trade = self._enter_trade(
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade)
if pos_trade is not None:
self.wallets.update()
return pos_trade
if stake_amount is not None and stake_amount < 0.0: if stake_amount is not None and stake_amount < 0.0:
amount = abs(stake_amount) / current_rate amount = abs(stake_amount) / current_rate
@ -540,7 +545,8 @@ class Backtesting:
if remaining < min_stake: if remaining < min_stake:
# Remaining stake is too low to be sold. # Remaining stake is too low to be sold.
return trade return trade
pos_trade = self._exit_trade(trade, row, current_rate, amount) exit_ = ExitCheckTuple(ExitType.PARTIAL_EXIT)
pos_trade = self._get_exit_for_signal(trade, row, exit_, amount)
if pos_trade is not None: if pos_trade is not None:
order = pos_trade.orders[-1] order = pos_trade.orders[-1]
if self._get_order_filled(order.price, row): if self._get_order_filled(order.price, row):
@ -560,12 +566,7 @@ class Backtesting:
# Check if we need to adjust our current positions # Check if we need to adjust our current positions
if self.strategy.position_adjustment_enable: if self.strategy.position_adjustment_enable:
check_adjust_entry = True trade = self._get_adjust_trade_entry_for_candle(trade, row)
if self.strategy.max_entry_position_adjustment > -1:
entry_count = trade.nr_of_successful_entries
check_adjust_entry = (entry_count <= self.strategy.max_entry_position_adjustment)
if check_adjust_entry:
trade = self._get_adjust_trade_entry_for_candle(trade, row)
enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX] enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX]
exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX] exit_sig = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX]
@ -580,14 +581,15 @@ class Backtesting:
return t return t
return None return None
def _get_exit_for_signal(self, trade: LocalTrade, row: Tuple, def _get_exit_for_signal(
exit_: ExitCheckTuple) -> Optional[LocalTrade]: self, trade: LocalTrade, row: Tuple, exit_: ExitCheckTuple,
amount: Optional[float] = None) -> Optional[LocalTrade]:
exit_candle_time: datetime = row[DATE_IDX].to_pydatetime() exit_candle_time: datetime = row[DATE_IDX].to_pydatetime()
if exit_.exit_flag: if exit_.exit_flag:
trade.close_date = exit_candle_time trade.close_date = exit_candle_time
exit_reason = exit_.exit_reason exit_reason = exit_.exit_reason
amount_ = amount if amount is not None else trade.amount
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60) trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
try: try:
close_rate = self._get_close_rate(row, trade, exit_, trade_dur) close_rate = self._get_close_rate(row, trade, exit_, trade_dur)
@ -596,7 +598,8 @@ class Backtesting:
# call the custom exit price,with default value as previous close_rate # call the custom exit price,with default value as previous close_rate
current_profit = trade.calc_profit_ratio(close_rate) current_profit = trade.calc_profit_ratio(close_rate)
order_type = self.strategy.order_types['exit'] order_type = self.strategy.order_types['exit']
if exit_.exit_type in (ExitType.EXIT_SIGNAL, ExitType.CUSTOM_EXIT): if exit_.exit_type in (ExitType.EXIT_SIGNAL, ExitType.CUSTOM_EXIT,
ExitType.PARTIAL_EXIT):
# Checks and adds an exit tag, after checking that the length of the # Checks and adds an exit tag, after checking that the length of the
# row has the length for an exit tag column # row has the length for an exit tag column
if ( if (
@ -624,22 +627,23 @@ class Backtesting:
# Confirm trade exit: # Confirm trade exit:
time_in_force = self.strategy.order_time_in_force['exit'] time_in_force = self.strategy.order_time_in_force['exit']
if (exit_.exit_type != ExitType.LIQUIDATION and not strategy_safe_wrapper( if (exit_.exit_type not in (ExitType.LIQUIDATION, ExitType.PARTIAL_EXIT)
self.strategy.confirm_trade_exit, default_retval=True)( and not strategy_safe_wrapper(
pair=trade.pair, self.strategy.confirm_trade_exit, default_retval=True)(
trade=trade, # type: ignore[arg-type] pair=trade.pair,
order_type=order_type, trade=trade, # type: ignore[arg-type]
amount=trade.amount, order_type=order_type,
rate=close_rate, amount=amount_,
time_in_force=time_in_force, rate=close_rate,
sell_reason=exit_reason, # deprecated time_in_force=time_in_force,
exit_reason=exit_reason, sell_reason=exit_reason, # deprecated
current_time=exit_candle_time)): exit_reason=exit_reason,
current_time=exit_candle_time)):
return None return None
trade.exit_reason = exit_reason trade.exit_reason = exit_reason
return self._exit_trade(trade, row, close_rate, trade.amount) return self._exit_trade(trade, row, close_rate, amount_)
return None return None
def _exit_trade(self, trade: LocalTrade, sell_row: Tuple, def _exit_trade(self, trade: LocalTrade, sell_row: Tuple,
@ -647,7 +651,10 @@ class Backtesting:
self.order_id_counter += 1 self.order_id_counter += 1
exit_candle_time = sell_row[DATE_IDX].to_pydatetime() exit_candle_time = sell_row[DATE_IDX].to_pydatetime()
order_type = self.strategy.order_types['exit'] order_type = self.strategy.order_types['exit']
amount = amount or trade.amount # amount = amount or trade.amount
amount = amount_to_contract_precision(amount or trade.amount, trade.amount_precision,
self.precision_mode, trade.contract_size)
rate = price_to_precision(close_rate, trade.price_precision, self.precision_mode)
order = Order( order = Order(
id=self.order_id_counter, id=self.order_id_counter,
ft_trade_id=trade.id, ft_trade_id=trade.id,
@ -661,12 +668,12 @@ class Backtesting:
side=trade.exit_side, side=trade.exit_side,
order_type=order_type, order_type=order_type,
status="open", status="open",
price=close_rate, price=rate,
average=close_rate, average=rate,
amount=amount, amount=amount,
filled=0, filled=0,
remaining=amount, remaining=amount,
cost=amount * close_rate, cost=amount * rate,
) )
trade.orders.append(order) trade.orders.append(order)
return trade return trade
@ -812,7 +819,17 @@ class Backtesting:
if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount): if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount):
self.order_id_counter += 1 self.order_id_counter += 1
base_currency = self.exchange.get_pair_base_currency(pair) base_currency = self.exchange.get_pair_base_currency(pair)
amount = round((stake_amount / propose_rate) * leverage, 8) precision_price = self.exchange.get_precision_price(pair)
propose_rate = price_to_precision(propose_rate, precision_price, self.precision_mode)
amount_p = (stake_amount / propose_rate) * leverage
contract_size = self.exchange.get_contract_size(pair)
precision_amount = self.exchange.get_precision_amount(pair)
amount = amount_to_contract_precision(amount_p, precision_amount, self.precision_mode,
contract_size)
# Backcalculate actual stake amount.
stake_amount = amount * propose_rate / leverage
is_short = (direction == 'short') is_short = (direction == 'short')
# Necessary for Margin trading. Disabled until support is enabled. # Necessary for Margin trading. Disabled until support is enabled.
# interest_rate = self.exchange.get_interest_rate() # interest_rate = self.exchange.get_interest_rate()
@ -841,9 +858,10 @@ class Backtesting:
trading_mode=self.trading_mode, trading_mode=self.trading_mode,
leverage=leverage, leverage=leverage,
# interest_rate=interest_rate, # interest_rate=interest_rate,
amount_precision=self.exchange.get_precision_amount(pair), amount_precision=precision_amount,
price_precision=self.exchange.get_precision_price(pair), price_precision=precision_price,
precision_mode=self.precision_mode, precision_mode=self.precision_mode,
contract_size=contract_size,
orders=[], orders=[],
) )
@ -853,7 +871,8 @@ class Backtesting:
pair=pair, pair=pair,
open_rate=propose_rate, open_rate=propose_rate,
amount=amount, amount=amount,
leverage=leverage, stake_amount=trade.stake_amount,
wallet_balance=trade.stake_amount,
is_short=is_short, is_short=is_short,
)) ))

View File

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

View File

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

View File

@ -133,6 +133,7 @@ def migrate_trades_and_orders_table(
amount_precision = get_column_def(cols, 'amount_precision', 'null') amount_precision = get_column_def(cols, 'amount_precision', 'null')
price_precision = get_column_def(cols, 'price_precision', 'null') price_precision = get_column_def(cols, 'price_precision', 'null')
precision_mode = get_column_def(cols, 'precision_mode', 'null') precision_mode = get_column_def(cols, 'precision_mode', 'null')
contract_size = get_column_def(cols, 'contract_size', 'null')
# Schema migration necessary # Schema migration necessary
with engine.begin() as connection: with engine.begin() as connection:
@ -161,7 +162,7 @@ def migrate_trades_and_orders_table(
timeframe, open_trade_value, close_profit_abs, timeframe, open_trade_value, close_profit_abs,
trading_mode, leverage, liquidation_price, is_short, trading_mode, leverage, liquidation_price, is_short,
interest_rate, funding_fees, realized_profit, interest_rate, funding_fees, realized_profit,
amount_precision, price_precision, precision_mode amount_precision, price_precision, precision_mode, contract_size
) )
select id, lower(exchange), pair, {base_currency} base_currency, select id, lower(exchange), pair, {base_currency} base_currency,
{stake_currency} stake_currency, {stake_currency} stake_currency,
@ -189,7 +190,7 @@ def migrate_trades_and_orders_table(
{is_short} is_short, {interest_rate} interest_rate, {is_short} is_short, {interest_rate} interest_rate,
{funding_fees} funding_fees, {realized_profit} realized_profit, {funding_fees} funding_fees, {realized_profit} realized_profit,
{amount_precision} amount_precision, {price_precision} price_precision, {amount_precision} amount_precision, {price_precision} price_precision,
{precision_mode} precision_mode {precision_mode} precision_mode, {contract_size} contract_size
from {trade_back_name} from {trade_back_name}
""")) """))
@ -307,7 +308,9 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
# Migrates both trades and orders table! # Migrates both trades and orders table!
# if ('orders' not in previous_tables # if ('orders' not in previous_tables
# or not has_column(cols_orders, 'stop_price')): # or not has_column(cols_orders, 'stop_price')):
if not has_column(cols_trades, 'precision_mode'): migrating = False
if not has_column(cols_trades, 'contract_size'):
migrating = True
logger.info(f"Running database migration for trades - " logger.info(f"Running database migration for trades - "
f"backup: {table_back_name}, {order_table_bak_name}") f"backup: {table_back_name}, {order_table_bak_name}")
migrate_trades_and_orders_table( migrate_trades_and_orders_table(
@ -315,6 +318,7 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
order_table_bak_name, cols_orders) order_table_bak_name, cols_orders)
if not has_column(cols_pairlocks, 'side'): if not has_column(cols_pairlocks, 'side'):
migrating = True
logger.info(f"Running database migration for pairlocks - " logger.info(f"Running database migration for pairlocks - "
f"backup: {pairlock_table_bak_name}") f"backup: {pairlock_table_bak_name}")
@ -329,3 +333,6 @@ def check_migrate(engine, decl_base, previous_tables) -> None:
set_sqlite_to_wal(engine) set_sqlite_to_wal(engine)
fix_old_dry_orders(engine) fix_old_dry_orders(engine)
if migrating:
logger.info("Database migration finished.")

View File

@ -53,7 +53,7 @@ def init_db(db_url: str) -> None:
# https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope
# Scoped sessions proxy requests to the appropriate thread-local session. # Scoped sessions proxy requests to the appropriate thread-local session.
# We should use the scoped_session object - not a seperately initialized version # 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() Trade.query = Trade._session.query_property()
Order.query = Trade._session.query_property() Order.query = Trade._session.query_property()
PairLock.query = Trade._session.query_property() PairLock.query = Trade._session.query_property()

View File

@ -14,7 +14,7 @@ from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPE
BuySell, LongShort) BuySell, LongShort)
from freqtrade.enums import ExitType, TradingMode from freqtrade.enums import ExitType, TradingMode
from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.exchange import amount_to_precision, price_to_precision from freqtrade.exchange import amount_to_contract_precision, price_to_precision
from freqtrade.leverage import interest from freqtrade.leverage import interest
from freqtrade.persistence.base import _DECL_BASE from freqtrade.persistence.base import _DECL_BASE
from freqtrade.util import FtPrecise from freqtrade.util import FtPrecise
@ -296,6 +296,7 @@ class LocalTrade():
amount_precision: Optional[float] = None amount_precision: Optional[float] = None
price_precision: Optional[float] = None price_precision: Optional[float] = None
precision_mode: Optional[int] = None precision_mode: Optional[int] = None
contract_size: Optional[float] = None
# Leverage trading properties # Leverage trading properties
liquidation_price: Optional[float] = None liquidation_price: Optional[float] = None
@ -623,7 +624,8 @@ class LocalTrade():
else: else:
logger.warning( logger.warning(
f'Got different open_order_id {self.open_order_id} != {order.order_id}') f'Got different open_order_id {self.open_order_id} != {order.order_id}')
amount_tr = amount_to_precision(self.amount, self.amount_precision, self.precision_mode) amount_tr = amount_to_contract_precision(self.amount, self.amount_precision,
self.precision_mode, self.contract_size)
if isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC): if isclose(order.safe_amount_after_fee, amount_tr, abs_tol=MATH_CLOSE_PREC):
self.close(order.safe_price) self.close(order.safe_price)
else: else:
@ -841,7 +843,7 @@ class LocalTrade():
avg_price = FtPrecise(0.0) avg_price = FtPrecise(0.0)
close_profit = 0.0 close_profit = 0.0
close_profit_abs = 0.0 close_profit_abs = 0.0
profit = None
for o in self.orders: for o in self.orders:
if o.ft_is_open or not o.filled: if o.ft_is_open or not o.filled:
continue continue
@ -868,8 +870,6 @@ class LocalTrade():
close_profit_abs += profit close_profit_abs += profit
close_profit = self.calc_profit_ratio( close_profit = self.calc_profit_ratio(
exit_rate, amount=exit_amount, open_rate=avg_price) exit_rate, amount=exit_amount, open_rate=avg_price)
if current_amount <= ZERO:
profit = close_profit_abs
else: else:
total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price) total_stake = total_stake + self._calc_open_trade_value(tmp_amount, price)
@ -878,8 +878,8 @@ class LocalTrade():
self.realized_profit = close_profit_abs self.realized_profit = close_profit_abs
self.close_profit_abs = profit self.close_profit_abs = profit
current_amount_tr = amount_to_precision(float(current_amount), current_amount_tr = amount_to_contract_precision(
self.amount_precision, self.precision_mode) float(current_amount), self.amount_precision, self.precision_mode, self.contract_size)
if current_amount_tr > 0.0: if current_amount_tr > 0.0:
# Trade is still open # Trade is still open
# Leverage not updated, as we don't allow changing leverage through DCA at the moment. # Leverage not updated, as we don't allow changing leverage through DCA at the moment.
@ -894,6 +894,7 @@ class LocalTrade():
# Close profit abs / maximum owned # Close profit abs / maximum owned
# Fees are considered as they are part of close_profit_abs # Fees are considered as they are part of close_profit_abs
self.close_profit = (close_profit_abs / total_stake) * self.leverage self.close_profit = (close_profit_abs / total_stake) * self.leverage
self.close_profit_abs = close_profit_abs
def select_order_by_order_id(self, order_id: str) -> Optional[Order]: def select_order_by_order_id(self, order_id: str) -> Optional[Order]:
""" """
@ -1044,6 +1045,16 @@ class LocalTrade():
""" """
return Trade.get_trades_proxy(is_open=True) return Trade.get_trades_proxy(is_open=True)
@staticmethod
def get_open_trade_count() -> int:
"""
get open trade count
"""
if Trade.use_db:
return Trade.query.filter(Trade.is_open.is_(True)).count()
else:
return len(LocalTrade.trades_open)
@staticmethod @staticmethod
def stoploss_reinitialization(desired_stoploss): def stoploss_reinitialization(desired_stoploss):
""" """
@ -1132,6 +1143,7 @@ class Trade(_DECL_BASE, LocalTrade):
amount_precision = Column(Float, nullable=True) amount_precision = Column(Float, nullable=True)
price_precision = Column(Float, nullable=True) price_precision = Column(Float, nullable=True)
precision_mode = Column(Integer, nullable=True) precision_mode = Column(Integer, nullable=True)
contract_size = Column(Float, nullable=True)
# Leverage trading properties # Leverage trading properties
leverage = Column(Float, nullable=True, default=1.0) leverage = Column(Float, nullable=True, default=1.0)

View File

@ -51,6 +51,11 @@ class PrecisionFilter(IPairList):
:param ticker: ticker dict as returned from ccxt.fetch_tickers() :param ticker: ticker dict as returned from ccxt.fetch_tickers()
:return: True if the pair can stay, false if it should be removed :return: True if the pair can stay, false if it should be removed
""" """
if ticker.get('last', None) is None:
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 stop_price = ticker['last'] * self._stoploss
# Adjust stop-prices to precision # Adjust stop-prices to precision

View File

@ -73,7 +73,7 @@ class VolumePairList(IPairList):
if (not self._use_range and not ( if (not self._use_range and not (
self._exchange.exchange_has('fetchTickers') self._exchange.exchange_has('fetchTickers')
and self._exchange._ft_has["tickers_have_quoteVolume"])): and self._exchange.get_option("tickers_have_quoteVolume"))):
raise OperationalException( raise OperationalException(
"Exchange does not support dynamic whitelist in this configuration. " "Exchange does not support dynamic whitelist in this configuration. "
"Please edit your config and either remove Volumepairlist, " "Please edit your config and either remove Volumepairlist, "
@ -193,7 +193,7 @@ class VolumePairList(IPairList):
) in candles else None ) in candles else None
# in case of candle data calculate typical price and quoteVolume for candle # in case of candle data calculate typical price and quoteVolume for candle
if pair_candles is not None and not pair_candles.empty: if pair_candles is not None and not pair_candles.empty:
if self._exchange._ft_has["ohlcv_volume_currency"] == "base": if self._exchange.get_option("ohlcv_volume_currency") == "base":
pair_candles['typical_price'] = (pair_candles['high'] + pair_candles['low'] pair_candles['typical_price'] = (pair_candles['high'] + pair_candles['low']
+ pair_candles['close']) / 3 + pair_candles['close']) / 3

View File

@ -193,7 +193,10 @@ class IResolver:
:return: List of dicts containing 'name', 'class' and 'location' entries :return: List of dicts containing 'name', 'class' and 'location' entries
""" """
logger.debug(f"Searching for {cls.object_type.__name__} '{directory}'") logger.debug(f"Searching for {cls.object_type.__name__} '{directory}'")
objects = [] objects: List[Dict[str, Any]] = []
if not directory.is_dir():
logger.info(f"'{directory}' is not a directory, skipping.")
return objects
for entry in directory.iterdir(): for entry in directory.iterdir():
if ( if (
recursive and entry.is_dir() recursive and entry.is_dir()

View File

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

View File

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

View File

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

View File

@ -78,8 +78,8 @@ class IStrategy(ABC, HyperStrategyMixin):
# Optional time in force # Optional time in force
order_time_in_force: Dict = { order_time_in_force: Dict = {
'entry': 'gtc', 'entry': 'GTC',
'exit': 'gtc', 'exit': 'GTC',
} }
# run "populate_indicators" only for new candle # run "populate_indicators" only for new candle

View File

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

View File

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

View File

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

View File

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

View File

@ -30,7 +30,7 @@
"\n", "\n",
"# Initialize empty configuration object\n", "# Initialize empty configuration object\n",
"config = Configuration.from_files([])\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", "# config = Configuration.from_files([\"config.json\"])\n",
"\n", "\n",
"# Define some constants\n", "# Define some constants\n",
@ -38,7 +38,7 @@
"# Name of the strategy class\n", "# Name of the strategy class\n",
"config[\"strategy\"] = \"SampleStrategy\"\n", "config[\"strategy\"] = \"SampleStrategy\"\n",
"# Location of the data\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 to analyze - Only use one pair here\n",
"pair = \"BTC/USDT\"" "pair = \"BTC/USDT\""
] ]
@ -365,7 +365,7 @@
"metadata": { "metadata": {
"file_extension": ".py", "file_extension": ".py",
"kernelspec": { "kernelspec": {
"display_name": "Python 3", "display_name": "Python 3.9.7 64-bit ('trade_397')",
"language": "python", "language": "python",
"name": "python3" "name": "python3"
}, },
@ -379,7 +379,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.8.5" "version": "3.9.7"
}, },
"mimetype": "text/x-python", "mimetype": "text/x-python",
"name": "python", "name": "python",
@ -427,7 +427,12 @@
], ],
"window_display": false "window_display": false
}, },
"version": 3 "version": 3,
"vscode": {
"interpreter": {
"hash": "675f32a300d6d26767470181ad0b11dd4676bcce7ed1dd2ffe2fbc370c95fc7c"
}
}
}, },
"nbformat": 4, "nbformat": 4,
"nbformat_minor": 4 "nbformat_minor": 4

View File

@ -148,7 +148,7 @@ class Wallets:
# Position is not open ... # Position is not open ...
continue continue
size = self._exchange._contracts_to_amount(symbol, position['contracts']) size = self._exchange._contracts_to_amount(symbol, position['contracts'])
collateral = position['collateral'] collateral = position['collateral'] or 0.0
leverage = position['leverage'] leverage = position['leverage']
self._positions[symbol] = PositionWallet( self._positions[symbol] = PositionWallet(
symbol, position=size, symbol, position=size,

View File

@ -17,14 +17,14 @@ pytest-mock==3.8.2
pytest-random-order==1.0.4 pytest-random-order==1.0.4
isort==5.10.1 isort==5.10.1
# For datetime mocking # For datetime mocking
time-machine==2.7.1 time-machine==2.8.1
# Convert jupyter notebooks to markdown documents # Convert jupyter notebooks to markdown documents
nbconvert==6.5.3 nbconvert==7.0.0
# mypy types # mypy types
types-cachetools==5.2.1 types-cachetools==5.2.1
types-filelock==3.2.7 types-filelock==3.2.7
types-requests==2.28.8 types-requests==2.28.9
types-tabulate==0.8.11 types-tabulate==0.8.11
types-python-dateutil==2.8.19 types-python-dateutil==2.8.19

View File

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

View File

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

View File

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

View File

@ -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 | futures |\n" in captured.out
assert "\n| XRP/USDT | 1h, 8h | mark |\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") @pytest.mark.usefixtures("init_persistence")
def test_show_trades(mocker, fee, capsys, caplog): def test_show_trades(mocker, fee, capsys, caplog):

View File

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

View File

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

View File

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

View File

@ -137,6 +137,10 @@ def exchange_futures(request, exchange_conf, class_mocker):
'freqtrade.exchange.binance.Binance.fill_leverage_tiers') 'freqtrade.exchange.binance.Binance.fill_leverage_tiers')
class_mocker.patch('freqtrade.exchange.exchange.Exchange.fetch_trading_fees') 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.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( exchange = ExchangeResolver.load_exchange(
request.param, exchange_conf, validate=True, load_leverage_tiers=True) request.param, exchange_conf, validate=True, load_leverage_tiers=True)
@ -405,14 +409,14 @@ class TestCCXTExchange():
assert (isinstance(futures_leverage, float) or isinstance(futures_leverage, int)) assert (isinstance(futures_leverage, float) or isinstance(futures_leverage, int))
assert futures_leverage >= 1.0 assert futures_leverage >= 1.0
def test_ccxt__get_contract_size(self, exchange_futures): def test_ccxt_get_contract_size(self, exchange_futures):
futures, futures_name = exchange_futures futures, futures_name = exchange_futures
if futures: if futures:
futures_pair = EXCHANGES[futures_name].get( futures_pair = EXCHANGES[futures_name].get(
'futures_pair', 'futures_pair',
EXCHANGES[futures_name]['pair'] EXCHANGES[futures_name]['pair']
) )
contract_size = futures._get_contract_size(futures_pair) contract_size = futures.get_contract_size(futures_pair)
assert (isinstance(contract_size, float) or isinstance(contract_size, int)) assert (isinstance(contract_size, float) or isinstance(contract_size, int))
assert contract_size >= 0.0 assert contract_size >= 0.0
@ -464,6 +468,7 @@ class TestCCXTExchange():
False, False,
100, 100,
100, 100,
100,
) )
assert (isinstance(liquidation_price, float)) assert (isinstance(liquidation_price, float))
assert liquidation_price >= 0.0 assert liquidation_price >= 0.0
@ -474,6 +479,7 @@ class TestCCXTExchange():
False, False,
100, 100,
100, 100,
100,
) )
assert (isinstance(liquidation_price, float)) assert (isinstance(liquidation_price, float))
assert liquidation_price >= 0.0 assert liquidation_price >= 0.0

View File

@ -2,7 +2,6 @@ import copy
import logging import logging
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from math import isclose
from random import randint from random import randint
from unittest.mock import MagicMock, Mock, PropertyMock, patch from unittest.mock import MagicMock, Mock, PropertyMock, patch
@ -181,11 +180,11 @@ def test_init_ccxt_kwargs(default_conf, mocker, caplog):
assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog) assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog)
assert log_has(asynclogmsg, caplog) assert log_has(asynclogmsg, caplog)
# Test additional headers case # Test additional headers case
Exchange._headers = {'hello': 'world'} Exchange._ccxt_params = {'hello': 'world'}
ex = Exchange(conf) ex = Exchange(conf)
assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog) assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog)
assert ex._api.headers == {'hello': 'world'} assert ex._api.hello == 'world'
assert ex._ccxt_config == {} assert ex._ccxt_config == {}
Exchange._headers = {} Exchange._headers = {}
@ -275,7 +274,7 @@ def test_validate_order_time_in_force(default_conf, mocker, caplog):
ex.validate_order_time_in_force(tif2) ex.validate_order_time_in_force(tif2)
# Patch to see if this will pass if the values are in the ft dict # Patch to see if this will pass if the values are in the ft dict
ex._ft_has.update({"order_time_in_force": ["gtc", "fok", "ioc"]}) ex._ft_has.update({"order_time_in_force": ["GTC", "FOK", "IOC"]})
ex.validate_order_time_in_force(tif2) ex.validate_order_time_in_force(tif2)
@ -407,10 +406,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
# min # min
result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss)
expected_result = 2 * (1 + 0.05) / (1 - abs(stoploss)) expected_result = 2 * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss, 3.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss, 3.0)
assert isclose(result, expected_result / 3) assert pytest.approx(result) == expected_result / 3
# max # max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 10000 assert result == 10000
@ -426,10 +425,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss)
expected_result = 2 * 2 * (1 + 0.05) / (1 - abs(stoploss)) expected_result = 2 * 2 * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 5.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 5.0)
assert isclose(result, expected_result / 5) assert pytest.approx(result) == expected_result / 5
# max # max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 20000 assert result == 20000
@ -445,10 +444,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss)
expected_result = max(2, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss)) expected_result = max(2, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 10) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 10)
assert isclose(result, expected_result / 10) assert pytest.approx(result) == expected_result / 10
# min amount and cost are set (amount is minial) # min amount and cost are set (amount is minial)
markets["ETH/BTC"]["limits"] = { markets["ETH/BTC"]["limits"] = {
@ -461,20 +460,20 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss)
expected_result = max(8, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss)) expected_result = max(8, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss))
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 7.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 7.0)
assert isclose(result, expected_result / 7.0) assert pytest.approx(result) == expected_result / 7.0
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 1000 assert result == 1000
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4)
expected_result = max(8, 2 * 2) * 1.5 expected_result = max(8, 2 * 2) * 1.5
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4, 8.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4, 8.0)
assert isclose(result, expected_result / 8.0) assert pytest.approx(result) == expected_result / 8.0
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 1000 assert result == 1000
@ -482,10 +481,10 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
# Really big stoploss # Really big stoploss
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1)
expected_result = max(8, 2 * 2) * 1.5 expected_result = max(8, 2 * 2) * 1.5
assert isclose(result, expected_result) assert pytest.approx(result) == expected_result
# With Leverage # With Leverage
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0)
assert isclose(result, expected_result / 12) assert pytest.approx(result) == expected_result / 12
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 1000 assert result == 1000
@ -501,7 +500,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
# Contract size 0.01 # Contract size 0.01
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1)
assert isclose(result, expected_result * 0.01) assert pytest.approx(result) == expected_result * 0.01
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 10 assert result == 10
@ -513,7 +512,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None:
) )
# With Leverage, Contract size 10 # With Leverage, Contract size 10
result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0)
assert isclose(result, (expected_result / 12) * 10.0) assert pytest.approx(result) == (expected_result / 12) * 10.0
# Max # Max
result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) result = exchange.get_max_pair_stake_amount('ETH/BTC', 2)
assert result == 10000 assert result == 10000
@ -1503,7 +1502,7 @@ def test_buy_considers_time_in_force(default_conf, mocker, exchange_name):
assert api_mock.create_order.call_args[0][3] == 1 assert api_mock.create_order.call_args[0][3] == 1
assert api_mock.create_order.call_args[0][4] == 200 assert api_mock.create_order.call_args[0][4] == 200
assert "timeInForce" in api_mock.create_order.call_args[0][5] assert "timeInForce" in api_mock.create_order.call_args[0][5]
assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force.upper()
order_type = 'market' order_type = 'market'
time_in_force = 'ioc' time_in_force = 'ioc'
@ -1642,10 +1641,10 @@ def test_sell_considers_time_in_force(default_conf, mocker, exchange_name):
assert api_mock.create_order.call_args[0][3] == 1 assert api_mock.create_order.call_args[0][3] == 1
assert api_mock.create_order.call_args[0][4] == 200 assert api_mock.create_order.call_args[0][4] == 200
assert "timeInForce" in api_mock.create_order.call_args[0][5] assert "timeInForce" in api_mock.create_order.call_args[0][5]
assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force.upper()
order_type = 'market' order_type = 'market'
time_in_force = 'ioc' time_in_force = 'IOC'
order = exchange.create_order(pair='ETH/BTC', ordertype=order_type, side="sell", order = exchange.create_order(pair='ETH/BTC', ordertype=order_type, side="sell",
amount=1, rate=200, leverage=1.0, amount=1, rate=200, leverage=1.0,
time_in_force=time_in_force) time_in_force=time_in_force)
@ -2352,10 +2351,11 @@ def test_fetch_l2_order_book(default_conf, mocker, order_book_l2, exchange_name)
order_book = exchange.fetch_l2_order_book(pair='ETH/BTC', limit=val) order_book = exchange.fetch_l2_order_book(pair='ETH/BTC', limit=val)
assert api_mock.fetch_l2_order_book.call_args_list[0][0][0] == 'ETH/BTC' assert api_mock.fetch_l2_order_book.call_args_list[0][0][0] == 'ETH/BTC'
# Not all exchanges support all limits for orderbook # Not all exchanges support all limits for orderbook
if not exchange._ft_has['l2_limit_range'] or val in exchange._ft_has['l2_limit_range']: if (not exchange.get_option('l2_limit_range')
or val in exchange.get_option('l2_limit_range')):
assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == val assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == val
else: else:
next_limit = exchange.get_next_limit_in_list(val, exchange._ft_has['l2_limit_range']) next_limit = exchange.get_next_limit_in_list(val, exchange.get_option('l2_limit_range'))
assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == next_limit assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == next_limit
@ -3238,7 +3238,7 @@ def test_get_trades_for_order(default_conf, mocker, exchange_name, trading_mode,
orders = exchange.get_trades_for_order(order_id, 'ETH/USDT:USDT', since) orders = exchange.get_trades_for_order(order_id, 'ETH/USDT:USDT', since)
assert len(orders) == 1 assert len(orders) == 1
assert orders[0]['price'] == 165 assert orders[0]['price'] == 165
assert isclose(orders[0]['amount'], amount) assert pytest.approx(orders[0]['amount']) == amount
assert api_mock.fetch_my_trades.call_count == 1 assert api_mock.fetch_my_trades.call_count == 1
# since argument should be # since argument should be
assert isinstance(api_mock.fetch_my_trades.call_args[0][1], int) assert isinstance(api_mock.fetch_my_trades.call_args[0][1], int)
@ -3311,16 +3311,16 @@ def test_merge_ft_has_dict(default_conf, mocker):
ex = Kraken(default_conf) ex = Kraken(default_conf)
assert ex._ft_has != Exchange._ft_has_default assert ex._ft_has != Exchange._ft_has_default
assert ex._ft_has['trades_pagination'] == 'id' assert ex.get_option('trades_pagination') == 'id'
assert ex._ft_has['trades_pagination_arg'] == 'since' assert ex.get_option('trades_pagination_arg') == 'since'
# Binance defines different values # Binance defines different values
ex = Binance(default_conf) ex = Binance(default_conf)
assert ex._ft_has != Exchange._ft_has_default assert ex._ft_has != Exchange._ft_has_default
assert ex._ft_has['stoploss_on_exchange'] assert ex.get_option('stoploss_on_exchange')
assert ex._ft_has['order_time_in_force'] == ['gtc', 'fok', 'ioc'] assert ex.get_option('order_time_in_force') == ['GTC', 'FOK', 'IOC']
assert ex._ft_has['trades_pagination'] == 'id' assert ex.get_option('trades_pagination') == 'id'
assert ex._ft_has['trades_pagination_arg'] == 'fromId' assert ex.get_option('trades_pagination_arg') == 'fromId'
conf = copy.deepcopy(default_conf) conf = copy.deepcopy(default_conf)
conf['exchange']['_ft_has_params'] = {"DeadBeef": 20, conf['exchange']['_ft_has_params'] = {"DeadBeef": 20,
@ -3775,8 +3775,8 @@ def test__get_funding_fees_from_exchange(default_conf, mocker, exchange_name):
since=unix_time since=unix_time
) )
assert (isclose(expected_fees, fees_from_datetime)) assert pytest.approx(expected_fees) == fees_from_datetime
assert (isclose(expected_fees, fees_from_unix_time)) assert pytest.approx(expected_fees) == fees_from_unix_time
ccxt_exceptionhandlers( ccxt_exceptionhandlers(
mocker, mocker,
@ -4088,66 +4088,6 @@ def test_combine_funding_and_mark(
assert len(df) == 0 assert len(df) == 0
def test_get_or_calculate_liquidation_price(mocker, default_conf):
api_mock = MagicMock()
positions = [
{
'info': {},
'symbol': 'NEAR/USDT:USDT',
'timestamp': 1642164737148,
'datetime': '2022-01-14T12:52:17.148Z',
'initialMargin': 1.51072,
'initialMarginPercentage': 0.1,
'maintenanceMargin': 0.38916147,
'maintenanceMarginPercentage': 0.025,
'entryPrice': 18.884,
'notional': 15.1072,
'leverage': 9.97,
'unrealizedPnl': 0.0048,
'contracts': 8,
'contractSize': 0.1,
'marginRatio': None,
'liquidationPrice': 17.47,
'markPrice': 18.89,
'margin_mode': 1.52549075,
'marginType': 'isolated',
'side': 'buy',
'percentage': 0.003177292946409658
}
]
api_mock.fetch_positions = MagicMock(return_value=positions)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
exchange_has=MagicMock(return_value=True),
)
default_conf['dry_run'] = False
default_conf['trading_mode'] = 'futures'
default_conf['margin_mode'] = 'isolated'
default_conf['liquidation_buffer'] = 0.0
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_or_calculate_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
position=0.8,
wallet_balance=0.8,
)
assert liq_price == 17.47
default_conf['liquidation_buffer'] = 0.05
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_or_calculate_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
position=0.8,
wallet_balance=0.8,
)
assert liq_price == 17.540699999999998
@pytest.mark.parametrize('exchange,rate_start,rate_end,d1,d2,amount,expected_fees', [ @pytest.mark.parametrize('exchange,rate_start,rate_end,d1,d2,amount,expected_fees', [
('binance', 0, 2, "2021-09-01 01:00:00", "2021-09-01 04:00:00", 30.0, 0.0), ('binance', 0, 2, "2021-09-01 01:00:00", "2021-09-01 04:00:00", 30.0, 0.0),
('binance', 0, 2, "2021-09-01 00:00:00", "2021-09-01 08:00:00", 30.0, -0.00091409999), ('binance', 0, 2, "2021-09-01 00:00:00", "2021-09-01 08:00:00", 30.0, -0.00091409999),
@ -4287,7 +4227,7 @@ def test__fetch_and_calculate_funding_fees_datetime_called(
('XLTCUSDT', 0.01, 'futures'), ('XLTCUSDT', 0.01, 'futures'),
('ETH/USDT:USDT', 10, 'futures') ('ETH/USDT:USDT', 10, 'futures')
]) ])
def test__get_contract_size(mocker, default_conf, pair, expected_size, trading_mode): def est__get_contract_size(mocker, default_conf, pair, expected_size, trading_mode):
api_mock = MagicMock() api_mock = MagicMock()
default_conf['trading_mode'] = trading_mode default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = 'isolated' default_conf['margin_mode'] = 'isolated'
@ -4306,7 +4246,7 @@ def test__get_contract_size(mocker, default_conf, pair, expected_size, trading_m
'contractSize': '10', 'contractSize': '10',
} }
}) })
size = exchange._get_contract_size(pair) size = exchange.get_contract_size(pair)
assert expected_size == size assert expected_size == size
@ -4538,11 +4478,12 @@ def test_liquidation_price_is_none(
default_conf['trading_mode'] = trading_mode default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = margin_mode default_conf['margin_mode'] = margin_mode
exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) exchange = get_patched_exchange(mocker, default_conf, id=exchange_name)
assert exchange.get_or_calculate_liquidation_price( assert exchange.get_liquidation_price(
pair='DOGE/USDT', pair='DOGE/USDT',
open_rate=open_rate, open_rate=open_rate,
is_short=is_short, is_short=is_short,
position=71200.81144, amount=71200.81144,
stake_amount=open_rate * 71200.81144,
wallet_balance=-56354.57, wallet_balance=-56354.57,
mm_ex_1=0.10, mm_ex_1=0.10,
upnl_ex_1=0.0 upnl_ex_1=0.0
@ -4551,7 +4492,7 @@ def test_liquidation_price_is_none(
@pytest.mark.parametrize( @pytest.mark.parametrize(
'exchange_name, is_short, trading_mode, margin_mode, wallet_balance, ' 'exchange_name, is_short, trading_mode, margin_mode, wallet_balance, '
'mm_ex_1, upnl_ex_1, maintenance_amt, position, open_rate, ' 'mm_ex_1, upnl_ex_1, maintenance_amt, amount, open_rate, '
'mm_ratio, expected', 'mm_ratio, expected',
[ [
("binance", False, 'futures', 'isolated', 1535443.01, 0.0, ("binance", False, 'futures', 'isolated', 1535443.01, 0.0,
@ -4565,22 +4506,23 @@ def test_liquidation_price_is_none(
]) ])
def test_liquidation_price( def test_liquidation_price(
mocker, default_conf, exchange_name, open_rate, is_short, trading_mode, mocker, default_conf, exchange_name, open_rate, is_short, trading_mode,
margin_mode, wallet_balance, mm_ex_1, upnl_ex_1, maintenance_amt, position, mm_ratio, expected margin_mode, wallet_balance, mm_ex_1, upnl_ex_1, maintenance_amt, amount, mm_ratio, expected
): ):
default_conf['trading_mode'] = trading_mode default_conf['trading_mode'] = trading_mode
default_conf['margin_mode'] = margin_mode default_conf['margin_mode'] = margin_mode
default_conf['liquidation_buffer'] = 0.0 default_conf['liquidation_buffer'] = 0.0
exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) exchange = get_patched_exchange(mocker, default_conf, id=exchange_name)
exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(mm_ratio, maintenance_amt)) exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(mm_ratio, maintenance_amt))
assert isclose(round(exchange.get_or_calculate_liquidation_price( assert pytest.approx(round(exchange.get_liquidation_price(
pair='DOGE/USDT', pair='DOGE/USDT',
open_rate=open_rate, open_rate=open_rate,
is_short=is_short, is_short=is_short,
wallet_balance=wallet_balance, wallet_balance=wallet_balance,
mm_ex_1=mm_ex_1, mm_ex_1=mm_ex_1,
upnl_ex_1=upnl_ex_1, upnl_ex_1=upnl_ex_1,
position=position, amount=amount,
), 2), expected) stake_amount=open_rate * amount,
), 2)) == expected
def test_get_max_pair_stake_amount( def test_get_max_pair_stake_amount(
@ -4791,6 +4733,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): def test_parse_leverage_tier(mocker, default_conf):
exchange = get_patched_exchange(mocker, default_conf) exchange = get_patched_exchange(mocker, default_conf)
@ -4811,10 +4767,10 @@ def test_parse_leverage_tier(mocker, default_conf):
} }
assert exchange.parse_leverage_tier(tier) == { assert exchange.parse_leverage_tier(tier) == {
"min": 0, "minNotional": 0,
"max": 100000, "maxNotional": 100000,
"mmr": 0.025, "maintenanceMarginRate": 0.025,
"lev": 20, "maxLeverage": 20,
"maintAmt": 0.0, "maintAmt": 0.0,
} }
@ -4840,10 +4796,10 @@ def test_parse_leverage_tier(mocker, default_conf):
} }
assert exchange.parse_leverage_tier(tier2) == { assert exchange.parse_leverage_tier(tier2) == {
'min': 0, 'minNotional': 0,
'max': 2000, 'maxNotional': 2000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 75, 'maxLeverage': 75,
"maintAmt": None, "maintAmt": None,
} }
@ -4911,8 +4867,8 @@ def test_get_max_leverage_futures(default_conf, mocker, leverage_tiers):
assert exchange.get_max_leverage("BNB/BUSD", 1.0) == 20.0 assert exchange.get_max_leverage("BNB/BUSD", 1.0) == 20.0
assert exchange.get_max_leverage("BNB/USDT", 100.0) == 75.0 assert exchange.get_max_leverage("BNB/USDT", 100.0) == 75.0
assert exchange.get_max_leverage("BTC/USDT", 170.30) == 125.0 assert exchange.get_max_leverage("BTC/USDT", 170.30) == 125.0
assert isclose(exchange.get_max_leverage("BNB/BUSD", 99999.9), 5.000005) assert pytest.approx(exchange.get_max_leverage("BNB/BUSD", 99999.9)) == 5.000005
assert isclose(exchange.get_max_leverage("BNB/USDT", 1500), 33.333333333333333) assert pytest.approx(exchange.get_max_leverage("BNB/USDT", 1500)) == 33.333333333333333
assert exchange.get_max_leverage("BTC/USDT", 300000000) == 2.0 assert exchange.get_max_leverage("BTC/USDT", 300000000) == 2.0
assert exchange.get_max_leverage("BTC/USDT", 600000000) == 1.0 # Last tier assert exchange.get_max_leverage("BTC/USDT", 600000000) == 1.0 # Last tier
@ -4935,7 +4891,7 @@ def test__get_params(mocker, default_conf, exchange_name):
params1 = {'test': True} params1 = {'test': True}
params2 = { params2 = {
'test': True, 'test': True,
'timeInForce': 'ioc', 'timeInForce': 'IOC',
'reduceOnly': True, 'reduceOnly': True,
} }
@ -4950,7 +4906,7 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='market', ordertype='market',
reduceOnly=False, reduceOnly=False,
time_in_force='gtc', time_in_force='GTC',
leverage=1.0, leverage=1.0,
) == params1 ) == params1
@ -4958,7 +4914,7 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='market', ordertype='market',
reduceOnly=False, reduceOnly=False,
time_in_force='ioc', time_in_force='IOC',
leverage=1.0, leverage=1.0,
) == params1 ) == params1
@ -4966,7 +4922,7 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='limit', ordertype='limit',
reduceOnly=False, reduceOnly=False,
time_in_force='gtc', time_in_force='GTC',
leverage=1.0, leverage=1.0,
) == params1 ) == params1
@ -4979,11 +4935,93 @@ def test__get_params(mocker, default_conf, exchange_name):
side="buy", side="buy",
ordertype='limit', ordertype='limit',
reduceOnly=True, reduceOnly=True,
time_in_force='ioc', time_in_force='IOC',
leverage=3.0, leverage=3.0,
) == params2 ) == params2
def test_get_liquidation_price1(mocker, default_conf):
api_mock = MagicMock()
positions = [
{
'info': {},
'symbol': 'NEAR/USDT:USDT',
'timestamp': 1642164737148,
'datetime': '2022-01-14T12:52:17.148Z',
'initialMargin': 1.51072,
'initialMarginPercentage': 0.1,
'maintenanceMargin': 0.38916147,
'maintenanceMarginPercentage': 0.025,
'entryPrice': 18.884,
'notional': 15.1072,
'leverage': 9.97,
'unrealizedPnl': 0.0048,
'contracts': 8,
'contractSize': 0.1,
'marginRatio': None,
'liquidationPrice': 17.47,
'markPrice': 18.89,
'margin_mode': 1.52549075,
'marginType': 'isolated',
'side': 'buy',
'percentage': 0.003177292946409658
}
]
api_mock.fetch_positions = MagicMock(return_value=positions)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
exchange_has=MagicMock(return_value=True),
)
default_conf['dry_run'] = False
default_conf['trading_mode'] = 'futures'
default_conf['margin_mode'] = 'isolated'
default_conf['liquidation_buffer'] = 0.0
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
)
assert liq_price == 17.47
default_conf['liquidation_buffer'] = 0.05
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
)
assert liq_price == 17.540699999999998
api_mock.fetch_positions = MagicMock(return_value=[])
exchange = get_patched_exchange(mocker, default_conf, api_mock)
liq_price = exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
)
assert liq_price is None
default_conf['trading_mode'] = 'margin'
exchange = get_patched_exchange(mocker, default_conf, api_mock)
with pytest.raises(OperationalException, match=r'.*does not support .* margin'):
exchange.get_liquidation_price(
pair='NEAR/USDT:USDT',
open_rate=18.884,
is_short=False,
amount=0.8,
stake_amount=18.884 * 0.8,
)
@pytest.mark.parametrize('liquidation_buffer', [0.0, 0.05]) @pytest.mark.parametrize('liquidation_buffer', [0.0, 0.05])
@pytest.mark.parametrize( @pytest.mark.parametrize(
"is_short,trading_mode,exchange_name,margin_mode,leverage,open_rate,amount,expected_liq", [ "is_short,trading_mode,exchange_name,margin_mode,leverage,open_rate,amount,expected_liq", [
@ -4997,22 +5035,22 @@ def test__get_params(mocker, default_conf, exchange_name):
(True, 'futures', 'binance', 'isolated', 5.0, 10.0, 1.0, 11.89108910891089), (True, 'futures', 'binance', 'isolated', 5.0, 10.0, 1.0, 11.89108910891089),
(True, 'futures', 'binance', 'isolated', 3.0, 10.0, 1.0, 13.211221122079207), (True, 'futures', 'binance', 'isolated', 3.0, 10.0, 1.0, 13.211221122079207),
(True, 'futures', 'binance', 'isolated', 5.0, 8.0, 1.0, 9.514851485148514), (True, 'futures', 'binance', 'isolated', 5.0, 8.0, 1.0, 9.514851485148514),
(True, 'futures', 'binance', 'isolated', 5.0, 10.0, 0.6, 12.557755775577558), (True, 'futures', 'binance', 'isolated', 5.0, 10.0, 0.6, 11.897689768976898),
# Binance, long # Binance, long
(False, 'futures', 'binance', 'isolated', 5, 10, 1.0, 8.070707070707071), (False, 'futures', 'binance', 'isolated', 5, 10, 1.0, 8.070707070707071),
(False, 'futures', 'binance', 'isolated', 5, 8, 1.0, 6.454545454545454), (False, 'futures', 'binance', 'isolated', 5, 8, 1.0, 6.454545454545454),
(False, 'futures', 'binance', 'isolated', 3, 10, 1.0, 6.717171717171718), (False, 'futures', 'binance', 'isolated', 3, 10, 1.0, 6.723905723905723),
(False, 'futures', 'binance', 'isolated', 5, 10, 0.6, 7.39057239057239), (False, 'futures', 'binance', 'isolated', 5, 10, 0.6, 8.063973063973064),
# Gateio/okx, short # Gateio/okx, short
(True, 'futures', 'gateio', 'isolated', 5, 10, 1.0, 11.87413417771621), (True, 'futures', 'gateio', 'isolated', 5, 10, 1.0, 11.87413417771621),
(True, 'futures', 'gateio', 'isolated', 5, 10, 2.0, 11.87413417771621), (True, 'futures', 'gateio', 'isolated', 5, 10, 2.0, 11.87413417771621),
(True, 'futures', 'gateio', 'isolated', 3, 10, 1.0, 13.476180850346978), (True, 'futures', 'gateio', 'isolated', 3, 10, 1.0, 13.193482419684678),
(True, 'futures', 'gateio', 'isolated', 5, 8, 1.0, 9.499307342172967), (True, 'futures', 'gateio', 'isolated', 5, 8, 1.0, 9.499307342172967),
(True, 'futures', 'okx', 'isolated', 3, 10, 1.0, 13.193482419684678),
# Gateio/okx, long # Gateio/okx, long
(False, 'futures', 'gateio', 'isolated', 5.0, 10.0, 1.0, 8.085708510208207), (False, 'futures', 'gateio', 'isolated', 5.0, 10.0, 1.0, 8.085708510208207),
(False, 'futures', 'gateio', 'isolated', 3.0, 10.0, 1.0, 6.738090425173506), (False, 'futures', 'gateio', 'isolated', 3.0, 10.0, 1.0, 6.738090425173506),
# (True, 'futures', 'okx', 'isolated', 11.87413417771621), (False, 'futures', 'okx', 'isolated', 3.0, 10.0, 1.0, 6.738090425173506),
# (False, 'futures', 'okx', 'isolated', 8.085708510208207),
] ]
) )
def test_get_liquidation_price( def test_get_liquidation_price(
@ -5085,7 +5123,7 @@ def test_get_liquidation_price(
default_conf_usdt['exchange']['name'] = exchange_name default_conf_usdt['exchange']['name'] = exchange_name
default_conf_usdt['margin_mode'] = margin_mode default_conf_usdt['margin_mode'] = margin_mode
mocker.patch('freqtrade.exchange.Gateio.validate_ordertypes') mocker.patch('freqtrade.exchange.Gateio.validate_ordertypes')
exchange = get_patched_exchange(mocker, default_conf_usdt) exchange = get_patched_exchange(mocker, default_conf_usdt, id=exchange_name)
exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(0.01, 0.01)) exchange.get_maintenance_ratio_and_amt = MagicMock(return_value=(0.01, 0.01))
exchange.name = exchange_name exchange.name = exchange_name
@ -5096,7 +5134,9 @@ def test_get_liquidation_price(
pair='ETH/USDT:USDT', pair='ETH/USDT:USDT',
open_rate=open_rate, open_rate=open_rate,
amount=amount, amount=amount,
leverage=leverage, stake_amount=amount * open_rate / leverage,
wallet_balance=amount * open_rate / leverage,
# leverage=leverage,
is_short=is_short, is_short=is_short,
) )
if expected_liq is None: if expected_liq is None:
@ -5104,7 +5144,7 @@ def test_get_liquidation_price(
else: else:
buffer_amount = liquidation_buffer * abs(open_rate - expected_liq) buffer_amount = liquidation_buffer * abs(open_rate - expected_liq)
expected_liq = expected_liq - buffer_amount if is_short else expected_liq + buffer_amount expected_liq = expected_liq - buffer_amount if is_short else expected_liq + buffer_amount
isclose(expected_liq, liq) assert pytest.approx(expected_liq) == liq
@pytest.mark.parametrize('contract_size,order_amount', [ @pytest.mark.parametrize('contract_size,order_amount', [
@ -5131,7 +5171,7 @@ def test_stoploss_contract_size(mocker, default_conf, contract_size, order_amoun
mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y)
exchange = get_patched_exchange(mocker, default_conf, api_mock) exchange = get_patched_exchange(mocker, default_conf, api_mock)
exchange._get_contract_size = MagicMock(return_value=contract_size) exchange.get_contract_size = MagicMock(return_value=contract_size)
api_mock.create_order.reset_mock() api_mock.create_order.reset_mock()
order = exchange.stoploss( order = exchange.stoploss(

View File

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

View File

@ -1,4 +1,5 @@
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import MagicMock, PropertyMock from unittest.mock import MagicMock, PropertyMock
import pytest import pytest
@ -6,7 +7,7 @@ import pytest
from freqtrade.enums import MarginMode, TradingMode from freqtrade.enums import MarginMode, TradingMode
from freqtrade.enums.candletype import CandleType from freqtrade.enums.candletype import CandleType
from freqtrade.exchange.exchange import timeframe_to_minutes 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 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") "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() api_mock = MagicMock()
type(api_mock).has = PropertyMock(return_value={ type(api_mock).has = PropertyMock(return_value={
'fetchLeverageTiers': False, 'fetchLeverageTiers': False,
@ -410,48 +414,66 @@ def test_load_leverage_tiers_okx(default_conf, mocker, markets):
assert exchange._leverage_tiers == { assert exchange._leverage_tiers == {
'ADA/USDT:USDT': [ 'ADA/USDT:USDT': [
{ {
'min': 0, 'minNotional': 0,
'max': 500, 'maxNotional': 500,
'mmr': 0.02, 'maintenanceMarginRate': 0.02,
'lev': 75, 'maxLeverage': 75,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 501, 'minNotional': 501,
'max': 1000, 'maxNotional': 1000,
'mmr': 0.025, 'maintenanceMarginRate': 0.025,
'lev': 50, 'maxLeverage': 50,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 1001, 'minNotional': 1001,
'max': 2000, 'maxNotional': 2000,
'mmr': 0.03, 'maintenanceMarginRate': 0.03,
'lev': 20, 'maxLeverage': 20,
'maintAmt': None 'maintAmt': None
}, },
], ],
'ETH/USDT:USDT': [ 'ETH/USDT:USDT': [
{ {
'min': 0, 'minNotional': 0,
'max': 2000, 'maxNotional': 2000,
'mmr': 0.01, 'maintenanceMarginRate': 0.01,
'lev': 75, 'maxLeverage': 75,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 2001, 'minNotional': 2001,
'max': 4000, 'maxNotional': 4000,
'mmr': 0.015, 'maintenanceMarginRate': 0.015,
'lev': 50, 'maxLeverage': 50,
'maintAmt': None 'maintAmt': None
}, },
{ {
'min': 4001, 'minNotional': 4001,
'max': 8000, 'maxNotional': 8000,
'mmr': 0.02, 'maintenanceMarginRate': 0.02,
'lev': 20, 'maxLeverage': 20,
'maintAmt': None 'maintAmt': None
}, },
], ],
} }
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)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -366,6 +366,9 @@ def test_VolumePairList_refresh_empty(mocker, markets_empty, whitelist_conf):
([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"}, ([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"},
{"method": "PrecisionFilter"}], {"method": "PrecisionFilter"}],
"BTC", ['ETH/BTC', 'TKN/BTC', 'LTC/BTC', 'XRP/BTC']), "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 # PriceFilter and VolumePairList
([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"}, ([{"method": "VolumePairList", "number_assets": 5, "sort_key": "quoteVolume"},
{"method": "PriceFilter", "low_price_ratio": 0.03}], {"method": "PriceFilter", "low_price_ratio": 0.03}],

View File

@ -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.close(open_rate * (2 - profit_rate if is_short else profit_rate))
trade.exit_reason = exit_reason trade.exit_reason = exit_reason
Trade.query.session.add(trade)
Trade.commit()
return trade return trade
@ -125,33 +127,33 @@ def test_stoploss_guard(mocker, default_conf, fee, caplog, is_short):
assert not log_has_re(message, caplog) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=200, min_ago_close=30, is_short=is_short, min_ago_open=200, min_ago_close=30, is_short=is_short,
)) )
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not log_has_re(message, caplog) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
# This trade does not count, as it's closed too long ago # 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, 'BCH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=250, min_ago_close=100, is_short=is_short, 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, 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=240, min_ago_close=30, is_short=is_short, min_ago_open=240, min_ago_close=30, is_short=is_short,
)) )
# 3 Trades closed - but the 2nd has been closed too long ago. # 3 Trades closed - but the 2nd has been closed too long ago.
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not log_has_re(message, caplog) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
'LTC/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, 'LTC/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=180, min_ago_close=30, is_short=is_short, min_ago_open=180, min_ago_close=30, is_short=is_short,
)) )
assert freqtrade.protections.global_stop() assert freqtrade.protections.global_stop()
assert log_has_re(message, caplog) 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) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
pair, fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, 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 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.stop_per_pair(pair)
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not log_has_re(message, caplog) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
# This trade does not count, as it's closed too long ago # 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, 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 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 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, '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 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. # 3 Trades closed - but the 2nd has been closed too long ago.
assert not freqtrade.protections.stop_per_pair(pair) assert not freqtrade.protections.stop_per_pair(pair)
assert freqtrade.protections.global_stop() != only_per_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() caplog.clear()
# Trade does not count potentially, as it's in the wrong direction # 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, 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 min_ago_open=150, min_ago_close=25, profit_rate=0.9, is_short=not is_short
)) )
freqtrade.protections.stop_per_pair(pair) freqtrade.protections.stop_per_pair(pair)
assert freqtrade.protections.global_stop() != only_per_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) 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() caplog.clear()
# 2nd Trade that counts with correct pair # 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, 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 min_ago_open=180, min_ago_close=30, profit_rate=0.9, is_short=is_short
)) )
freqtrade.protections.stop_per_pair(pair) freqtrade.protections.stop_per_pair(pair)
assert freqtrade.protections.global_stop() != only_per_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) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=200, min_ago_close=30, min_ago_open=200, min_ago_close=30,
)) )
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert freqtrade.protections.stop_per_pair('XRP/BTC') assert freqtrade.protections.stop_per_pair('XRP/BTC')
assert PairLocks.is_pair_locked('XRP/BTC') assert PairLocks.is_pair_locked('XRP/BTC')
assert not PairLocks.is_global_lock() 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, 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value,
min_ago_open=205, min_ago_close=35, min_ago_open=205, min_ago_close=35,
)) )
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not PairLocks.is_pair_locked('ETH/BTC') 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) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=800, min_ago_close=450, profit_rate=0.9, min_ago_open=800, min_ago_close=450, profit_rate=0.9,
)) )
Trade.commit() Trade.commit()
# Not locked with 1 trade # 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_pair_locked('XRP/BTC')
assert not PairLocks.is_global_lock() 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, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=200, min_ago_close=120, profit_rate=0.9, min_ago_open=200, min_ago_close=120, profit_rate=0.9,
)) )
Trade.commit() Trade.commit()
# Not locked with 1 trade (first trade is outside of lookback_period) # 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() assert not PairLocks.is_global_lock()
# Add positive trade # Add positive trade
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
'XRP/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value, '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 min_ago_open=20, min_ago_close=10, profit_rate=1.15, is_short=True
)) )
Trade.commit() Trade.commit()
assert freqtrade.protections.stop_per_pair('XRP/BTC') != only_per_side assert freqtrade.protections.stop_per_pair('XRP/BTC') != only_per_side
assert not PairLocks.is_pair_locked('XRP/BTC', side='*') assert not PairLocks.is_pair_locked('XRP/BTC', side='*')
assert PairLocks.is_pair_locked('XRP/BTC', side='long') == only_per_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, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=110, min_ago_close=21, profit_rate=0.8, min_ago_open=110, min_ago_close=21, profit_rate=0.8,
)) )
Trade.commit() Trade.commit()
# Locks due to 2nd trade # 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') assert not freqtrade.protections.stop_per_pair('XRP/BTC')
caplog.clear() caplog.clear()
Trade.query.session.add(generate_mock_trade( generate_mock_trade(
'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=1000, min_ago_close=900, profit_rate=1.1, 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, 'ETH/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=1000, min_ago_close=900, profit_rate=1.1, 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, 'NEO/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=1000, min_ago_close=900, profit_rate=1.1, min_ago_open=1000, min_ago_close=900, profit_rate=1.1,
)) )
Trade.commit()
# No losing trade yet ... so max_drawdown will raise exception # No losing trade yet ... so max_drawdown will raise exception
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not freqtrade.protections.stop_per_pair('XRP/BTC') 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, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=500, min_ago_close=400, profit_rate=0.9, min_ago_open=500, min_ago_close=400, profit_rate=0.9,
)) )
# Not locked with one trade # Not locked with one trade
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not freqtrade.protections.stop_per_pair('XRP/BTC') assert not freqtrade.protections.stop_per_pair('XRP/BTC')
assert not PairLocks.is_pair_locked('XRP/BTC') assert not PairLocks.is_pair_locked('XRP/BTC')
assert not PairLocks.is_global_lock() 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, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.STOP_LOSS.value,
min_ago_open=1200, min_ago_close=1100, profit_rate=0.5, 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) # Not locked with 1 trade (2nd trade is outside of lookback_period)
assert not freqtrade.protections.global_stop() 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) assert not log_has_re(message, caplog)
# Winning trade ... (should not lock, does not change drawdown!) # 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, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value,
min_ago_open=320, min_ago_close=410, profit_rate=1.5, min_ago_open=320, min_ago_close=410, profit_rate=1.5,
)) )
Trade.commit()
assert not freqtrade.protections.global_stop() assert not freqtrade.protections.global_stop()
assert not PairLocks.is_global_lock() assert not PairLocks.is_global_lock()
caplog.clear() caplog.clear()
# Add additional negative trade, causing a loss of > 15% # 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, 'XRP/BTC', fee.return_value, False, exit_reason=ExitType.ROI.value,
min_ago_open=20, min_ago_close=10, profit_rate=0.8, min_ago_open=20, min_ago_close=10, profit_rate=0.8,
)) )
Trade.commit()
assert not freqtrade.protections.stop_per_pair('XRP/BTC') assert not freqtrade.protections.stop_per_pair('XRP/BTC')
# local lock not supported # local lock not supported
assert not PairLocks.is_pair_locked('XRP/BTC') assert not PairLocks.is_pair_locked('XRP/BTC')

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -48,6 +48,10 @@ def test_search_all_strategies_with_failed():
assert len([x for x in strategies if x['class'] is not None]) == 9 assert len([x for x in strategies if x['class'] is not None]) == 9
assert len([x for x in strategies if x['class'] is None]) == 1 assert len([x for x in strategies if x['class'] is None]) == 1
directory = Path(__file__).parent / "strats_nonexistingdir"
strategies = StrategyResolver.search_all_objects(directory, enum_failed=True)
assert len(strategies) == 0
def test_load_strategy(default_conf, result): def test_load_strategy(default_conf, result):
default_conf.update({'strategy': 'SampleStrategy', default_conf.update({'strategy': 'SampleStrategy',
@ -271,8 +275,8 @@ def test_strategy_override_order_tif(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
order_time_in_force = { order_time_in_force = {
'entry': 'fok', 'entry': 'FOK',
'exit': 'gtc', 'exit': 'GTC',
} }
default_conf.update({ default_conf.update({
@ -286,11 +290,11 @@ def test_strategy_override_order_tif(caplog, default_conf):
assert strategy.order_time_in_force[method] == order_time_in_force[method] assert strategy.order_time_in_force[method] == order_time_in_force[method]
assert log_has("Override strategy 'order_time_in_force' with value in config file:" assert log_has("Override strategy 'order_time_in_force' with value in config file:"
" {'entry': 'fok', 'exit': 'gtc'}.", caplog) " {'entry': 'FOK', 'exit': 'GTC'}.", caplog)
default_conf.update({ default_conf.update({
'strategy': CURRENT_TEST_STRATEGY, 'strategy': CURRENT_TEST_STRATEGY,
'order_time_in_force': {'entry': 'fok'} 'order_time_in_force': {'entry': 'FOK'}
}) })
# Raise error for invalid configuration # Raise error for invalid configuration
with pytest.raises(ImportError, with pytest.raises(ImportError,

View File

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

View File

@ -473,8 +473,6 @@ def test_create_trade_no_signal(default_conf_usdt, fee, mocker) -> None:
freqtrade = FreqtradeBot(default_conf_usdt) freqtrade = FreqtradeBot(default_conf_usdt)
patch_get_signal(freqtrade, enter_long=False, exit_long=False) patch_get_signal(freqtrade, enter_long=False, exit_long=False)
Trade.query = MagicMock()
Trade.query.filter = MagicMock()
assert not freqtrade.create_trade('ETH/USDT') assert not freqtrade.create_trade('ETH/USDT')
@ -677,6 +675,7 @@ def test_process_trade_no_whitelist_pair(default_conf_usdt, ticker_usdt, limit_b
open_rate=0.001, open_rate=0.001,
exchange='binance', exchange='binance',
)) ))
Trade.commit()
assert pair not in freqtrade.active_pair_whitelist assert pair not in freqtrade.active_pair_whitelist
freqtrade.process() freqtrade.process()
@ -1052,8 +1051,6 @@ def test_add_stoploss_on_exchange(mocker, default_conf_usdt, limit_order, is_sho
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True)) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True))
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order) mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[]) mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[])
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount',
return_value=order['amount'])
stoploss = MagicMock(return_value={'id': 13434334}) stoploss = MagicMock(return_value={'id': 13434334})
mocker.patch('freqtrade.exchange.Binance.stoploss', stoploss) mocker.patch('freqtrade.exchange.Binance.stoploss', stoploss)
@ -1876,8 +1873,6 @@ def test_exit_positions(mocker, default_conf_usdt, limit_order, is_short, caplog
mocker.patch('freqtrade.exchange.Exchange.fetch_order', mocker.patch('freqtrade.exchange.Exchange.fetch_order',
return_value=limit_order[entry_side(is_short)]) return_value=limit_order[entry_side(is_short)])
mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[]) mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[])
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount',
return_value=limit_order[entry_side(is_short)]['amount'])
trade = MagicMock() trade = MagicMock()
trade.is_short = is_short trade.is_short = is_short
@ -1887,14 +1882,13 @@ def test_exit_positions(mocker, default_conf_usdt, limit_order, is_short, caplog
n = freqtrade.exit_positions(trades) n = freqtrade.exit_positions(trades)
assert n == 0 assert n == 0
# Test amount not modified by fee-logic # Test amount not modified by fee-logic
assert not log_has( assert not log_has_re(r'Applying fee to amount for Trade .*', caplog)
'Applying fee to amount for Trade {} from 30.0 to 90.81'.format(trade), caplog
)
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=90.81) gra = mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=0.0)
# test amount modified by fee-logic # test amount modified by fee-logic
n = freqtrade.exit_positions(trades) n = freqtrade.exit_positions(trades)
assert n == 0 assert n == 0
assert gra.call_count == 0
@pytest.mark.parametrize("is_short", [False, True]) @pytest.mark.parametrize("is_short", [False, True])
@ -1928,8 +1922,7 @@ def test_update_trade_state(mocker, default_conf_usdt, limit_order, is_short, ca
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True)) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True))
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order) mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[]) mocker.patch('freqtrade.exchange.Exchange.get_trades_for_order', return_value=[])
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=0.0)
return_value=order['amount'])
order_id = order['id'] order_id = order['id']
trade = Trade( trade = Trade(
@ -1961,11 +1954,11 @@ def test_update_trade_state(mocker, default_conf_usdt, limit_order, is_short, ca
assert trade.amount == order['amount'] assert trade.amount == order['amount']
trade.open_order_id = order_id trade.open_order_id = order_id
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=90.81) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_real_amount', return_value=0.01)
assert trade.amount != 90.81 assert trade.amount == 30.0
# test amount modified by fee-logic # test amount modified by fee-logic
freqtrade.update_trade_state(trade, order_id) freqtrade.update_trade_state(trade, order_id)
assert trade.amount == 90.81 assert trade.amount == 29.99
assert trade.open_order_id is None assert trade.open_order_id is None
trade.is_open = True trade.is_open = True
@ -2414,6 +2407,7 @@ def test_manage_open_orders_entry_usercustom(
open_trade.orders[0].side = 'sell' if is_short else 'buy' open_trade.orders[0].side = 'sell' if is_short else 'buy'
open_trade.orders[0].ft_order_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.query.session.add(open_trade)
Trade.commit()
# Ensure default is to return empty (so not mocked yet) # Ensure default is to return empty (so not mocked yet)
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -2472,6 +2466,7 @@ def test_manage_open_orders_entry(
open_trade.is_short = is_short open_trade.is_short = is_short
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False) freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False)
freqtrade.strategy.adjust_entry_price = MagicMock(return_value=1234) freqtrade.strategy.adjust_entry_price = MagicMock(return_value=1234)
@ -2509,6 +2504,7 @@ def test_adjust_entry_cancel(
open_trade.is_short = is_short open_trade.is_short = is_short
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# Timeout to not interfere # Timeout to not interfere
freqtrade.strategy.ft_check_timed_out = MagicMock(return_value=False) freqtrade.strategy.ft_check_timed_out = MagicMock(return_value=False)
@ -2549,6 +2545,7 @@ def test_adjust_entry_maintain_replace(
open_trade.is_short = is_short open_trade.is_short = is_short
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# Timeout to not interfere # Timeout to not interfere
freqtrade.strategy.ft_check_timed_out = MagicMock(return_value=False) freqtrade.strategy.ft_check_timed_out = MagicMock(return_value=False)
@ -2601,6 +2598,7 @@ def test_check_handle_cancelled_buy(
open_trade.orders = [] open_trade.orders = []
open_trade.is_short = is_short open_trade.is_short = is_short
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# check it does cancel buy orders over the time limit # check it does cancel buy orders over the time limit
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -2631,6 +2629,7 @@ def test_manage_open_orders_buy_exception(
open_trade.is_short = is_short open_trade.is_short = is_short
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# check it does cancel buy orders over the time limit # check it does cancel buy orders over the time limit
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -2672,6 +2671,7 @@ def test_manage_open_orders_exit_usercustom(
open_trade_usdt.is_open = False open_trade_usdt.is_open = False
Trade.query.session.add(open_trade_usdt) Trade.query.session.add(open_trade_usdt)
Trade.commit()
# Ensure default is false # Ensure default is false
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
assert cancel_order_mock.call_count == 0 assert cancel_order_mock.call_count == 0
@ -2754,6 +2754,7 @@ def test_manage_open_orders_exit(
open_trade_usdt.is_short = is_short open_trade_usdt.is_short = is_short
Trade.query.session.add(open_trade_usdt) Trade.query.session.add(open_trade_usdt)
Trade.commit()
freqtrade.strategy.check_exit_timeout = MagicMock(return_value=False) freqtrade.strategy.check_exit_timeout = MagicMock(return_value=False)
freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False) freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False)
@ -2794,6 +2795,7 @@ def test_check_handle_cancelled_exit(
open_trade_usdt.is_short = is_short open_trade_usdt.is_short = is_short
Trade.query.session.add(open_trade_usdt) Trade.query.session.add(open_trade_usdt)
Trade.commit()
# check it does cancel sell orders over the time limit # check it does cancel sell orders over the time limit
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -2830,6 +2832,7 @@ def test_manage_open_orders_partial(
freqtrade = FreqtradeBot(default_conf_usdt) freqtrade = FreqtradeBot(default_conf_usdt)
prior_stake = open_trade.stake_amount prior_stake = open_trade.stake_amount
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# check it does cancel buy orders over the time limit # check it does cancel buy orders over the time limit
# note this is for a partially-complete buy order # note this is for a partially-complete buy order
@ -2874,6 +2877,7 @@ def test_manage_open_orders_partial_fee(
open_trade.fee_open = fee() open_trade.fee_open = fee()
open_trade.fee_close = fee() open_trade.fee_close = fee()
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# cancelling a half-filled order should update the amount to the bought amount # cancelling a half-filled order should update the amount to the bought amount
# and apply fees if necessary. # and apply fees if necessary.
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -2923,6 +2927,7 @@ def test_manage_open_orders_partial_except(
open_trade.fee_open = fee() open_trade.fee_open = fee()
open_trade.fee_close = fee() open_trade.fee_close = fee()
Trade.query.session.add(open_trade) Trade.query.session.add(open_trade)
Trade.commit()
# cancelling a half-filled order should update the amount to the bought amount # cancelling a half-filled order should update the amount to the bought amount
# and apply fees if necessary. # and apply fees if necessary.
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -2961,6 +2966,7 @@ def test_manage_open_orders_exception(default_conf_usdt, ticker_usdt, open_trade
freqtrade = FreqtradeBot(default_conf_usdt) freqtrade = FreqtradeBot(default_conf_usdt)
Trade.query.session.add(open_trade_usdt) Trade.query.session.add(open_trade_usdt)
Trade.commit()
caplog.clear() caplog.clear()
freqtrade.manage_open_orders() freqtrade.manage_open_orders()
@ -4256,10 +4262,10 @@ def test_get_real_amount_quote(default_conf_usdt, trades_for_order, buy_order_fe
caplog.clear() caplog.clear()
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount is reduced by "fee" # Amount is reduced by "fee"
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == amount - (amount * 0.001) assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == (amount * 0.001)
assert log_has( assert log_has(
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, is_short=False,' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, is_short=False,'
' leverage=1.0, open_rate=0.24544100, open_since=closed) (from 8.0 to 7.992).', ' leverage=1.0, open_rate=0.24544100, open_since=closed), fee=0.008.',
caplog caplog
) )
@ -4284,7 +4290,7 @@ def test_get_real_amount_quote_dust(default_conf_usdt, trades_for_order, buy_ord
walletmock.reset_mock() walletmock.reset_mock()
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount is kept as is # Amount is kept as is
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == amount assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) is None
assert walletmock.call_count == 1 assert walletmock.call_count == 1
assert log_has_re(r'Fee amount for Trade.* was in base currency ' assert log_has_re(r'Fee amount for Trade.* was in base currency '
'- Eating Fee 0.008 into dust', caplog) '- Eating Fee 0.008 into dust', caplog)
@ -4307,7 +4313,7 @@ def test_get_real_amount_no_trade(default_conf_usdt, buy_order_fee, caplog, mock
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount is reduced by "fee" # Amount is reduced by "fee"
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == amount assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) is None
assert log_has( assert log_has(
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, ' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, '
'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) failed: ' 'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) failed: '
@ -4331,8 +4337,7 @@ def test_get_real_amount_no_trade(default_conf_usdt, buy_order_fee, caplog, mock
# from order # from order
({'cost': 0.004, 'currency': 'LTC'}, 0.004, False, ( ({'cost': 0.004, 'currency': 'LTC'}, 0.004, False, (
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, ' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, '
'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) (from' 'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed), fee=0.004.'
' 8.0 to 7.996).'
)), )),
# invalid, no currency in from fee dict # invalid, no currency in from fee dict
({'cost': 0.008, 'currency': None}, 0, True, None), ({'cost': 0.008, 'currency': None}, 0, True, None),
@ -4364,7 +4369,11 @@ def test_get_real_amount(
caplog.clear() caplog.clear()
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, buy_order, order_obj) == amount - fee_reduction_amount res = freqtrade.get_real_amount(trade, buy_order, order_obj)
if fee_reduction_amount == 0:
assert res is None
else:
assert res == fee_reduction_amount
if expected_log: if expected_log:
assert log_has(expected_log, caplog) assert log_has(expected_log, caplog)
@ -4410,14 +4419,14 @@ def test_get_real_amount_multi(
return_value={'ask': 0.19, 'last': 0.2}) return_value={'ask': 0.19, 'last': 0.2})
# Amount is reduced by "fee" # Amount is reduced by "fee"
expected_amount = amount - (amount * fee_reduction_amount) expected_amount = amount * fee_reduction_amount
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == expected_amount assert freqtrade.get_real_amount(trade, buy_order_fee, order_obj) == expected_amount
assert log_has( assert log_has(
( (
'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, ' 'Applying fee on amount for Trade(id=None, pair=LTC/ETH, amount=8.00000000, '
'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed) ' 'is_short=False, leverage=1.0, open_rate=0.24544100, open_since=closed), '
f'(from 8.0 to {expected_log_amount}).' f'fee={expected_amount}.'
), ),
caplog caplog
) )
@ -4450,7 +4459,7 @@ def test_get_real_amount_invalid_order(default_conf_usdt, trades_for_order, buy_
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount does not change # Amount does not change
assert freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) == amount assert freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) is None
def test_get_real_amount_fees_order(default_conf_usdt, market_buy_order_usdt_doublefee, def test_get_real_amount_fees_order(default_conf_usdt, market_buy_order_usdt_doublefee,
@ -4473,7 +4482,7 @@ def test_get_real_amount_fees_order(default_conf_usdt, market_buy_order_usdt_dou
# Amount does not change # Amount does not change
assert trade.fee_open == 0.0025 assert trade.fee_open == 0.0025
order_obj = Order.parse_from_ccxt_object(market_buy_order_usdt_doublefee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(market_buy_order_usdt_doublefee, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, market_buy_order_usdt_doublefee, order_obj) == 30.0 assert freqtrade.get_real_amount(trade, market_buy_order_usdt_doublefee, order_obj) is None
assert tfo_mock.call_count == 0 assert tfo_mock.call_count == 0
# Fetch fees from trades dict if available to get "proper" values # Fetch fees from trades dict if available to get "proper" values
assert round(trade.fee_open, 4) == 0.001 assert round(trade.fee_open, 4) == 0.001
@ -4525,7 +4534,7 @@ def test_get_real_amount_wrong_amount_rounding(default_conf_usdt, trades_for_ord
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
# Amount changes by fee amount. # Amount changes by fee amount.
assert pytest.approx(freqtrade.get_real_amount( assert pytest.approx(freqtrade.get_real_amount(
trade, limit_buy_order_usdt, order_obj)) == amount - (amount * 0.001) trade, limit_buy_order_usdt, order_obj)) == (amount * 0.001)
def test_get_real_amount_open_trade_usdt(default_conf_usdt, fee, mocker): def test_get_real_amount_open_trade_usdt(default_conf_usdt, fee, mocker):
@ -4547,7 +4556,7 @@ def test_get_real_amount_open_trade_usdt(default_conf_usdt, fee, mocker):
} }
freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt) freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt)
order_obj = Order.parse_from_ccxt_object(order, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(order, 'LTC/ETH', 'buy')
assert freqtrade.get_real_amount(trade, order, order_obj) == amount assert freqtrade.get_real_amount(trade, order, order_obj) is None
def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker, caplog): def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker, caplog):
@ -4604,7 +4613,7 @@ def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker,
order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy') order_obj = Order.parse_from_ccxt_object(buy_order_fee, 'LTC/ETH', 'buy')
res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj)
assert res == amount assert res is None
assert trade.fee_open_currency is None assert trade.fee_open_currency is None
assert trade.fee_open_cost is None assert trade.fee_open_cost is None
message = "Not updating buy-fee - rate: None, POINT." message = "Not updating buy-fee - rate: None, POINT."
@ -4612,7 +4621,7 @@ def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker,
caplog.clear() caplog.clear()
freqtrade.config['exchange']['unknown_fee_rate'] = 1 freqtrade.config['exchange']['unknown_fee_rate'] = 1
res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj) res = freqtrade.get_real_amount(trade, limit_buy_order_usdt, order_obj)
assert res == amount assert res is None
assert trade.fee_open_currency == 'POINT' assert trade.fee_open_currency == 'POINT'
assert pytest.approx(trade.fee_open_cost) == 0.3046651026 assert pytest.approx(trade.fee_open_cost) == 0.3046651026
assert trade.fee_open == 0.002 assert trade.fee_open == 0.002
@ -4621,12 +4630,12 @@ def test_get_real_amount_in_point(default_conf_usdt, buy_order_fee, fee, mocker,
@pytest.mark.parametrize('amount,fee_abs,wallet,amount_exp', [ @pytest.mark.parametrize('amount,fee_abs,wallet,amount_exp', [
(8.0, 0.0, 10, 8), (8.0, 0.0, 10, None),
(8.0, 0.0, 0, 8), (8.0, 0.0, 0, None),
(8.0, 0.1, 0, 7.9), (8.0, 0.1, 0, 0.1),
(8.0, 0.1, 10, 8), (8.0, 0.1, 10, None),
(8.0, 0.1, 8.0, 8.0), (8.0, 0.1, 8.0, None),
(8.0, 0.1, 7.9, 7.9), (8.0, 0.1, 7.9, 0.1),
]) ])
def test_apply_fee_conditional(default_conf_usdt, fee, mocker, def test_apply_fee_conditional(default_conf_usdt, fee, mocker,
amount, fee_abs, wallet, amount_exp): amount, fee_abs, wallet, amount_exp):

Some files were not shown because too many files have changed in this diff Show More