Merge branch 'develop' into renaming-forceentry-forceexit

This commit is contained in:
மனோஜ்குமார் பழனிச்சாமி 2022-04-08 00:01:51 +05:30 committed by GitHub
commit 9417bb01dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 455 additions and 384 deletions

View File

@ -15,10 +15,10 @@
"trailing_stop_positive": 0.005,
"trailing_stop_positive_offset": 0.0051,
"trailing_only_offset_is_reached": false,
"use_sell_signal": true,
"sell_profit_only": false,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": false,
"use_exit_signal": true,
"exit_profit_only": false,
"exit_profit_offset": 0.0,
"ignore_roi_if_entry_signal": false,
"ignore_buying_expired_candle_after": 300,
"trading_mode": "spot",
"margin_mode": "",

View File

@ -345,9 +345,9 @@ The column `Avg Profit %` shows the average profit for all trades made while the
The column `Tot Profit %` shows instead the total profit % in relation to the starting balance.
In the above results, we have a starting balance of 0.01 BTC and an absolute profit of 0.00762792 BTC - so the `Tot Profit %` will be `(0.00762792 / 0.01) * 100 ~= 76.2%`.
Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the `minimal_roi` and `stop_loss` you have set.
Your strategy performance is influenced by your buy strategy, your exit strategy, and also by the `minimal_roi` and `stop_loss` you have set.
For example, if your `minimal_roi` is only `"0": 0.01` you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%).
For example, if your `minimal_roi` is only `"0": 0.01` you cannot expect the bot to make more profit than 1% (because it will exit every time a trade reaches 1%).
```json
"minimal_roi": {
@ -362,7 +362,7 @@ Hence, keep in mind that your performance is an integral mix of all different el
### Exit reasons table
The 2nd table contains a recap of exit reasons.
This table can tell you which area needs some additional work (e.g. all or many of the `exit_signal` trades are losses, so you should work on improving the sell signal, or consider disabling it).
This table can tell you which area needs some additional work (e.g. all or many of the `exit_signal` trades are losses, so you should work on improving the exit signal, or consider disabling it).
### Left open trades table
@ -492,24 +492,24 @@ Since backtesting lacks some detailed information about what happens within a ca
- Buys happen at open-price
- All orders are filled at the requested price (no slippage, no unfilled orders)
- Sell-signal sells happen at open-price of the consecutive candle
- Sell-signal is favored over Stoploss, because sell-signals are assumed to trigger on candle's open
- Exit-signal exits happen at open-price of the consecutive candle
- Exit-signal is favored over Stoploss, because exit-signals are assumed to trigger on candle's open
- ROI
- sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%)
- sells are never "below the candle", so a ROI of 2% may result in a sell at 2.4% if low was at 2.4% profit
- Forcesells caused by `<N>=-1` ROI entries use low as sell value, unless N falls on the candle open (e.g. `120: -1` for 1h candles)
- Stoploss sells happen exactly at stoploss price, even if low was lower, but the loss will be `2 * fees` higher than the stoploss price
- exits are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the exit will be at 2%)
- exits are never "below the candle", so a ROI of 2% may result in a exit at 2.4% if low was at 2.4% profit
- Forceexits caused by `<N>=-1` ROI entries use low as exit value, unless N falls on the candle open (e.g. `120: -1` for 1h candles)
- Stoploss exits happen exactly at stoploss price, even if low was lower, but the loss will be `2 * fees` higher than the stoploss price
- Stoploss is evaluated before ROI within one candle. So you can often see more trades with the `stoploss` exit reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes
- Low happens before high for stoploss, protecting capital first
- Trailing stoploss
- Trailing Stoploss is only adjusted if it's below the candle's low (otherwise it would be triggered)
- On trade entry candles that trigger trailing stoploss, the "minimum offset" (`stop_positive_offset`) is assumed (instead of high) - and the stop is calculated from this point
- High happens first - adjusting stoploss
- Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)
- Low uses the adjusted stoploss (so exits with large high-low difference are backtested correctly)
- ROI applies before trailing-stop, ensuring profits are "top-capped" at ROI if both ROI and trailing stop applies
- Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
- Exit-reason does not explain if a trade was positive or negative, just what triggered the exit (this can look odd if negative ROI values are used)
- Evaluation sequence (if multiple signals happen on the same candle)
- Sell-signal
- Exit-signal
- ROI (if not stoploss)
- Stoploss

View File

@ -92,7 +92,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `dry_run_wallet` | Define the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode.<br>*Defaults to `1000`.* <br> **Datatype:** Float
| `cancel_open_orders_on_exit` | Cancel open orders when the `/stop` RPC command is issued, `Ctrl+C` is pressed or the bot dies unexpectedly. When set to `true`, this allows you to use `/stop` to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `process_only_new_candles` | Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to sell a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
| `minimal_roi` | **Required.** Set the threshold as ratio the bot will use to exit a trade. [More information below](#understand-minimal_roi). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
| `stoploss` | **Required.** Value as ratio of the stoploss used by the bot. More details in the [stoploss documentation](stoploss.md). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float (as ratio)
| `trailing_stop` | Enables trailing stoploss (based on `stoploss` in either configuration or strategy file). More details in the [stoploss documentation](stoploss.md#trailing-stop-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Boolean
| `trailing_stop_positive` | Changes stoploss once profit has been reached. More details in the [stoploss documentation](stoploss.md#trailing-stop-loss-custom-positive-loss). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Float
@ -105,7 +105,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `unfilledtimeout.entry` | **Required.** How long (in minutes or seconds) the bot will wait for an unfilled entry order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
| `unfilledtimeout.exit` | **Required.** How long (in minutes or seconds) the bot will wait for an unfilled exit order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Integer
| `unfilledtimeout.unit` | Unit to use in unfilledtimeout setting. Note: If you set unfilledtimeout.unit to "seconds", "internals.process_throttle_secs" must be inferior or equal to timeout [Strategy Override](#parameters-in-the-strategy). <br> *Defaults to `minutes`.* <br> **Datatype:** String
| `unfilledtimeout.exit_timeout_count` | How many times can exit orders time out. Once this number of timeouts is reached, an emergency sell is triggered. 0 to disable and allow unlimited order cancels. [Strategy Override](#parameters-in-the-strategy).<br>*Defaults to `0`.* <br> **Datatype:** Integer
| `unfilledtimeout.exit_timeout_count` | How many times can exit orders time out. Once this number of timeouts is reached, an emergency exit is triggered. 0 to disable and allow unlimited order cancels. [Strategy Override](#parameters-in-the-strategy).<br>*Defaults to `0`.* <br> **Datatype:** Integer
| `entry_pricing.price_side` | Select the side of the spread the bot should look at to get the entry rate. [More information below](#buy-price-side).<br> *Defaults to `same`.* <br> **Datatype:** String (either `ask`, `bid`, `same` or `other`).
| `entry_pricing.price_last_balance` | **Required.** Interpolate the bidding price. More information [below](#entry-price-without-orderbook-enabled).
| `entry_pricing.use_order_book` | Enable entering using the rates in [Order Book Entry](#entry-price-with-orderbook-enabled). <br> *Defaults to `True`.*<br> **Datatype:** Boolean
@ -115,11 +115,11 @@ Mandatory parameters are marked as **Required**, which means that they are requi
| `exit_pricing.price_side` | Select the side of the spread the bot should look at to get the exit rate. [More information below](#exit-price-side).<br> *Defaults to `same`.* <br> **Datatype:** String (either `ask`, `bid`, `same` or `other`).
| `exit_pricing.price_last_balance` | Interpolate the exiting price. More information [below](#exit-price-without-orderbook-enabled).
| `exit_pricing.use_order_book` | Enable exiting of open trades using [Order Book Exit](#exit-price-with-orderbook-enabled). <br> *Defaults to `True`.*<br> **Datatype:** Boolean
| `exit_pricing.order_book_top` | Bot will use the top N rate in Order Book "price_side" to sell. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in [Order Book Exit](#exit-price-with-orderbook-enabled)<br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
| `use_sell_signal` | Use sell signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
| `sell_profit_only` | Wait until the bot reaches `sell_profit_offset` before taking a sell decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `sell_profit_offset` | Sell-signal is only active above this value. Only active in combination with `sell_profit_only=True`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
| `ignore_roi_if_buy_signal` | Do not sell if the buy signal is still active. This setting takes preference over `minimal_roi` and `use_sell_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `exit_pricing.order_book_top` | Bot will use the top N rate in Order Book "price_side" to exit. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in [Order Book Exit](#exit-price-with-orderbook-enabled)<br>*Defaults to `1`.* <br> **Datatype:** Positive Integer
| `use_exit_signal` | Use exit signals produced by the strategy in addition to the `minimal_roi`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `true`.* <br> **Datatype:** Boolean
| `exit_profit_only` | Wait until the bot reaches `exit_profit_offset` before taking an exit decision. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `exit_profit_offset` | Exit-signal is only active above this value. Only active in combination with `exit_profit_only=True`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `0.0`.* <br> **Datatype:** Float (as ratio)
| `ignore_roi_if_entry_signal` | Do not exit if the entry signal is still active. This setting takes preference over `minimal_roi` and `use_exit_signal`. [Strategy Override](#parameters-in-the-strategy). <br>*Defaults to `false`.* <br> **Datatype:** Boolean
| `ignore_buying_expired_candle_after` | Specifies the number of seconds until a buy signal is no longer used. <br> **Datatype:** Integer
| `order_types` | Configure order-types depending on the action (`"entry"`, `"exit"`, `"stoploss"`, `"stoploss_on_exchange"`). [More information below](#understand-order_types). [Strategy Override](#parameters-in-the-strategy).<br> **Datatype:** Dict
| `order_time_in_force` | Configure time in force for entry and exit orders. [More information below](#understand-order_time_in_force). [Strategy Override](#parameters-in-the-strategy). <br> **Datatype:** Dict
@ -198,10 +198,10 @@ Values set in the configuration file always overwrite values set in the strategy
* `order_time_in_force`
* `unfilledtimeout`
* `disable_dataframe_checks`
* `use_sell_signal`
* `sell_profit_only`
* `sell_profit_offset`
* `ignore_roi_if_buy_signal`
- `use_exit_signal`
* `exit_profit_only`
- `exit_profit_offset`
- `ignore_roi_if_entry_signal`
* `ignore_buying_expired_candle_after`
* `position_adjustment_enable`
* `max_entry_position_adjustment`
@ -330,10 +330,10 @@ See the example below:
```json
"minimal_roi": {
"40": 0.0, # Sell after 40 minutes if the profit is not negative
"30": 0.01, # Sell after 30 minutes if there is at least 1% profit
"20": 0.02, # Sell after 20 minutes if there is at least 2% profit
"0": 0.04 # Sell immediately if there is at least 4% profit
"40": 0.0, # Exit after 40 minutes if the profit is not negative
"30": 0.01, # Exit after 30 minutes if there is at least 1% profit
"20": 0.02, # Exit after 20 minutes if there is at least 2% profit
"0": 0.04 # Exit immediately if there is at least 4% profit
},
```
@ -342,14 +342,14 @@ This parameter can be set in either Strategy or Configuration file. If you use i
`minimal_roi` value from the strategy file.
If it is not set in either Strategy or Configuration, a default of 1000% `{"0": 10}` is used, and minimal ROI is disabled unless your trade generates 1000% profit.
!!! Note "Special case to forcesell after a specific time"
A special case presents using `"<N>": -1` as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.
!!! Note "Special case to forceexit after a specific time"
A special case presents using `"<N>": -1` as ROI. This forces the bot to exit a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-exit.
### Understand forcebuy_enable
The `forcebuy_enable` configuration parameter enables the usage of forcebuy commands via Telegram and REST API.
The `forcebuy_enable` configuration parameter enables the usage of forceenter commands via Telegram and REST API.
For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled.
For example, you can send `/forcebuy ETH/BTC` to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
For example, you can send `/forceenter ETH/BTC` to the bot, which will result in freqtrade buying the pair and holds it until a regular exit-signal (ROI, stoploss, /forceexit) appears.
This can be dangerous with some strategies, so use with care.
@ -378,10 +378,9 @@ For example, if your strategy is using a 1h timeframe, and you only want to buy
The `order_types` configuration parameter maps actions (`entry`, `exit`, `stoploss`, `emergency_exit`, `force_exit`, `force_entry`) to order-types (`market`, `limit`, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
This allows to buy using limit orders, sell using
limit-orders, and create stoplosses using market orders. It also allows to set the
stoploss "on exchange" which means stoploss order would be placed immediately once
the buy order is fulfilled.
This allows to enter using limit orders, exit using limit-orders, and create stoplosses using market orders.
It also allows to set the
stoploss "on exchange" which means stoploss order would be placed immediately once the buy order is fulfilled.
`order_types` set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole `order_types` dictionary in one place.
@ -436,7 +435,10 @@ Configuration:
If `stoploss_on_exchange` is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.
!!! Warning "Warning: stoploss_on_exchange failures"
If stoploss on exchange creation fails for some reason, then an "emergency exit" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the `emergency_exit` value in the `order_types` dictionary - however, this is not advised.
If stoploss on exchange creation fails for some reason, then an "emergency exit" is initiated. By default, this will exit t_he trade using a market order. The order-type for the emergency-exit can be changed by setting the `emergency_exit` value in the `order_types` dictionary - however, this is not advised.
### Understand order_time_in_force

View File

@ -38,7 +38,7 @@ The old section of configuration parameters (`"pairlist"`) has been deprecated i
Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4, and have been removed in 2020.9.
### Using order book steps for sell price
### Using order book steps for exit price
Using `order_book_min` and `order_book_max` used to allow stepping the orderbook and trying to find the next ROI slot - trying to place sell-orders early.
As this does however increase risk and provides no benefit, it's been removed for maintainability purposes in 2021.7.

View File

@ -220,13 +220,13 @@ Protections can have 2 different ways to stop trading for a limited :
##### Protections - per pair
Protections that implement the per pair approach must set `has_local_stop=True`.
The method `stop_per_pair()` will be called whenever a trade closed (sell order completed).
The method `stop_per_pair()` will be called whenever a trade closed (exit order completed).
##### Protections - global protection
These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock).
Global protection must set `has_global_stop=True` to be evaluated for global stops.
The method `global_stop()` will be called whenever a trade closed (sell order completed).
The method `global_stop()` will be called whenever a trade closed (exit order completed).
##### Protections - calculating lock end time
@ -264,7 +264,7 @@ Additional tests / steps to complete:
* Check if balance shows correctly (*)
* Create market order (*)
* Create limit order (*)
* Complete trade (buy + sell) (*)
* Complete trade (enter + exit) (*)
* Compare result calculation between exchange and bot
* Ensure fees are applied correctly (check the database against the exchange)

View File

@ -84,16 +84,16 @@ Freqtrade will fall back to the `proposed_stake` value should your code raise an
Called for open trade every throttling iteration (roughly every 5 seconds) until a trade is closed.
Allows to define custom exit signals, indicating that specified position should be sold. This is very useful when we need to customize sell conditions for each individual trade, or if you need trade data to make an exit decision.
Allows to define custom exit signals, indicating that specified position should be sold. This is very useful when we need to customize exit conditions for each individual trade, or if you need trade data to make an exit decision.
For example you could implement a 1:2 risk-reward ROI with `custom_exit()`.
Using custom_exit() signals in place of stoploss though *is not recommended*. It is a inferior method to using `custom_stoploss()` in this regard - which also allows you to keep the stoploss on exchange.
!!! Note
Returning a (none-empty) `string` or `True` from this method is equal to setting sell signal on a candle at specified time. This method is not called when sell signal is set already, or if sell signals are disabled (`use_sell_signal=False` or `sell_profit_only=True` while profit is below `sell_profit_offset`). `string` max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters.
Returning a (none-empty) `string` or `True` from this method is equal to setting exit signal on a candle at specified time. This method is not called when exit signal is set already, or if exit signals are disabled (`use_exit_signal=False` or `exit_profit_only=True` while profit is below `exit_profit_offset`). `string` max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters.
An example of how we can use different indicators depending on the current profit and also sell trades that were open longer than one day:
An example of how we can use different indicators depending on the current profit and also exit trades that were open longer than one day:
``` python
class AwesomeStrategy(IStrategy):
@ -665,7 +665,7 @@ class DigDeeperStrategy(IStrategy):
if last_candle['close'] < previous_candle['close']:
return None
filled_entries = trade.select_filled_orders(trade.enter_side)
filled_entries = trade.select_filled_orders(trade.entry_side)
count_of_entries = trade.nr_of_successful_entries
# Allow up to 3 additional increasingly larger buys (4 in total)
# Initial buy is 1x

View File

@ -99,7 +99,7 @@ With this section, you have a new column in your dataframe, which has `1` assign
### Customize Indicators
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
Buy and sell signals need indicators. You can add more indicators by extending the list contained in the method `populate_indicators()` from your strategy file.
You should only add the indicators used in either `populate_entry_trend()`, `populate_exit_trend()`, or to populate another indicator, otherwise performance may suffer.
@ -263,8 +263,8 @@ def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFram
### Exit signal rules
Edit the method `populate_exit_trend()` into your strategy file to update your sell strategy.
Please note that the sell-signal is only used if `use_sell_signal` is set to true in the configuration.
Edit the method `populate_exit_trend()` into your strategy file to update your exit strategy.
Please note that the exit-signal is only used if `use_exit_signal` is set to true in the configuration.
It's important to always return the dataframe without removing/modifying the columns `"open", "high", "low", "close", "volume"`, otherwise these fields would contain something unexpected.
@ -275,7 +275,7 @@ Sample from `user_data/strategies/sample_strategy.py`:
```python
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
Based on TA indicators, populates the sell signal for the given dataframe
Based on TA indicators, populates the exit signal for the given dataframe
:param dataframe: DataFrame populated with indicators
:param metadata: Additional information, like the currently traded pair
:return: DataFrame with buy column
@ -319,7 +319,7 @@ def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame
### Minimal ROI
This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.
This dict defines the minimal Return On Investment (ROI) a trade should reach before exiting, independent from the exit signal.
It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
@ -334,10 +334,10 @@ minimal_roi = {
The above configuration would therefore mean:
- Sell whenever 4% profit was reached
- Sell when 2% profit was reached (in effect after 20 minutes)
- Sell when 1% profit was reached (in effect after 30 minutes)
- Sell when trade is non-loosing (in effect after 40 minutes)
- Exit whenever 4% profit was reached
- Exit when 2% profit was reached (in effect after 20 minutes)
- Exit when 1% profit was reached (in effect after 30 minutes)
- Exit when trade is non-loosing (in effect after 40 minutes)
The calculation does include fees.
@ -349,7 +349,7 @@ minimal_roi = {
}
```
While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
While technically not completely disabled, this would exit once the trade reaches 10000% Profit.
To use times based on candle duration (timeframe), the following snippet can be handy.
This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...)
@ -385,7 +385,7 @@ For the full documentation on stoploss features, look at the dedicated [stoploss
This is the set of candles the bot should download and use for the analysis.
Common values are `"1m"`, `"5m"`, `"15m"`, `"1h"`, however all values supported by your exchange should work.
Please note that the same buy/sell signals may work well with one timeframe, but not with the others.
Please note that the same entry/exit signals may work well with one timeframe, but not with the others.
This setting is accessible within the strategy methods as the `self.timeframe` attribute.
@ -1088,7 +1088,7 @@ The following lists some common patterns which should be avoided to prevent frus
### Colliding signals
When conflicting signals collide (e.g. both `'enter_long'` and `'exit_long'` are 1), freqtrade will do nothing and ignore the entry signal. This will avoid trades that buy, and sell immediately. Obviously, this can potentially lead to missed entries.
When conflicting signals collide (e.g. both `'enter_long'` and `'exit_long'` are 1), freqtrade will do nothing and ignore the entry signal. This will avoid trades that enter, and exit immediately. Obviously, this can potentially lead to missed entries.
The following rules apply, and entry signals will be ignored if more than one of the 3 signals is set:

View File

@ -29,7 +29,7 @@ Note : `force_exit`, `force_enter`, `emergency_exit` are changed to `force_exit`
* [New column `enter_short` and corresponding new column `exit_short`](#populate_sell_trend)
* trade-object now has the following new properties:
* `is_short`
* `enter_side`
* `entry_side`
* `exit_side`
* `trade_direction`
* renamed: `sell_reason` -> `exit_reason`
@ -63,8 +63,11 @@ Note : `force_exit`, `force_enter`, `emergency_exit` are changed to `force_exit`
* `sell` -> `exit`
* `sell_fill` -> `exit_fill`
* `sell_cancel` -> `exit_cancel`
* Strategy/config settings:
* `use_sell_signal` -> `use_exit_signal`
* `sell_profit_only` -> `exit_profit_only`
* `sell_profit_offset` -> `exit_profit_offset`
* `ignore_roi_if_buy_signal` -> `ignore_roi_if_entry_signal`
## Extensive explanation
@ -363,6 +366,31 @@ After:
}
```
#### Strategy level settings
* `use_sell_signal` -> `use_exit_signal`
* `sell_profit_only` -> `exit_profit_only`
* `sell_profit_offset` -> `exit_profit_offset`
* `ignore_roi_if_buy_signal` -> `ignore_roi_if_entry_signal`
``` python hl_lines="2-5"
# These values can be overridden in the config.
use_sell_signal = True
sell_profit_only = True
sell_profit_offset: 0.01
ignore_roi_if_buy_signal = False
```
After:
``` python hl_lines="2-5"
# These values can be overridden in the config.
use_exit_signal = True
exit_profit_only = True
exit_profit_offset: 0.01
ignore_roi_if_entry_signal = False
```
#### `unfilledtimeout`
`unfilledtimeout` have changed all wordings from `buy` to `entry` - and `sell` to `exit`.

View File

@ -202,6 +202,8 @@ def ask_user_config() -> Dict[str, Any]:
if not answers:
# Interrupted questionary sessions return an empty dict.
raise OperationalException("User interrupted interactive questions.")
# Ensure default is set for non-futures exchanges
answers['trading_mode'] = answers.get('trading_mode', "spot")
answers['margin_mode'] = (
'isolated'
if answers.get('trading_mode') == 'futures'

View File

@ -154,9 +154,9 @@ def _validate_edge(conf: Dict[str, Any]) -> None:
if not conf.get('edge', {}).get('enabled'):
return
if not conf.get('use_sell_signal', True):
if not conf.get('use_exit_signal', True):
raise OperationalException(
"Edge requires `use_sell_signal` to be True, otherwise no sells will happen."
"Edge requires `use_exit_signal` to be True, otherwise no sells will happen."
)
@ -219,6 +219,7 @@ def validate_migrated_strategy_settings(conf: Dict[str, Any]) -> None:
_validate_order_types(conf)
_validate_unfilledtimeout(conf)
_validate_pricing_rules(conf)
_strategy_settings(conf)
def _validate_time_in_force(conf: Dict[str, Any]) -> None:
@ -315,3 +316,12 @@ def _validate_pricing_rules(conf: Dict[str, Any]) -> None:
else:
process_deprecated_setting(conf, 'ask_strategy', obj, 'exit_pricing', obj)
del conf['ask_strategy']
def _strategy_settings(conf: Dict[str, Any]) -> None:
process_deprecated_setting(conf, None, 'use_sell_signal', None, 'use_exit_signal')
process_deprecated_setting(conf, None, 'sell_profit_only', None, 'exit_profit_only')
process_deprecated_setting(conf, None, 'sell_profit_offset', None, 'exit_profit_offset')
process_deprecated_setting(conf, None, 'ignore_roi_if_buy_signal',
None, 'ignore_roi_if_entry_signal')

View File

@ -433,8 +433,9 @@ class Configuration:
logstring='Detected --new-pairs-days: {}')
self._args_to_config(config, argname='trading_mode',
logstring='Detected --trading-mode: {}')
config['candle_type_def'] = CandleType.get_default(config.get('trading_mode', 'spot'))
config['trading_mode'] = TradingMode(config.get('trading_mode', 'spot'))
config['candle_type_def'] = CandleType.get_default(
config.get('trading_mode', 'spot') or 'spot')
config['trading_mode'] = TradingMode(config.get('trading_mode', 'spot') or 'spot')
self._args_to_config(config, argname='candle_types',
logstring='Detected --candle-types: {}')

View File

@ -12,14 +12,15 @@ logger = logging.getLogger(__name__)
def check_conflicting_settings(config: Dict[str, Any],
section_old: str, name_old: str,
section_old: Optional[str], name_old: str,
section_new: Optional[str], name_new: str) -> None:
section_new_config = config.get(section_new, {}) if section_new else config
section_old_config = config.get(section_old, {})
section_old_config = config.get(section_old, {}) if section_old else config
if name_new in section_new_config and name_old in section_old_config:
new_name = f"{section_new}.{name_new}" if section_new else f"{name_new}"
old_name = f"{section_old}.{name_old}" if section_old else f"{name_old}"
raise OperationalException(
f"Conflicting settings `{new_name}` and `{section_old}.{name_old}` "
f"Conflicting settings `{new_name}` and `{old_name}` "
"(DEPRECATED) detected in the configuration file. "
"This deprecated setting will be removed in the next versions of Freqtrade. "
f"Please delete it from your configuration and use the `{new_name}` "
@ -47,11 +48,11 @@ def process_removed_setting(config: Dict[str, Any],
def process_deprecated_setting(config: Dict[str, Any],
section_old: str, name_old: str,
section_old: Optional[str], name_old: str,
section_new: Optional[str], name_new: str
) -> None:
check_conflicting_settings(config, section_old, name_old, section_new, name_new)
section_old_config = config.get(section_old, {})
section_old_config = config.get(section_old, {}) if section_old else config
if name_old in section_old_config:
section_2 = f"{section_new}.{name_new}" if section_new else f"{name_new}"
@ -72,14 +73,7 @@ def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
# Kept for future deprecated / moved settings
# check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal',
# 'experimental', 'use_sell_signal')
process_deprecated_setting(config, 'ask_strategy', 'use_sell_signal',
None, 'use_sell_signal')
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_only',
None, 'sell_profit_only')
process_deprecated_setting(config, 'ask_strategy', 'sell_profit_offset',
None, 'sell_profit_offset')
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
None, 'ignore_roi_if_buy_signal')
process_deprecated_setting(config, 'ask_strategy', 'ignore_buying_expired_candle_after',
None, 'ignore_buying_expired_candle_after')
# New settings
@ -109,13 +103,18 @@ def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
'webhook', 'webhookexitfill')
# Legacy way - having them in experimental ...
process_removed_setting(config, 'experimental', 'use_sell_signal',
None, 'use_sell_signal')
process_removed_setting(config, 'experimental', 'sell_profit_only',
None, 'sell_profit_only')
process_removed_setting(config, 'experimental', 'ignore_roi_if_buy_signal',
None, 'ignore_roi_if_buy_signal')
process_removed_setting(config, 'experimental', 'use_sell_signal', None, 'use_exit_signal')
process_removed_setting(config, 'experimental', 'sell_profit_only', None, 'exit_profit_only')
process_removed_setting(config, 'experimental', 'ignore_roi_if_buy_signal',
None, 'ignore_roi_if_entry_signal')
process_removed_setting(config, 'ask_strategy', 'use_sell_signal', None, 'exit_sell_signal')
process_removed_setting(config, 'ask_strategy', 'sell_profit_only', None, 'exit_profit_only')
process_removed_setting(config, 'ask_strategy', 'sell_profit_offset',
None, 'exit_profit_offset')
process_removed_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
None, 'ignore_roi_if_entry_signal')
if (config.get('edge', {}).get('enabled', False)
and 'capital_available_percentage' in config.get('edge', {})):
raise OperationalException(

View File

@ -86,8 +86,8 @@ SUPPORTED_FIAT = [
"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
"EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
"KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN",
"RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD",
"BTC", "ETH", "XRP", "LTC", "BCH"
"RUB", "UAH", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR",
"USD", "BTC", "ETH", "XRP", "LTC", "BCH"
]
MINIMAL_CONFIG = {
@ -149,10 +149,10 @@ CONF_SCHEMA = {
'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},
'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},
'trailing_only_offset_is_reached': {'type': 'boolean'},
'use_sell_signal': {'type': 'boolean'},
'sell_profit_only': {'type': 'boolean'},
'sell_profit_offset': {'type': 'number'},
'ignore_roi_if_buy_signal': {'type': 'boolean'},
'use_exit_signal': {'type': 'boolean'},
'exit_profit_only': {'type': 'boolean'},
'exit_profit_offset': {'type': 'number'},
'ignore_roi_if_entry_signal': {'type': 'boolean'},
'ignore_buying_expired_candle_after': {'type': 'number'},
'trading_mode': {'type': 'string', 'enum': TRADING_MODES},
'margin_mode': {'type': 'string', 'enum': MARGIN_MODES},

View File

@ -330,12 +330,12 @@ class FreqtradeBot(LoggingMixin):
trades: List[Trade] = Trade.get_open_trades_without_assigned_fees()
for trade in trades:
if trade.is_open and not trade.fee_updated(trade.enter_side):
order = trade.select_order(trade.enter_side, False)
open_order = trade.select_order(trade.enter_side, True)
if trade.is_open and not trade.fee_updated(trade.entry_side):
order = trade.select_order(trade.entry_side, False)
open_order = trade.select_order(trade.entry_side, True)
if order and open_order is None:
logger.info(
f"Updating {trade.enter_side}-fee on trade {trade}"
f"Updating {trade.entry_side}-fee on trade {trade}"
f"for order {order.order_id}."
)
self.update_trade_state(trade, order.order_id, send_msg=False)
@ -364,7 +364,7 @@ class FreqtradeBot(LoggingMixin):
if fo and fo['status'] == 'open':
# Assume this as the open order
trade.open_order_id = order.order_id
elif order.ft_order_side == trade.enter_side:
elif order.ft_order_side == trade.entry_side:
if fo and fo['status'] == 'open':
trade.open_order_id = order.order_id
if fo:
@ -549,9 +549,9 @@ class FreqtradeBot(LoggingMixin):
order_book_bids = order_book_data_frame['b_size'].sum()
order_book_asks = order_book_data_frame['a_size'].sum()
enter_side = order_book_bids if side == SignalDirection.LONG else order_book_asks
entry_side = order_book_bids if side == SignalDirection.LONG else order_book_asks
exit_side = order_book_asks if side == SignalDirection.LONG else order_book_bids
bids_ask_delta = enter_side / exit_side
bids_ask_delta = entry_side / exit_side
bids = f"Bids: {order_book_bids}"
asks = f"Asks: {order_book_asks}"
@ -926,8 +926,8 @@ class FreqtradeBot(LoggingMixin):
exit_tag = None
exit_signal_type = "exit_short" if trade.is_short else "exit_long"
if (self.config.get('use_sell_signal', True) or
self.config.get('ignore_roi_if_buy_signal', False)):
if (self.config.get('use_exit_signal', True) or
self.config.get('ignore_roi_if_entry_signal', False)):
analyzed_df, _ = self.dataprovider.get_analyzed_dataframe(trade.pair,
self.strategy.timeframe)
@ -1136,7 +1136,7 @@ class FreqtradeBot(LoggingMixin):
continue
fully_cancelled = self.update_trade_state(trade, trade.open_order_id, order)
is_entering = order['side'] == trade.enter_side
is_entering = order['side'] == trade.entry_side
not_closed = order['status'] == 'open' or fully_cancelled
max_timeouts = self.config.get('unfilledtimeout', {}).get('exit_timeout_count', 0)
@ -1177,7 +1177,7 @@ class FreqtradeBot(LoggingMixin):
logger.info('Cannot query order for %s due to %s', trade, traceback.format_exc())
continue
if order['side'] == trade.enter_side:
if order['side'] == trade.entry_side:
self.handle_cancel_enter(trade, order, constants.CANCEL_REASON['ALL_CANCELLED'])
elif order['side'] == trade.exit_side:
@ -1216,7 +1216,7 @@ class FreqtradeBot(LoggingMixin):
corder = order
reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE']
side = trade.enter_side.capitalize()
side = trade.entry_side.capitalize()
logger.info('%s order %s for %s.', side, reason, trade)
# Using filled to determine the filled amount
@ -1247,7 +1247,7 @@ class FreqtradeBot(LoggingMixin):
self.update_trade_state(trade, trade.open_order_id, corder)
trade.open_order_id = None
logger.info(f'Partial {trade.enter_side} order timeout for {trade}.')
logger.info(f'Partial {trade.entry_side} order timeout for {trade}.')
reason += f", {constants.CANCEL_REASON['PARTIALLY_FILLED']}"
self.wallets.update()
@ -1577,7 +1577,7 @@ class FreqtradeBot(LoggingMixin):
if order['status'] in constants.NON_OPEN_EXCHANGE_STATES:
# If a entry order was closed, force update on stoploss on exchange
if order.get('side', None) == trade.enter_side:
if order.get('side', None) == trade.entry_side:
trade = self.cancel_stoploss_on_exchange(trade)
# TODO: Margin will need to use interest_rate as well.
# interest_rate = self.exchange.get_interest_rate()

View File

@ -349,20 +349,20 @@ class Backtesting:
data[pair] = df_analyzed[headers].values.tolist() if not df_analyzed.empty else []
return data
def _get_close_rate(self, sell_row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
def _get_close_rate(self, row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
trade_dur: int) -> float:
"""
Get close rate for backtesting result
"""
# Special handling if high or low hit STOP_LOSS or ROI
if sell.exit_type in (ExitType.STOP_LOSS, ExitType.TRAILING_STOP_LOSS):
return self._get_close_rate_for_stoploss(sell_row, trade, sell, trade_dur)
return self._get_close_rate_for_stoploss(row, trade, sell, trade_dur)
elif sell.exit_type == (ExitType.ROI):
return self._get_close_rate_for_roi(sell_row, trade, sell, trade_dur)
return self._get_close_rate_for_roi(row, trade, sell, trade_dur)
else:
return sell_row[OPEN_IDX]
return row[OPEN_IDX]
def _get_close_rate_for_stoploss(self, sell_row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
def _get_close_rate_for_stoploss(self, row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
trade_dur: int) -> float:
# our stoploss was already lower than candle high,
# possibly due to a cancelled trade exit.
@ -371,11 +371,11 @@ class Backtesting:
leverage = trade.leverage or 1.0
side_1 = -1 if is_short else 1
if is_short:
if trade.stop_loss < sell_row[LOW_IDX]:
return sell_row[OPEN_IDX]
if trade.stop_loss < row[LOW_IDX]:
return row[OPEN_IDX]
else:
if trade.stop_loss > sell_row[HIGH_IDX]:
return sell_row[OPEN_IDX]
if trade.stop_loss > row[HIGH_IDX]:
return row[OPEN_IDX]
# Special case: trailing triggers within same candle as trade opened. Assume most
# pessimistic price movement, which is moving just enough to arm stoploss and
@ -388,29 +388,28 @@ class Backtesting:
and self.strategy.trailing_stop_positive
):
# Worst case: price reaches stop_positive_offset and dives down.
stop_rate = (sell_row[OPEN_IDX] *
stop_rate = (row[OPEN_IDX] *
(1 + side_1 * abs(self.strategy.trailing_stop_positive_offset) -
side_1 * abs(self.strategy.trailing_stop_positive / leverage)))
else:
# Worst case: price ticks tiny bit above open and dives down.
stop_rate = sell_row[OPEN_IDX] * (1 -
side_1 * abs(trade.stop_loss_pct / leverage))
stop_rate = row[OPEN_IDX] * (1 - side_1 * abs(trade.stop_loss_pct / leverage))
if is_short:
assert stop_rate > sell_row[LOW_IDX]
assert stop_rate > row[LOW_IDX]
else:
assert stop_rate < sell_row[HIGH_IDX]
assert stop_rate < row[HIGH_IDX]
# Limit lower-end to candle low to avoid sells below the low.
# This still remains "worst case" - but "worst realistic case".
if is_short:
return min(sell_row[HIGH_IDX], stop_rate)
return min(row[HIGH_IDX], stop_rate)
else:
return max(sell_row[LOW_IDX], stop_rate)
return max(row[LOW_IDX], stop_rate)
# Set close_rate to stoploss
return trade.stop_loss
def _get_close_rate_for_roi(self, sell_row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
def _get_close_rate_for_roi(self, row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
trade_dur: int) -> float:
is_short = trade.is_short or False
leverage = trade.leverage or 1.0
@ -421,38 +420,38 @@ class Backtesting:
# When forceselling with ROI=-1, the roi time will always be equal to trade_dur.
# If that entry is a multiple of the timeframe (so on candle open)
# - we'll use open instead of close
return sell_row[OPEN_IDX]
return row[OPEN_IDX]
# - (Expected abs profit - open_rate - open_fee) / (fee_close -1)
roi_rate = trade.open_rate * roi / leverage
open_fee_rate = side_1 * trade.open_rate * (1 + side_1 * trade.fee_open)
close_rate = -(roi_rate + open_fee_rate) / (trade.fee_close - side_1 * 1)
if is_short:
is_new_roi = sell_row[OPEN_IDX] < close_rate
is_new_roi = row[OPEN_IDX] < close_rate
else:
is_new_roi = sell_row[OPEN_IDX] > close_rate
is_new_roi = row[OPEN_IDX] > close_rate
if (trade_dur > 0 and trade_dur == roi_entry
and roi_entry % self.timeframe_min == 0
and is_new_roi):
# new ROI entry came into effect.
# use Open rate if open_rate > calculated sell rate
return sell_row[OPEN_IDX]
return row[OPEN_IDX]
if (trade_dur == 0 and (
(
is_short
# Red candle (for longs)
and sell_row[OPEN_IDX] < sell_row[CLOSE_IDX] # Red candle
and trade.open_rate > sell_row[OPEN_IDX] # trade-open above open_rate
and close_rate < sell_row[CLOSE_IDX] # closes below close
and row[OPEN_IDX] < row[CLOSE_IDX] # Red candle
and trade.open_rate > row[OPEN_IDX] # trade-open above open_rate
and close_rate < row[CLOSE_IDX] # closes below close
)
or
(
not is_short
# green candle (for shorts)
and sell_row[OPEN_IDX] > sell_row[CLOSE_IDX] # green candle
and trade.open_rate < sell_row[OPEN_IDX] # trade-open below open_rate
and close_rate > sell_row[CLOSE_IDX] # closes above close
and row[OPEN_IDX] > row[CLOSE_IDX] # green candle
and trade.open_rate < row[OPEN_IDX] # trade-open below open_rate
and close_rate > row[CLOSE_IDX] # closes above close
)
)):
# ROI on opening candles with custom pricing can only
@ -464,11 +463,11 @@ class Backtesting:
# Use the maximum between close_rate and low as we
# cannot sell outside of a candle.
# Applies when a new ROI setting comes in place and the whole candle is above that.
return min(max(close_rate, sell_row[LOW_IDX]), sell_row[HIGH_IDX])
return min(max(close_rate, row[LOW_IDX]), row[HIGH_IDX])
else:
# This should not be reached...
return sell_row[OPEN_IDX]
return row[OPEN_IDX]
def _get_adjust_trade_entry_for_candle(self, trade: LocalTrade, row: Tuple
) -> LocalTrade:
@ -498,7 +497,7 @@ class Backtesting:
return row[LOW_IDX] <= rate <= row[HIGH_IDX]
def _get_sell_trade_entry_for_candle(self, trade: LocalTrade,
sell_row: Tuple) -> Optional[LocalTrade]:
row: Tuple) -> Optional[LocalTrade]:
# Check if we need to adjust our current positions
if self.strategy.position_adjustment_enable:
@ -507,15 +506,15 @@ class Backtesting:
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, sell_row)
trade = self._get_adjust_trade_entry_for_candle(trade, row)
sell_candle_time: datetime = sell_row[DATE_IDX].to_pydatetime()
enter = sell_row[SHORT_IDX] if trade.is_short else sell_row[LONG_IDX]
exit_ = sell_row[ESHORT_IDX] if trade.is_short else sell_row[ELONG_IDX]
sell_candle_time: datetime = row[DATE_IDX].to_pydatetime()
enter = row[SHORT_IDX] if trade.is_short else row[LONG_IDX]
exit_ = row[ESHORT_IDX] if trade.is_short else row[ELONG_IDX]
sell = self.strategy.should_exit(
trade, sell_row[OPEN_IDX], sell_candle_time, # type: ignore
trade, row[OPEN_IDX], sell_candle_time, # type: ignore
enter=enter, exit_=exit_,
low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX]
low=row[LOW_IDX], high=row[HIGH_IDX]
)
if sell.exit_flag:
@ -523,7 +522,7 @@ class Backtesting:
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
try:
closerate = self._get_close_rate(sell_row, trade, sell, trade_dur)
closerate = self._get_close_rate(row, trade, sell, trade_dur)
except ValueError:
return None
# call the custom exit price,with default value as previous closerate
@ -540,9 +539,9 @@ class Backtesting:
# We can't place orders lower than current low.
# freqtrade does not support this in live, and the order would fill immediately
if trade.is_short:
closerate = min(closerate, sell_row[HIGH_IDX])
closerate = min(closerate, row[HIGH_IDX])
else:
closerate = max(closerate, sell_row[LOW_IDX])
closerate = max(closerate, row[LOW_IDX])
# Confirm trade exit:
time_in_force = self.strategy.order_time_in_force['exit']
@ -558,13 +557,13 @@ class Backtesting:
trade.exit_reason = sell.exit_reason
# Checks and adds an exit tag, after checking that the length of the
# sell_row has the length for an exit tag column
# row has the length for an exit tag column
if(
len(sell_row) > EXIT_TAG_IDX
and sell_row[EXIT_TAG_IDX] is not None
and len(sell_row[EXIT_TAG_IDX]) > 0
len(row) > EXIT_TAG_IDX
and row[EXIT_TAG_IDX] is not None
and len(row[EXIT_TAG_IDX]) > 0
):
trade.exit_reason = sell_row[EXIT_TAG_IDX]
trade.exit_reason = row[EXIT_TAG_IDX]
self.order_id_counter += 1
order = Order(
@ -592,8 +591,8 @@ class Backtesting:
return None
def _get_sell_trade_entry(self, trade: LocalTrade, sell_row: Tuple) -> Optional[LocalTrade]:
sell_candle_time: datetime = sell_row[DATE_IDX].to_pydatetime()
def _get_sell_trade_entry(self, trade: LocalTrade, row: Tuple) -> Optional[LocalTrade]:
sell_candle_time: datetime = row[DATE_IDX].to_pydatetime()
if self.trading_mode == TradingMode.FUTURES:
trade.funding_fees = self.exchange.calculate_funding_fees(
@ -614,13 +613,13 @@ class Backtesting:
].copy()
if len(detail_data) == 0:
# Fall back to "regular" data if no detail data was found for this candle
return self._get_sell_trade_entry_for_candle(trade, sell_row)
detail_data.loc[:, 'enter_long'] = sell_row[LONG_IDX]
detail_data.loc[:, 'exit_long'] = sell_row[ELONG_IDX]
detail_data.loc[:, 'enter_short'] = sell_row[SHORT_IDX]
detail_data.loc[:, 'exit_short'] = sell_row[ESHORT_IDX]
detail_data.loc[:, 'enter_tag'] = sell_row[ENTER_TAG_IDX]
detail_data.loc[:, 'exit_tag'] = sell_row[EXIT_TAG_IDX]
return self._get_sell_trade_entry_for_candle(trade, row)
detail_data.loc[:, 'enter_long'] = row[LONG_IDX]
detail_data.loc[:, 'exit_long'] = row[ELONG_IDX]
detail_data.loc[:, 'enter_short'] = row[SHORT_IDX]
detail_data.loc[:, 'exit_short'] = row[ESHORT_IDX]
detail_data.loc[:, 'enter_tag'] = row[ENTER_TAG_IDX]
detail_data.loc[:, 'exit_tag'] = row[EXIT_TAG_IDX]
headers = ['date', 'open', 'high', 'low', 'close', 'enter_long', 'exit_long',
'enter_short', 'exit_short', 'enter_tag', 'exit_tag']
for det_row in detail_data[headers].values.tolist():
@ -631,7 +630,7 @@ class Backtesting:
return None
else:
return self._get_sell_trade_entry_for_candle(trade, sell_row)
return self._get_sell_trade_entry_for_candle(trade, row)
def get_valid_price_and_stake(
self, pair: str, row: Tuple, propose_rate: float, stake_amount: Optional[float],
@ -774,8 +773,8 @@ class Backtesting:
ft_pair=trade.pair,
order_id=str(self.order_id_counter),
symbol=trade.pair,
ft_order_side=trade.enter_side,
side=trade.enter_side,
ft_order_side=trade.entry_side,
side=trade.entry_side,
order_type=order_type,
status="open",
order_date=current_time,
@ -857,7 +856,7 @@ class Backtesting:
timedout = self.strategy.ft_check_timed_out(trade, order, current_time)
if timedout:
if order.side == trade.enter_side:
if order.side == trade.entry_side:
self.timedout_entry_orders += 1
if trade.nr_of_successful_entries == 0:
# Remove trade due to entry timeout expiration.
@ -972,7 +971,7 @@ class Backtesting:
for trade in list(open_trades[pair]):
# 3. Process entry orders.
order = trade.select_order(trade.enter_side, is_open=True)
order = trade.select_order(trade.entry_side, is_open=True)
if order and self._get_order_filled(order.price, row):
order.close_bt_order(current_time)
trade.open_order_id = None

View File

@ -114,8 +114,8 @@ class Hyperopt:
self.position_stacking = self.config.get('position_stacking', False)
if HyperoptTools.has_space(self.config, 'sell'):
# Make sure use_sell_signal is enabled
self.config['use_sell_signal'] = True
# Make sure use_exit_signal is enabled
self.config['use_exit_signal'] = True
self.print_all = self.config.get('print_all', False)
self.hyperopt_table_header = 0

View File

@ -460,10 +460,10 @@ def generate_strategy_stats(pairlist: List[str],
'trailing_only_offset_is_reached': config.get('trailing_only_offset_is_reached', False),
'use_custom_stoploss': config.get('use_custom_stoploss', False),
'minimal_roi': config['minimal_roi'],
'use_sell_signal': config['use_sell_signal'],
'sell_profit_only': config['sell_profit_only'],
'sell_profit_offset': config['sell_profit_offset'],
'ignore_roi_if_buy_signal': config['ignore_roi_if_buy_signal'],
'use_exit_signal': config['use_exit_signal'],
'exit_profit_only': config['exit_profit_only'],
'exit_profit_offset': config['exit_profit_offset'],
'ignore_roi_if_entry_signal': config['ignore_roi_if_entry_signal'],
**daily_stats,
**trade_stats
}

View File

@ -372,6 +372,12 @@ class LocalTrade():
@property
def enter_side(self) -> str:
""" DEPRECATED, please use entry_side instead"""
# TODO: Please remove me after 2022.5
return self.entry_side
@property
def entry_side(self) -> str:
if self.is_short:
return "sell"
else:
@ -412,7 +418,7 @@ class LocalTrade():
def to_json(self) -> Dict[str, Any]:
filled_orders = self.select_filled_orders()
orders = [order.to_json(self.enter_side) for order in filled_orders]
orders = [order.to_json(self.entry_side) for order in filled_orders]
return {
'trade_id': self.id,
@ -601,7 +607,7 @@ class LocalTrade():
logger.info(f'Updating trade (id={self.id}) ...')
if order.ft_order_side == self.enter_side:
if order.ft_order_side == self.entry_side:
# Update open rate and actual amount
self.open_rate = order.safe_price
self.amount = order.safe_amount_after_fee
@ -650,7 +656,7 @@ class LocalTrade():
"""
Update Fee parameters. Only acts once per side
"""
if self.enter_side == side and self.fee_open_currency is None:
if self.entry_side == side and self.fee_open_currency is None:
self.fee_open_cost = fee_cost
self.fee_open_currency = fee_currency
if fee_rate is not None:
@ -667,7 +673,7 @@ class LocalTrade():
"""
Verify if this side (buy / sell) has already been updated
"""
if self.enter_side == side:
if self.entry_side == side:
return self.fee_open_currency is not None
elif self.exit_side == side:
return self.fee_close_currency is not None
@ -840,7 +846,7 @@ class LocalTrade():
def recalc_trade_from_orders(self):
# We need at least 2 entry orders for averaging amounts and rates.
# TODO: this condition could probably be removed
if len(self.select_filled_orders(self.enter_side)) < 2:
if len(self.select_filled_orders(self.entry_side)) < 2:
self.stake_amount = self.amount * self.open_rate / self.leverage
# Just in case, still recalc open trade value
@ -851,7 +857,7 @@ class LocalTrade():
total_stake = 0.0
for o in self.orders:
if (o.ft_is_open or
(o.ft_order_side != self.enter_side) or
(o.ft_order_side != self.entry_side) or
(o.status not in NON_OPEN_EXCHANGE_STATES)):
continue
@ -919,7 +925,7 @@ class LocalTrade():
:return: int count of entry orders that have been filled for this trade.
"""
return len(self.select_filled_orders(self.enter_side))
return len(self.select_filled_orders(self.entry_side))
@property
def nr_of_successful_exits(self) -> int:

View File

@ -85,10 +85,10 @@ class StrategyResolver(IResolver):
("protections", None),
("startup_candle_count", None),
("unfilledtimeout", None),
("use_sell_signal", True),
("sell_profit_only", False),
("ignore_roi_if_buy_signal", False),
("sell_profit_offset", 0.0),
("use_exit_signal", True),
("exit_profit_only", False),
("ignore_roi_if_entry_signal", False),
("exit_profit_offset", 0.0),
("disable_dataframe_checks", False),
("ignore_buying_expired_candle_after", 0),
("position_adjustment_enable", False),
@ -173,6 +173,12 @@ class StrategyResolver(IResolver):
def validate_strategy(strategy: IStrategy) -> IStrategy:
if strategy.config.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT:
# Require new method
warn_deprecated_setting(strategy, 'sell_profit_only', 'exit_profit_only', True)
warn_deprecated_setting(strategy, 'sell_profit_offset', 'exit_profit_offset', True)
warn_deprecated_setting(strategy, 'use_sell_signal', 'use_exit_signal', True)
warn_deprecated_setting(strategy, 'ignore_roi_if_buy_signal',
'ignore_roi_if_entry_signal', True)
if not check_override(strategy, IStrategy, 'populate_entry_trend'):
raise OperationalException("`populate_entry_trend` must be implemented.")
if not check_override(strategy, IStrategy, 'populate_exit_trend'):
@ -187,9 +193,16 @@ class StrategyResolver(IResolver):
if check_override(strategy, IStrategy, 'custom_sell'):
raise OperationalException(
"Please migrate your implementation of `custom_sell` to `custom_exit`.")
else:
# TODO: Implementing one of the following methods should show a deprecation warning
# buy_trend and sell_trend, custom_sell
warn_deprecated_setting(strategy, 'sell_profit_only', 'exit_profit_only')
warn_deprecated_setting(strategy, 'sell_profit_offset', 'exit_profit_offset')
warn_deprecated_setting(strategy, 'use_sell_signal', 'use_exit_signal')
warn_deprecated_setting(strategy, 'ignore_roi_if_buy_signal',
'ignore_roi_if_entry_signal')
if (
not check_override(strategy, IStrategy, 'populate_buy_trend')
and not check_override(strategy, IStrategy, 'populate_entry_trend')
@ -262,6 +275,15 @@ class StrategyResolver(IResolver):
)
def warn_deprecated_setting(strategy: IStrategy, old: str, new: str, error=False):
if hasattr(strategy, old):
errormsg = f"DEPRECATED: Using '{old}' moved to '{new}'."
if error:
raise OperationalException(errormsg)
logger.warning(errormsg)
setattr(strategy, new, getattr(strategy, f'{old}'))
def check_override(object, parentclass, attribute):
"""
Checks if a object overrides the parent class attribute.

View File

@ -86,7 +86,7 @@ class CryptoToFiatConverter:
return None
else:
return None
found = [x for x in self._coinlistings if x['symbol'] == crypto_symbol]
found = [x for x in self._coinlistings if x['symbol'].lower() == crypto_symbol]
if crypto_symbol in coingecko_mapping.keys():
found = [x for x in self._coinlistings if x['id'] == coingecko_mapping[crypto_symbol]]

View File

@ -695,7 +695,7 @@ class RPC:
if trade.open_order_id:
order = self._freqtrade.exchange.fetch_order(trade.open_order_id, trade.pair)
if order['side'] == trade.enter_side:
if order['side'] == trade.entry_side:
fully_canceled = self._freqtrade.handle_cancel_enter(
trade, order, CANCEL_REASON['FORCE_EXIT'])

View File

@ -233,11 +233,11 @@ class Telegram(RPCHandler):
is_fill = msg['type'] in [RPCMessageType.ENTRY_FILL]
emoji = '\N{CHECK MARK}' if is_fill else '\N{LARGE BLUE CIRCLE}'
enter_side = ({'enter': 'Long', 'entered': 'Longed'} if msg['direction'] == 'Long'
entry_side = ({'enter': 'Long', 'entered': 'Longed'} if msg['direction'] == 'Long'
else {'enter': 'Short', 'entered': 'Shorted'})
message = (
f"{emoji} *{msg['exchange']}:*"
f" {enter_side['entered'] if is_fill else enter_side['enter']} {msg['pair']}"
f" {entry_side['entered'] if is_fill else entry_side['enter']} {msg['pair']}"
f" (#{msg['trade_id']})\n"
)
message += f"*Enter Tag:* `{msg['enter_tag']}`\n" if msg.get('enter_tag', None) else ""

View File

@ -90,10 +90,10 @@ class IStrategy(ABC, HyperStrategyMixin):
# run "populate_indicators" only for new candle
process_only_new_candles: bool = False
use_sell_signal: bool
sell_profit_only: bool
sell_profit_offset: float
ignore_roi_if_buy_signal: bool
use_exit_signal: bool
exit_profit_only: bool
exit_profit_offset: float
ignore_roi_if_entry_signal: bool
# Position adjustment is disabled by default
position_adjustment_enable: bool = False
@ -871,7 +871,7 @@ class IStrategy(ABC, HyperStrategyMixin):
current_profit = trade.calc_profit_ratio(current_rate)
# if enter signal and ignore_roi is set, we don't need to evaluate min_roi.
roi_reached = (not (enter and self.ignore_roi_if_buy_signal)
roi_reached = (not (enter and self.ignore_roi_if_entry_signal)
and self.min_roi_reached(trade=trade, current_profit=current_profit,
current_time=current_time))
@ -881,10 +881,10 @@ class IStrategy(ABC, HyperStrategyMixin):
current_rate = rate
current_profit = trade.calc_profit_ratio(current_rate)
if (self.sell_profit_only and current_profit <= self.sell_profit_offset):
# sell_profit_only and profit doesn't reach the offset - ignore sell signal
if (self.exit_profit_only and current_profit <= self.exit_profit_offset):
# exit_profit_only and profit doesn't reach the offset - ignore sell signal
pass
elif self.use_sell_signal and not enter:
elif self.use_exit_signal and not enter:
if exit_:
exit_signal = ExitType.EXIT_SIGNAL
else:
@ -1044,7 +1044,7 @@ class IStrategy(ABC, HyperStrategyMixin):
FT Internal method.
Check if timeout is active, and if the order is still open and timed out
"""
side = 'entry' if order.ft_order_side == trade.enter_side else 'exit'
side = 'entry' if order.ft_order_side == trade.entry_side else 'exit'
timeout = self.config.get('unfilledtimeout', {}).get(side)
if timeout is not None:

View File

@ -65,9 +65,9 @@ class {{ strategy }}(IStrategy):
process_only_new_candles = False
# These values can be overridden in the config.
use_sell_signal = True
sell_profit_only = False
ignore_roi_if_buy_signal = False
use_exit_signal = True
exit_profit_only = False
ignore_roi_if_entry_signal = False
# Number of candles the strategy requires before producing valid signals
startup_candle_count: int = 30

View File

@ -65,9 +65,9 @@ class SampleStrategy(IStrategy):
process_only_new_candles = False
# These values can be overridden in the config.
use_sell_signal = True
sell_profit_only = False
ignore_roi_if_buy_signal = False
use_exit_signal = True
exit_profit_only = False
ignore_roi_if_entry_signal = False
# Hyperoptable parameters
buy_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)

View File

@ -826,8 +826,9 @@ def test_download_data_trades(mocker, caplog):
]
with pytest.raises(OperationalException,
match="Trade download not supported for futures."):
start_download_data(get_args(args))
pargs = get_args(args)
pargs['config'] = None
start_download_data(pargs)
def test_start_convert_trades(mocker, caplog):

View File

@ -6,7 +6,7 @@ from freqtrade.persistence.models import Order, Trade
MOCK_TRADE_COUNT = 6
def enter_side(is_short: bool):
def entry_side(is_short: bool):
return "sell" if is_short else "buy"
@ -23,7 +23,7 @@ def mock_order_1(is_short: bool):
'id': f'1234_{direc(is_short)}',
'symbol': 'ETH/BTC',
'status': 'closed',
'side': enter_side(is_short),
'side': entry_side(is_short),
'type': 'limit',
'price': 0.123,
'average': 0.123,
@ -50,7 +50,7 @@ def mock_trade_1(fee, is_short: bool):
timeframe=5,
is_short=is_short
)
o = Order.parse_from_ccxt_object(mock_order_1(is_short), 'ETH/BTC', enter_side(is_short))
o = Order.parse_from_ccxt_object(mock_order_1(is_short), 'ETH/BTC', entry_side(is_short))
trade.orders.append(o)
return trade
@ -60,7 +60,7 @@ def mock_order_2(is_short: bool):
'id': f'1235_{direc(is_short)}',
'symbol': 'ETC/BTC',
'status': 'closed',
'side': enter_side(is_short),
'side': entry_side(is_short),
'type': 'limit',
'price': 0.123,
'amount': 123.0,
@ -109,7 +109,7 @@ def mock_trade_2(fee, is_short: bool):
close_date=datetime.now(tz=timezone.utc) - timedelta(minutes=2),
is_short=is_short
)
o = Order.parse_from_ccxt_object(mock_order_2(is_short), 'ETC/BTC', enter_side(is_short))
o = Order.parse_from_ccxt_object(mock_order_2(is_short), 'ETC/BTC', entry_side(is_short))
trade.orders.append(o)
o = Order.parse_from_ccxt_object(mock_order_2_sell(is_short), 'ETC/BTC', exit_side(is_short))
trade.orders.append(o)
@ -121,7 +121,7 @@ def mock_order_3(is_short: bool):
'id': f'41231a12a_{direc(is_short)}',
'symbol': 'XRP/BTC',
'status': 'closed',
'side': enter_side(is_short),
'side': entry_side(is_short),
'type': 'limit',
'price': 0.05,
'amount': 123.0,
@ -169,7 +169,7 @@ def mock_trade_3(fee, is_short: bool):
close_date=datetime.now(tz=timezone.utc),
is_short=is_short
)
o = Order.parse_from_ccxt_object(mock_order_3(is_short), 'XRP/BTC', enter_side(is_short))
o = Order.parse_from_ccxt_object(mock_order_3(is_short), 'XRP/BTC', entry_side(is_short))
trade.orders.append(o)
o = Order.parse_from_ccxt_object(mock_order_3_sell(is_short), 'XRP/BTC', exit_side(is_short))
trade.orders.append(o)
@ -181,7 +181,7 @@ def mock_order_4(is_short: bool):
'id': f'prod_buy_{direc(is_short)}_12345',
'symbol': 'ETC/BTC',
'status': 'open',
'side': enter_side(is_short),
'side': entry_side(is_short),
'type': 'limit',
'price': 0.123,
'amount': 123.0,
@ -210,7 +210,7 @@ def mock_trade_4(fee, is_short: bool):
timeframe=5,
is_short=is_short
)
o = Order.parse_from_ccxt_object(mock_order_4(is_short), 'ETC/BTC', enter_side(is_short))
o = Order.parse_from_ccxt_object(mock_order_4(is_short), 'ETC/BTC', entry_side(is_short))
trade.orders.append(o)
return trade
@ -220,7 +220,7 @@ def mock_order_5(is_short: bool):
'id': f'prod_buy_{direc(is_short)}_3455',
'symbol': 'XRP/BTC',
'status': 'closed',
'side': enter_side(is_short),
'side': entry_side(is_short),
'type': 'limit',
'price': 0.123,
'amount': 123.0,
@ -264,7 +264,7 @@ def mock_trade_5(fee, is_short: bool):
timeframe=5,
is_short=is_short
)
o = Order.parse_from_ccxt_object(mock_order_5(is_short), 'XRP/BTC', enter_side(is_short))
o = Order.parse_from_ccxt_object(mock_order_5(is_short), 'XRP/BTC', entry_side(is_short))
trade.orders.append(o)
o = Order.parse_from_ccxt_object(mock_order_5_stoploss(is_short), 'XRP/BTC', 'stoploss')
trade.orders.append(o)
@ -276,7 +276,7 @@ def mock_order_6(is_short: bool):
'id': f'prod_buy_{direc(is_short)}_6',
'symbol': 'LTC/BTC',
'status': 'closed',
'side': enter_side(is_short),
'side': entry_side(is_short),
'type': 'limit',
'price': 0.15,
'amount': 2.0,
@ -320,7 +320,7 @@ def mock_trade_6(fee, is_short: bool):
timeframe=5,
is_short=is_short
)
o = Order.parse_from_ccxt_object(mock_order_6(is_short), 'LTC/BTC', enter_side(is_short))
o = Order.parse_from_ccxt_object(mock_order_6(is_short), 'LTC/BTC', entry_side(is_short))
trade.orders.append(o)
o = Order.parse_from_ccxt_object(mock_order_6_sell(is_short), 'LTC/BTC', exit_side(is_short))
trade.orders.append(o)

View File

@ -821,7 +821,7 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data: BTContainer)
if data.trailing_stop_positive is not None:
default_conf["trailing_stop_positive"] = data.trailing_stop_positive
default_conf["trailing_stop_positive_offset"] = data.trailing_stop_positive_offset
default_conf["use_sell_signal"] = data.use_exit_signal
default_conf["use_exit_signal"] = data.use_exit_signal
mocker.patch("freqtrade.exchange.Exchange.get_fee", return_value=0.0)
mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001)

View File

@ -504,7 +504,7 @@ def test_backtesting_pairlist_list(default_conf, mocker, caplog, testdatadir, ti
def test_backtest__enter_trade(default_conf, fee, mocker) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))
@ -563,7 +563,7 @@ def test_backtest__enter_trade(default_conf, fee, mocker) -> None:
def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
default_conf_usdt['use_sell_signal'] = False
default_conf_usdt['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))
@ -645,7 +645,7 @@ def test_backtest__enter_trade_futures(default_conf_usdt, fee, mocker) -> None:
def test_backtest__get_sell_trade_entry(default_conf, fee, mocker) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))
@ -740,7 +740,7 @@ def test_backtest__get_sell_trade_entry(default_conf, fee, mocker) -> None:
def test_backtest_one(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))
@ -807,7 +807,7 @@ def test_backtest_one(default_conf, fee, mocker, testdatadir) -> None:
def test_backtest_1min_timeframe(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))
@ -833,7 +833,7 @@ def test_backtest_1min_timeframe(default_conf, fee, mocker, testdatadir) -> None
def test_backtest_trim_no_data_left(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))
@ -878,7 +878,7 @@ def test_processed(default_conf, mocker, testdatadir) -> None:
def test_backtest_dataprovider_analyzed_df(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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=100000)
@ -1151,10 +1151,10 @@ def test_backtest_start_timerange(default_conf, mocker, caplog, testdatadir):
def test_backtest_start_multi_strat(default_conf, mocker, caplog, testdatadir):
default_conf.update({
"use_sell_signal": True,
"sell_profit_only": False,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": False,
"use_exit_signal": True,
"exit_profit_only": False,
"exit_profit_offset": 0.0,
"ignore_roi_if_entry_signal": False,
})
patch_exchange(mocker)
backtestmock = MagicMock(return_value={
@ -1228,10 +1228,10 @@ def test_backtest_start_multi_strat(default_conf, mocker, caplog, testdatadir):
@pytest.mark.filterwarnings("ignore:deprecated")
def test_backtest_start_multi_strat_nomock(default_conf, mocker, caplog, testdatadir, capsys):
default_conf.update({
"use_sell_signal": True,
"sell_profit_only": False,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": False,
"use_exit_signal": True,
"exit_profit_only": False,
"exit_profit_offset": 0.0,
"ignore_roi_if_entry_signal": False,
})
patch_exchange(mocker)
result1 = pd.DataFrame({'pair': ['XRP/BTC', 'LTC/BTC'],
@ -1346,10 +1346,10 @@ def test_backtest_start_nomock_futures(default_conf_usdt, mocker,
default_conf_usdt.update({
"trading_mode": "futures",
"margin_mode": "isolated",
"use_sell_signal": True,
"sell_profit_only": False,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": False,
"use_exit_signal": True,
"exit_profit_only": False,
"exit_profit_offset": 0.0,
"ignore_roi_if_entry_signal": False,
"strategy": CURRENT_TEST_STRATEGY,
})
patch_exchange(mocker)
@ -1450,10 +1450,10 @@ def test_backtest_start_multi_strat_nomock_detail(default_conf, mocker,
caplog, testdatadir, capsys):
# Tests detail-data loading
default_conf.update({
"use_sell_signal": True,
"sell_profit_only": False,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": False,
"use_exit_signal": True,
"exit_profit_only": False,
"exit_profit_offset": 0.0,
"ignore_roi_if_entry_signal": False,
})
patch_exchange(mocker)
result1 = pd.DataFrame({'pair': ['XRP/BTC', 'LTC/BTC'],
@ -1557,10 +1557,10 @@ def test_backtest_start_multi_strat_nomock_detail(default_conf, mocker,
def test_backtest_start_multi_strat_caching(default_conf, mocker, caplog, testdatadir, run_id,
start_delta, cache):
default_conf.update({
"use_sell_signal": True,
"sell_profit_only": False,
"sell_profit_offset": 0.0,
"ignore_roi_if_buy_signal": False,
"use_exit_signal": True,
"exit_profit_only": False,
"exit_profit_offset": 0.0,
"ignore_roi_if_entry_signal": False,
})
patch_exchange(mocker)
backtestmock = MagicMock(return_value={

View File

@ -14,7 +14,7 @@ from tests.conftest import patch_exchange
def test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) -> None:
default_conf['use_sell_signal'] = False
default_conf['use_exit_signal'] = False
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
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'))

View File

@ -50,6 +50,8 @@ class StrategyTestV2(IStrategy):
'entry': 'gtc',
'exit': 'gtc',
}
# Test legacy use_sell_signal definition
use_sell_signal = False
# By default this strategy does not use Position Adjustments
position_adjustment_enable = False

View File

@ -183,7 +183,7 @@ class StrategyTestV3(IStrategy):
current_profit: float, min_stake: float, max_stake: float, **kwargs):
if current_profit < -0.0075:
orders = trade.select_filled_orders(trade.enter_side)
orders = trade.select_filled_orders(trade.entry_side)
return round(orders[0].cost, 0)
return None

View File

@ -143,16 +143,6 @@ def test_strategy_can_short(caplog, default_conf):
assert isinstance(strat, IStrategy)
def test_strategy_implements_populate_entry(caplog, default_conf):
caplog.set_level(logging.INFO)
default_conf.update({
'strategy': "StrategyTestV2",
})
default_conf['trading_mode'] = 'futures'
with pytest.raises(OperationalException, match="`populate_entry_trend` must be implemented."):
StrategyResolver.load_strategy(default_conf)
def test_strategy_override_minimal_roi(caplog, default_conf):
caplog.set_level(logging.INFO)
default_conf.update({
@ -310,50 +300,50 @@ def test_strategy_override_order_tif(caplog, default_conf):
StrategyResolver.load_strategy(default_conf)
def test_strategy_override_use_sell_signal(caplog, default_conf):
def test_strategy_override_use_exit_signal(caplog, default_conf):
caplog.set_level(logging.INFO)
default_conf.update({
'strategy': CURRENT_TEST_STRATEGY,
})
strategy = StrategyResolver.load_strategy(default_conf)
assert strategy.use_sell_signal
assert isinstance(strategy.use_sell_signal, bool)
assert strategy.use_exit_signal
assert isinstance(strategy.use_exit_signal, bool)
# must be inserted to configuration
assert 'use_sell_signal' in default_conf
assert default_conf['use_sell_signal']
assert 'use_exit_signal' in default_conf
assert default_conf['use_exit_signal']
default_conf.update({
'strategy': CURRENT_TEST_STRATEGY,
'use_sell_signal': False,
'use_exit_signal': False,
})
strategy = StrategyResolver.load_strategy(default_conf)
assert not strategy.use_sell_signal
assert isinstance(strategy.use_sell_signal, bool)
assert log_has("Override strategy 'use_sell_signal' with value in config file: False.", caplog)
assert not strategy.use_exit_signal
assert isinstance(strategy.use_exit_signal, bool)
assert log_has("Override strategy 'use_exit_signal' with value in config file: False.", caplog)
def test_strategy_override_use_sell_profit_only(caplog, default_conf):
def test_strategy_override_use_exit_profit_only(caplog, default_conf):
caplog.set_level(logging.INFO)
default_conf.update({
'strategy': CURRENT_TEST_STRATEGY,
})
strategy = StrategyResolver.load_strategy(default_conf)
assert not strategy.sell_profit_only
assert isinstance(strategy.sell_profit_only, bool)
assert not strategy.exit_profit_only
assert isinstance(strategy.exit_profit_only, bool)
# must be inserted to configuration
assert 'sell_profit_only' in default_conf
assert not default_conf['sell_profit_only']
assert 'exit_profit_only' in default_conf
assert not default_conf['exit_profit_only']
default_conf.update({
'strategy': CURRENT_TEST_STRATEGY,
'sell_profit_only': True,
'exit_profit_only': True,
})
strategy = StrategyResolver.load_strategy(default_conf)
assert strategy.sell_profit_only
assert isinstance(strategy.sell_profit_only, bool)
assert log_has("Override strategy 'sell_profit_only' with value in config file: True.", caplog)
assert strategy.exit_profit_only
assert isinstance(strategy.exit_profit_only, bool)
assert log_has("Override strategy 'exit_profit_only' with value in config file: True.", caplog)
@pytest.mark.filterwarnings("ignore:deprecated")
@ -391,7 +381,22 @@ def test_deprecate_populate_indicators(result, default_conf):
@pytest.mark.filterwarnings("ignore:deprecated")
def test_missing_implements(default_conf):
def test_missing_implements(default_conf, caplog):
default_location = Path(__file__).parent / "strats"
default_conf.update({'strategy': 'StrategyTestV2',
'strategy_path': default_location})
StrategyResolver.load_strategy(default_conf)
log_has_re(r"DEPRECATED: .*use_sell_signal.*use_exit_signal.", caplog)
default_conf['trading_mode'] = 'futures'
with pytest.raises(OperationalException,
match=r"DEPRECATED: .*use_sell_signal.*use_exit_signal."):
StrategyResolver.load_strategy(default_conf)
default_conf['trading_mode'] = 'spot'
default_location = Path(__file__).parent / "strats/broken_strats"
default_conf.update({'strategy': 'TestStrategyNoImplements',
'strategy_path': default_location})

View File

@ -868,15 +868,15 @@ def test_validate_tsl(default_conf):
def test_validate_edge2(edge_conf):
edge_conf.update({
"use_sell_signal": True,
"use_exit_signal": True,
})
# Passes test
validate_config_consistency(edge_conf)
edge_conf.update({
"use_sell_signal": False,
"use_exit_signal": False,
})
with pytest.raises(OperationalException, match="Edge requires `use_sell_signal` to be True, "
with pytest.raises(OperationalException, match="Edge requires `use_exit_signal` to be True, "
"otherwise no sells will happen."):
validate_config_consistency(edge_conf)
@ -1238,14 +1238,8 @@ def test_pairlist_resolving_fallback(mocker):
@pytest.mark.parametrize("setting", [
("ask_strategy", "use_sell_signal", True,
None, "use_sell_signal", False),
("ask_strategy", "sell_profit_only", True,
None, "sell_profit_only", False),
("ask_strategy", "sell_profit_offset", 0.1,
None, "sell_profit_offset", 0.01),
("ask_strategy", "ignore_roi_if_buy_signal", True,
None, "ignore_roi_if_buy_signal", False),
("webhook", "webhookbuy", 'testWEbhook',
"webhook", "webhookentry", 'testWEbhook'),
("ask_strategy", "ignore_buying_expired_candle_after", 5,
None, "ignore_buying_expired_candle_after", 6),
])

View File

@ -25,7 +25,7 @@ from freqtrade.worker import Worker
from tests.conftest import (create_mock_trades, get_patched_freqtradebot, get_patched_worker,
log_has, log_has_re, patch_edge, patch_exchange, patch_get_signal,
patch_wallet, patch_whitelist)
from tests.conftest_trades import (MOCK_TRADE_COUNT, enter_side, exit_side, mock_order_1,
from tests.conftest_trades import (MOCK_TRADE_COUNT, entry_side, exit_side, mock_order_1,
mock_order_2, mock_order_2_sell, mock_order_3, mock_order_3_sell,
mock_order_4, mock_order_5_stoploss, mock_order_6_sell)
@ -303,7 +303,7 @@ def test_create_trade(default_conf_usdt, ticker_usdt, limit_order,
# Simulate fulfilled LIMIT_BUY order for trade
oobj = Order.parse_from_ccxt_object(
limit_order[enter_side(is_short)], 'ADA/USDT', enter_side(is_short))
limit_order[entry_side(is_short)], 'ADA/USDT', entry_side(is_short))
trade.update_trade(oobj)
assert trade.open_rate == open_rate
@ -341,7 +341,7 @@ def test_create_trade_minimal_amount(
) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
enter_mock = MagicMock(return_value=limit_order_open[enter_side(is_short)])
enter_mock = MagicMock(return_value=limit_order_open[entry_side(is_short)])
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=ticker_usdt,
@ -537,8 +537,8 @@ def test_process_trade_creation(default_conf_usdt, ticker_usdt, limit_order, lim
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=ticker_usdt,
create_order=MagicMock(return_value=limit_order_open[enter_side(is_short)]),
fetch_order=MagicMock(return_value=limit_order[enter_side(is_short)]),
create_order=MagicMock(return_value=limit_order_open[entry_side(is_short)]),
fetch_order=MagicMock(return_value=limit_order[entry_side(is_short)]),
get_fee=fee,
)
freqtrade = FreqtradeBot(default_conf_usdt)
@ -751,8 +751,8 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order,
(10 - (2 / 1)) / (1 - (0.01 + 0.0006)) = 8.085708510208207
"""
# TODO: Split this test into multiple tests to improve readability
open_order = limit_order_open[enter_side(is_short)]
order = limit_order[enter_side(is_short)]
open_order = limit_order_open[entry_side(is_short)]
order = limit_order[entry_side(is_short)]
default_conf_usdt['trading_mode'] = trading_mode
default_conf_usdt['liquidation_buffer'] = liq_buffer
leverage = 1.0 if trading_mode == 'spot' else 5.0
@ -975,7 +975,7 @@ def test_execute_entry_confirm_error(mocker, default_conf_usdt, fee, limit_order
'ask': 2.2,
'last': 1.9
}),
create_order=MagicMock(return_value=limit_order[enter_side(is_short)]),
create_order=MagicMock(return_value=limit_order[entry_side(is_short)]),
get_rate=MagicMock(return_value=0.11),
get_min_pair_stake_amount=MagicMock(return_value=1),
get_fee=fee,
@ -986,11 +986,11 @@ def test_execute_entry_confirm_error(mocker, default_conf_usdt, fee, limit_order
freqtrade.strategy.confirm_trade_entry = MagicMock(side_effect=ValueError)
assert freqtrade.execute_entry(pair, stake_amount)
limit_order[enter_side(is_short)]['id'] = '222'
limit_order[entry_side(is_short)]['id'] = '222'
freqtrade.strategy.confirm_trade_entry = MagicMock(side_effect=Exception)
assert freqtrade.execute_entry(pair, stake_amount)
limit_order[enter_side(is_short)]['id'] = '2223'
limit_order[entry_side(is_short)]['id'] = '2223'
freqtrade.strategy.confirm_trade_entry = MagicMock(return_value=True)
assert freqtrade.execute_entry(pair, stake_amount)
@ -1010,7 +1010,7 @@ def test_execute_entry_min_leverage(mocker, default_conf_usdt, fee, limit_order,
'ask': 2.2,
'last': 1.9
}),
create_order=MagicMock(return_value=limit_order[enter_side(is_short)]),
create_order=MagicMock(return_value=limit_order[entry_side(is_short)]),
get_rate=MagicMock(return_value=0.11),
# Minimum stake-amount is ~5$
get_maintenance_ratio_and_amt=MagicMock(return_value=(0.0, 0.0)),
@ -1032,7 +1032,7 @@ def test_execute_entry_min_leverage(mocker, default_conf_usdt, fee, limit_order,
def test_add_stoploss_on_exchange(mocker, default_conf_usdt, limit_order, is_short) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
order = limit_order[enter_side(is_short)]
order = limit_order[entry_side(is_short)]
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.get_trades_for_order', return_value=[])
@ -1062,7 +1062,7 @@ def test_add_stoploss_on_exchange(mocker, default_conf_usdt, limit_order, is_sho
def test_handle_stoploss_on_exchange(mocker, default_conf_usdt, fee, caplog, is_short,
limit_order) -> None:
stoploss = MagicMock(return_value={'id': 13434334})
enter_order = limit_order[enter_side(is_short)]
enter_order = limit_order[entry_side(is_short)]
exit_order = limit_order[exit_side(is_short)]
patch_RPCManager(mocker)
patch_exchange(mocker)
@ -1217,7 +1217,7 @@ def test_handle_stoploss_on_exchange(mocker, default_conf_usdt, fee, caplog, is_
def test_handle_sle_cancel_cant_recreate(mocker, default_conf_usdt, fee, caplog, is_short,
limit_order) -> None:
# Sixth case: stoploss order was cancelled but couldn't create new one
enter_order = limit_order[enter_side(is_short)]
enter_order = limit_order[entry_side(is_short)]
exit_order = limit_order[exit_side(is_short)]
patch_RPCManager(mocker)
patch_exchange(mocker)
@ -1260,7 +1260,7 @@ def test_handle_sle_cancel_cant_recreate(mocker, default_conf_usdt, fee, caplog,
def test_create_stoploss_order_invalid_order(
mocker, default_conf_usdt, caplog, fee, is_short, limit_order, limit_order_open
):
open_order = limit_order_open[enter_side(is_short)]
open_order = limit_order_open[entry_side(is_short)]
order = limit_order[exit_side(is_short)]
rpc_mock = patch_RPCManager(mocker)
patch_exchange(mocker)
@ -1325,7 +1325,7 @@ def test_create_stoploss_order_insufficient_funds(
'last': 1.9
}),
create_order=MagicMock(side_effect=[
limit_order[enter_side(is_short)],
limit_order[entry_side(is_short)],
exit_order,
]),
get_fee=fee,
@ -1364,7 +1364,7 @@ def test_handle_stoploss_on_exchange_trailing(
mocker, default_conf_usdt, fee, is_short, bid, ask, limit_order, stop_price, amt, hang_price
) -> None:
# When trailing stoploss is set
enter_order = limit_order[enter_side(is_short)]
enter_order = limit_order[entry_side(is_short)]
exit_order = limit_order[exit_side(is_short)]
stoploss = MagicMock(return_value={'id': 13434334})
patch_RPCManager(mocker)
@ -1485,7 +1485,7 @@ def test_handle_stoploss_on_exchange_trailing(
def test_handle_stoploss_on_exchange_trailing_error(
mocker, default_conf_usdt, fee, caplog, limit_order, is_short
) -> None:
enter_order = limit_order[enter_side(is_short)]
enter_order = limit_order[entry_side(is_short)]
exit_order = limit_order[exit_side(is_short)]
# When trailing stoploss is set
stoploss = MagicMock(return_value={'id': 13434334})
@ -1593,7 +1593,7 @@ def test_stoploss_on_exchange_price_rounding(
def test_handle_stoploss_on_exchange_custom_stop(
mocker, default_conf_usdt, fee, is_short, limit_order
) -> None:
enter_order = limit_order[enter_side(is_short)]
enter_order = limit_order[entry_side(is_short)]
exit_order = limit_order[exit_side(is_short)]
# When trailing stoploss is set
stoploss = MagicMock(return_value={'id': 13434334})
@ -1860,10 +1860,10 @@ def test_exit_positions(mocker, default_conf_usdt, limit_order, is_short, caplog
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True))
mocker.patch('freqtrade.exchange.Exchange.fetch_order',
return_value=limit_order[enter_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.freqtradebot.FreqtradeBot.get_real_amount',
return_value=limit_order[enter_side(is_short)]['amount'])
return_value=limit_order[entry_side(is_short)]['amount'])
trade = MagicMock()
trade.is_short = is_short
@ -1886,7 +1886,7 @@ def test_exit_positions(mocker, default_conf_usdt, limit_order, is_short, caplog
@pytest.mark.parametrize("is_short", [False, True])
def test_exit_positions_exception(mocker, default_conf_usdt, limit_order, caplog, is_short) -> None:
freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt)
order = limit_order[enter_side(is_short)]
order = limit_order[entry_side(is_short)]
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
trade = MagicMock()
@ -1909,7 +1909,7 @@ def test_exit_positions_exception(mocker, default_conf_usdt, limit_order, caplog
@pytest.mark.parametrize("is_short", [False, True])
def test_update_trade_state(mocker, default_conf_usdt, limit_order, is_short, caplog) -> None:
freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt)
order = limit_order[enter_side(is_short)]
order = limit_order[entry_side(is_short)]
mocker.patch('freqtrade.freqtradebot.FreqtradeBot.handle_trade', MagicMock(return_value=True))
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
@ -1930,7 +1930,7 @@ def test_update_trade_state(mocker, default_conf_usdt, limit_order, is_short, ca
leverage=1,
)
trade.orders.append(Order(
ft_order_side=enter_side(is_short),
ft_order_side=entry_side(is_short),
price=0.01,
order_id=order_id,
@ -1980,7 +1980,7 @@ def test_update_trade_state_withorderdict(
default_conf_usdt, trades_for_order, limit_order, fee, mocker, initial_amount,
has_rounding_fee, is_short, caplog
):
order = limit_order[enter_side(is_short)]
order = limit_order[entry_side(is_short)]
trades_for_order[0]['amount'] = initial_amount
order_id = "oid_123456"
order['id'] = order_id
@ -2006,7 +2006,7 @@ def test_update_trade_state_withorderdict(
)
trade.orders.append(
Order(
ft_order_side=enter_side(is_short),
ft_order_side=entry_side(is_short),
ft_pair=trade.pair,
ft_is_open=True,
order_id=order_id,
@ -2026,7 +2026,7 @@ def test_update_trade_state_withorderdict(
@pytest.mark.parametrize("is_short", [False, True])
def test_update_trade_state_exception(mocker, default_conf_usdt, is_short, limit_order,
caplog) -> None:
order = limit_order[enter_side(is_short)]
order = limit_order[entry_side(is_short)]
freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt)
mocker.patch('freqtrade.exchange.Exchange.fetch_order', return_value=order)
@ -2107,7 +2107,7 @@ def test_handle_trade(
default_conf_usdt, limit_order_open, limit_order, fee, mocker, is_short, close_profit
) -> None:
open_order = limit_order_open[exit_side(is_short)]
enter_order = limit_order[enter_side(is_short)]
enter_order = limit_order[entry_side(is_short)]
exit_order = limit_order[exit_side(is_short)]
patch_RPCManager(mocker)
patch_exchange(mocker)
@ -2134,7 +2134,7 @@ def test_handle_trade(
assert trade
time.sleep(0.01) # Race condition fix
oobj = Order.parse_from_ccxt_object(enter_order, enter_order['symbol'], enter_side(is_short))
oobj = Order.parse_from_ccxt_object(enter_order, enter_order['symbol'], entry_side(is_short))
trade.update_trade(oobj)
assert trade.is_open is True
freqtrade.wallets.update()
@ -2235,7 +2235,7 @@ def test_handle_overlapping_signals(
def test_handle_trade_roi(default_conf_usdt, ticker_usdt, limit_order_open, fee, mocker, caplog,
is_short) -> None:
open_order = limit_order_open[enter_side(is_short)]
open_order = limit_order_open[entry_side(is_short)]
caplog.set_level(logging.DEBUG)
@ -2273,14 +2273,14 @@ def test_handle_trade_roi(default_conf_usdt, ticker_usdt, limit_order_open, fee,
@pytest.mark.parametrize("is_short", [False, True])
def test_handle_trade_use_sell_signal(
def test_handle_trade_use_exit_signal(
default_conf_usdt, ticker_usdt, limit_order_open, fee, mocker, caplog, is_short
) -> None:
enter_open_order = limit_order_open[exit_side(is_short)]
exit_open_order = limit_order_open[enter_side(is_short)]
exit_open_order = limit_order_open[entry_side(is_short)]
# use_sell_signal is True buy default
# use_exit_signal is True buy default
caplog.set_level(logging.DEBUG)
patch_RPCManager(mocker)
mocker.patch.multiple(
@ -2320,7 +2320,7 @@ def test_close_trade(
) -> None:
open_order = limit_order_open[exit_side(is_short)]
enter_order = limit_order[exit_side(is_short)]
exit_order = limit_order[enter_side(is_short)]
exit_order = limit_order[entry_side(is_short)]
patch_RPCManager(mocker)
patch_exchange(mocker)
mocker.patch.multiple(
@ -2766,7 +2766,7 @@ def test_check_handle_timedout_partial_fee(
assert trades[0].amount == (limit_buy_order_old_partial['amount'] -
limit_buy_order_old_partial['remaining']) - 0.023
assert trades[0].open_order_id is None
assert trades[0].fee_updated(open_trade.enter_side)
assert trades[0].fee_updated(open_trade.entry_side)
assert pytest.approx(trades[0].fee_open) == 0.001
@ -2853,8 +2853,8 @@ def test_check_handle_timedout_exception(default_conf_usdt, ticker_usdt, open_tr
def test_handle_cancel_enter(mocker, caplog, default_conf_usdt, limit_order, is_short) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
l_order = limit_order[enter_side(is_short)]
cancel_buy_order = deepcopy(limit_order[enter_side(is_short)])
l_order = limit_order[entry_side(is_short)]
cancel_buy_order = deepcopy(limit_order[entry_side(is_short)])
cancel_buy_order['status'] = 'canceled'
del cancel_buy_order['filled']
@ -2868,7 +2868,7 @@ def test_handle_cancel_enter(mocker, caplog, default_conf_usdt, limit_order, is_
trade.pair = 'LTC/USDT'
trade.open_rate = 200
trade.is_short = False
trade.enter_side = "buy"
trade.entry_side = "buy"
l_order['filled'] = 0.0
l_order['status'] = 'open'
reason = CANCEL_REASON['TIMEOUT']
@ -2896,7 +2896,7 @@ def test_handle_cancel_enter(mocker, caplog, default_conf_usdt, limit_order, is_
assert log_has_re(r"Order .* for .* not cancelled.", caplog)
# min_pair_stake empty should not crash
mocker.patch('freqtrade.exchange.Exchange.get_min_pair_stake_amount', return_value=None)
assert not freqtrade.handle_cancel_enter(trade, limit_order[enter_side(is_short)], reason)
assert not freqtrade.handle_cancel_enter(trade, limit_order[entry_side(is_short)], reason)
@pytest.mark.parametrize("is_short", [False, True])
@ -2915,11 +2915,11 @@ def test_handle_cancel_enter_exchanges(mocker, caplog, default_conf_usdt, is_sho
reason = CANCEL_REASON['TIMEOUT']
trade = MagicMock()
trade.pair = 'LTC/ETH'
trade.enter_side = "sell" if is_short else "buy"
trade.entry_side = "sell" if is_short else "buy"
assert freqtrade.handle_cancel_enter(trade, limit_buy_order_canceled_empty, reason)
assert cancel_order_mock.call_count == 0
assert log_has_re(
f'{trade.enter_side.capitalize()} order fully cancelled. '
f'{trade.entry_side.capitalize()} order fully cancelled. '
r'Removing .* from database\.',
caplog
)
@ -2937,7 +2937,7 @@ def test_handle_cancel_enter_corder_empty(mocker, default_conf_usdt, limit_order
cancelorder) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
l_order = limit_order[enter_side(is_short)]
l_order = limit_order[entry_side(is_short)]
cancel_order_mock = MagicMock(return_value=cancelorder)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
@ -2949,9 +2949,9 @@ def test_handle_cancel_enter_corder_empty(mocker, default_conf_usdt, limit_order
trade = MagicMock()
trade.pair = 'LTC/USDT'
trade.enter_side = "buy"
trade.entry_side = "buy"
trade.open_rate = 200
trade.enter_side = "buy"
trade.entry_side = "buy"
l_order['filled'] = 0.0
l_order['status'] = 'open'
reason = CANCEL_REASON['TIMEOUT']
@ -3637,12 +3637,12 @@ def test_execute_trade_exit_insufficient_funds_error(default_conf_usdt, ticker_u
(False, 0.10, 0.22, True, False, ExitType.EXIT_SIGNAL.value, False),
(False, 0.10, 0.22, True, False, ExitType.EXIT_SIGNAL.value, True),
])
def test_sell_profit_only(
def test_exit_profit_only(
default_conf_usdt, limit_order, limit_order_open, is_short,
fee, mocker, profit_only, bid, ask, handle_first, handle_second, exit_type) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
eside = enter_side(is_short)
eside = entry_side(is_short)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=MagicMock(return_value={
@ -3657,9 +3657,9 @@ def test_sell_profit_only(
get_fee=fee,
)
default_conf_usdt.update({
'use_sell_signal': True,
'sell_profit_only': profit_only,
'sell_profit_offset': 0.1,
'use_exit_signal': True,
'exit_profit_only': profit_only,
'exit_profit_offset': 0.1,
})
freqtrade = FreqtradeBot(default_conf_usdt)
patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short)
@ -3679,7 +3679,7 @@ def test_sell_profit_only(
assert freqtrade.handle_trade(trade) is handle_first
if handle_second:
freqtrade.strategy.sell_profit_offset = 0.0
freqtrade.strategy.exit_profit_offset = 0.0
assert freqtrade.handle_trade(trade) is True
@ -3799,11 +3799,11 @@ def test_locked_pairs(default_conf_usdt, ticker_usdt, fee,
@pytest.mark.parametrize("is_short", [False, True])
def test_ignore_roi_if_buy_signal(default_conf_usdt, limit_order, limit_order_open, is_short,
fee, mocker) -> None:
def test_ignore_roi_if_entry_signal(default_conf_usdt, limit_order, limit_order_open, is_short,
fee, mocker) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
eside = enter_side(is_short)
eside = entry_side(is_short)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=MagicMock(return_value={
@ -3817,7 +3817,7 @@ def test_ignore_roi_if_buy_signal(default_conf_usdt, limit_order, limit_order_op
]),
get_fee=fee,
)
default_conf_usdt['ignore_roi_if_buy_signal'] = True
default_conf_usdt['ignore_roi_if_entry_signal'] = True
freqtrade = FreqtradeBot(default_conf_usdt)
patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short)
@ -3863,7 +3863,7 @@ def test_trailing_stop_loss(default_conf_usdt, limit_order_open,
'last': 2.0
}),
create_order=MagicMock(side_effect=[
limit_order_open[enter_side(is_short)],
limit_order_open[entry_side(is_short)],
{'id': 1234553382},
]),
get_fee=fee,
@ -3921,10 +3921,10 @@ def test_trailing_stop_loss_positive(
default_conf_usdt, limit_order, limit_order_open,
offset, fee, caplog, mocker, trail_if_reached, second_sl, is_short
) -> None:
enter_price = limit_order[enter_side(is_short)]['price']
enter_price = limit_order[entry_side(is_short)]['price']
patch_RPCManager(mocker)
patch_exchange(mocker)
eside = enter_side(is_short)
eside = entry_side(is_short)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=MagicMock(return_value={
@ -4016,11 +4016,11 @@ def test_trailing_stop_loss_positive(
@pytest.mark.parametrize("is_short", [False, True])
def test_disable_ignore_roi_if_buy_signal(default_conf_usdt, limit_order, limit_order_open,
is_short, fee, mocker) -> None:
def test_disable_ignore_roi_if_entry_signal(default_conf_usdt, limit_order, limit_order_open,
is_short, fee, mocker) -> None:
patch_RPCManager(mocker)
patch_exchange(mocker)
eside = enter_side(is_short)
eside = entry_side(is_short)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=MagicMock(return_value={
@ -4037,7 +4037,7 @@ def test_disable_ignore_roi_if_buy_signal(default_conf_usdt, limit_order, limit_
_is_dry_limit_order_filled=MagicMock(return_value=False),
)
default_conf_usdt['exit_pricing'] = {
'ignore_roi_if_buy_signal': False
'ignore_roi_if_entry_signal': False
}
freqtrade = FreqtradeBot(default_conf_usdt)
patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short)
@ -4424,7 +4424,7 @@ def test_order_book_depth_of_market(
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
fetch_ticker=ticker_usdt,
create_order=MagicMock(return_value=limit_order_open[enter_side(is_short)]),
create_order=MagicMock(return_value=limit_order_open[entry_side(is_short)]),
get_fee=fee,
)
@ -4449,7 +4449,7 @@ def test_order_book_depth_of_market(
# Simulate fulfilled LIMIT_BUY order for trade
oobj = Order.parse_from_ccxt_object(
limit_order_open[enter_side(is_short)], 'ADA/USDT', enter_side(is_short))
limit_order_open[entry_side(is_short)], 'ADA/USDT', entry_side(is_short))
trade.update_trade(oobj)
assert trade.open_rate == ticker_usdt.return_value[ticker_side]
@ -4638,7 +4638,7 @@ def test_cancel_all_open_orders(mocker, default_conf_usdt, fee, limit_order, lim
side_effect=[
ExchangeError(),
limit_order[exit_side(is_short)],
limit_order_open[enter_side(is_short)],
limit_order_open[entry_side(is_short)],
limit_order_open[exit_side(is_short)],
]
)
@ -4751,7 +4751,7 @@ def test_update_closed_trades_without_assigned_fees(mocker, default_conf_usdt, f
for trade in trades:
if trade.is_open:
# Exclude Trade 4 - as the order is still open.
if trade.select_order(enter_side(is_short), False):
if trade.select_order(entry_side(is_short), False):
assert trade.fee_open_cost is not None
assert trade.fee_open_currency is not None
else:
@ -5008,7 +5008,7 @@ def test_update_funding_fees(
# SETUP
time_machine.move_to("2021-09-01 00:00:00 +00:00")
open_order = limit_order_open[enter_side(is_short)]
open_order = limit_order_open[entry_side(is_short)]
open_exit_order = limit_order_open[exit_side(is_short)]
bid = 0.11
enter_rate_mock = MagicMock(return_value=bid)

View File

@ -76,7 +76,7 @@ def test_init_dryrun_db(default_conf, tmpdir):
@pytest.mark.parametrize('is_short', [False, True])
@pytest.mark.usefixtures("init_persistence")
def test_enter_exit_side(fee, is_short):
enter_side, exit_side = ("sell", "buy") if is_short else ("buy", "sell")
entry_side, exit_side = ("sell", "buy") if is_short else ("buy", "sell")
trade = Trade(
id=2,
pair='ADA/USDT',
@ -92,7 +92,7 @@ def test_enter_exit_side(fee, is_short):
leverage=2.0,
trading_mode=margin
)
assert trade.enter_side == enter_side
assert trade.entry_side == entry_side
assert trade.exit_side == exit_side
assert trade.trade_direction == 'short' if is_short else 'long'
@ -456,7 +456,7 @@ def test_update_limit_order(fee, caplog, limit_buy_order_usdt, limit_sell_order_
enter_order = limit_sell_order_usdt if is_short else limit_buy_order_usdt
exit_order = limit_buy_order_usdt if is_short else limit_sell_order_usdt
enter_side, exit_side = ("sell", "buy") if is_short else ("buy", "sell")
entry_side, exit_side = ("sell", "buy") if is_short else ("buy", "sell")
trade = Trade(
id=2,
@ -479,13 +479,13 @@ def test_update_limit_order(fee, caplog, limit_buy_order_usdt, limit_sell_order_
assert trade.close_date is None
trade.open_order_id = 'something'
oobj = Order.parse_from_ccxt_object(enter_order, 'ADA/USDT', enter_side)
oobj = Order.parse_from_ccxt_object(enter_order, 'ADA/USDT', entry_side)
trade.update_trade(oobj)
assert trade.open_order_id is None
assert trade.open_rate == open_rate
assert trade.close_profit is None
assert trade.close_date is None
assert log_has_re(f"LIMIT_{enter_side.upper()} has been fulfilled for "
assert log_has_re(f"LIMIT_{entry_side.upper()} has been fulfilled for "
r"Trade\(id=2, pair=ADA/USDT, amount=30.00000000, "
f"is_short={is_short}, leverage={lev}, open_rate={open_rate}0000000, "
r"open_since=.*\).",
@ -2135,19 +2135,19 @@ def test_select_order(fee, is_short):
trades = Trade.get_trades().all()
# Open buy order, no sell order
order = trades[0].select_order(trades[0].enter_side, True)
order = trades[0].select_order(trades[0].entry_side, True)
assert order is None
order = trades[0].select_order(trades[0].enter_side, False)
order = trades[0].select_order(trades[0].entry_side, False)
assert order is not None
order = trades[0].select_order(trades[0].exit_side, None)
assert order is None
# closed buy order, and open sell order
order = trades[1].select_order(trades[1].enter_side, True)
order = trades[1].select_order(trades[1].entry_side, True)
assert order is None
order = trades[1].select_order(trades[1].enter_side, False)
order = trades[1].select_order(trades[1].entry_side, False)
assert order is not None
order = trades[1].select_order(trades[1].enter_side, None)
order = trades[1].select_order(trades[1].entry_side, None)
assert order is not None
order = trades[1].select_order(trades[1].exit_side, True)
assert order is None
@ -2155,15 +2155,15 @@ def test_select_order(fee, is_short):
assert order is not None
# Has open buy order
order = trades[3].select_order(trades[3].enter_side, True)
order = trades[3].select_order(trades[3].entry_side, True)
assert order is not None
order = trades[3].select_order(trades[3].enter_side, False)
order = trades[3].select_order(trades[3].entry_side, False)
assert order is None
# Open sell order
order = trades[4].select_order(trades[4].enter_side, True)
order = trades[4].select_order(trades[4].entry_side, True)
assert order is None
order = trades[4].select_order(trades[4].enter_side, False)
order = trades[4].select_order(trades[4].entry_side, False)
assert order is not None
trades[4].orders[1].ft_order_side = trades[4].exit_side
@ -2386,7 +2386,7 @@ def test_recalc_trade_from_orders_ignores_bad_orders(fee, is_short):
o1_cost = o1_amount * o1_rate
o1_fee_cost = o1_cost * fee.return_value
o1_trade_val = o1_cost - o1_fee_cost if is_short else o1_cost + o1_fee_cost
enter_side = "sell" if is_short else "buy"
entry_side = "sell" if is_short else "buy"
exit_side = "buy" if is_short else "sell"
trade = Trade(
@ -2402,16 +2402,16 @@ def test_recalc_trade_from_orders_ignores_bad_orders(fee, is_short):
is_short=is_short,
leverage=1.0,
)
trade.update_fee(o1_fee_cost, 'BNB', fee.return_value, enter_side)
trade.update_fee(o1_fee_cost, 'BNB', fee.return_value, entry_side)
# Check with 1 order
order1 = Order(
ft_order_side=enter_side,
ft_order_side=entry_side,
ft_pair=trade.pair,
ft_is_open=False,
status="closed",
symbol=trade.pair,
order_type="market",
side=enter_side,
side=entry_side,
price=o1_rate,
average=o1_rate,
filled=o1_amount,
@ -2432,13 +2432,13 @@ def test_recalc_trade_from_orders_ignores_bad_orders(fee, is_short):
assert trade.nr_of_successful_entries == 1
order2 = Order(
ft_order_side=enter_side,
ft_order_side=entry_side,
ft_pair=trade.pair,
ft_is_open=True,
status="open",
symbol=trade.pair,
order_type="market",
side=enter_side,
side=entry_side,
price=o1_rate,
average=o1_rate,
filled=o1_amount,
@ -2460,13 +2460,13 @@ def test_recalc_trade_from_orders_ignores_bad_orders(fee, is_short):
# Let's try with some other orders
order3 = Order(
ft_order_side=enter_side,
ft_order_side=entry_side,
ft_pair=trade.pair,
ft_is_open=False,
status="cancelled",
symbol=trade.pair,
order_type="market",
side=enter_side,
side=entry_side,
price=1,
average=2,
filled=0,
@ -2487,13 +2487,13 @@ def test_recalc_trade_from_orders_ignores_bad_orders(fee, is_short):
assert trade.nr_of_successful_entries == 1
order4 = Order(
ft_order_side=enter_side,
ft_order_side=entry_side,
ft_pair=trade.pair,
ft_is_open=False,
status="closed",
symbol=trade.pair,
order_type="market",
side=enter_side,
side=entry_side,
price=o1_rate,
average=o1_rate,
filled=o1_amount,
@ -2542,13 +2542,13 @@ def test_recalc_trade_from_orders_ignores_bad_orders(fee, is_short):
# Check with 1 order
order_noavg = Order(
ft_order_side=enter_side,
ft_order_side=entry_side,
ft_pair=trade.pair,
ft_is_open=False,
status="closed",
symbol=trade.pair,
order_type="market",
side=enter_side,
side=entry_side,
price=o1_rate,
average=None,
filled=o1_amount,

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long