Merge pull request #6276 from clover-es/feat/short

Add support for shorts in strategy.stoploss_from_absolute()
This commit is contained in:
Matthias
2022-01-25 19:11:05 +01:00
committed by GitHub
4 changed files with 35 additions and 20 deletions

View File

@@ -69,7 +69,7 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame,
def stoploss_from_open(
open_relative_stop: float,
current_profit: float,
for_short: bool = False
is_short: bool = False
) -> float:
"""
@@ -84,15 +84,15 @@ def stoploss_from_open(
:param open_relative_stop: Desired stop loss percentage relative to open price
:param current_profit: The current profit percentage
:param for_short: When true, perform the calculation for short instead of long
:param is_short: When true, perform the calculation for short instead of long
:return: Stop loss value relative to current price
"""
# formula is undefined for current_profit -1 (longs) or 1 (shorts), return maximum value
if (current_profit == -1 and not for_short) or (for_short and current_profit == 1):
if (current_profit == -1 and not is_short) or (is_short and current_profit == 1):
return 1
if for_short is True:
if is_short is True:
stoploss = -1+((1-open_relative_stop)/(1-current_profit))
else:
stoploss = 1-((1+open_relative_stop)/(1+current_profit))
@@ -102,9 +102,8 @@ def stoploss_from_open(
return max(stoploss, 0.0)
def stoploss_from_absolute(stop_rate: float, current_rate: float) -> float:
def stoploss_from_absolute(stop_rate: float, current_rate: float, is_short: bool = False) -> float:
"""
TODO-lev: Update this method with "is_short" formula
Given current price and desired stop price, return a stop loss value that is relative to current
price.
@@ -115,6 +114,7 @@ def stoploss_from_absolute(stop_rate: float, current_rate: float) -> float:
:param stop_rate: Stop loss price.
:param current_rate: Current asset price.
:param is_short: When true, perform the calculation for short instead of long
:return: Positive stop loss value relative to current price
"""
@@ -123,6 +123,10 @@ def stoploss_from_absolute(stop_rate: float, current_rate: float) -> float:
return 1
stoploss = 1 - (stop_rate / current_rate)
if is_short:
stoploss = -stoploss
# negative stoploss values indicate the requested stop price is higher than the current price
return max(stoploss, 0.0)
# negative stoploss values indicate the requested stop price is higher/lower
# (long/short) than the current price
# shorts can yield stoploss values higher than 1, so limit that as well
return max(min(stoploss, 1.0), 0.0)