-
Notifications
You must be signed in to change notification settings - Fork 0
/
tp_activating_tsl_with_inital_tsl_strategy.py
136 lines (105 loc) · 6.12 KB
/
tp_activating_tsl_with_inital_tsl_strategy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
from datetime import datetime
import json
import time
from typing import Optional
from file_loading_strategy import FileLoadingStrategy
from freqtrade.strategy.strategy_helper import stoploss_from_open
from freqtrade.persistence import Trade
# additional imports required
from datetime import datetime
from typing import Any, Optional
from pandas import DataFrame
from typing import Dict
from custom_order_form_handler import OrderStatus
from file_loading_strategy import FileLoadingStrategy
from freqtrade.persistence import Trade
class TPActivatingTSLwithInitialTSLStrategy(FileLoadingStrategy):
"""
Similar to TPActivatingTSLwithSLStrategy but uses TSL initially rather than SL. Once TP hit, "tight" TSL is activated.
"""
# use default variable, no callback needed (self.custom_stoploss)
use_custom_stoploss = True
stoploss = -1.0 #default off
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, current_rate: float, current_profit: float, after_fill: bool, **kwargs) -> Optional[float]:
try:
tight_trailing_stop_loss = self.get_dfile_arg(
pair, 'tight_trailing_stop_loss')
loose_trailing_stop_loss = self.get_dfile_arg(
pair, 'loose_trailing_stop_loss')
profit_activating_tsl = self.get_dfile_arg(pair, 'profit_activating_tsl')
take_profit_hit = self.get_dfile_arg(pair, 'take_profit_hit')
# Calculating the percentage difference between the current rate and the open trade rate
# print(f"""
# ************
# tight_trailing_stop_loss {tight_trailing_stop_loss}
# loose_trailing_stop_loss {loose_trailing_stop_loss}
# profit_activating_tsl {profit_activating_tsl}
# """)
#print(f"current_rate: {current_rate} trade :{trade}")
# note: 1.0 == 1%
percentage_difference = ((current_rate - trade.open_rate) / trade.open_rate) * 100
print(f"\n (stoploss) {pair} percentage_difference: {percentage_difference} profit_activating_tsl: {profit_activating_tsl} take_profit_hit {take_profit_hit}\n")
# print(f"""
# TPActivatingTSLwithInitialTSLStrategy
# current_rate: {current_rate}
# open_rate: {trade.open_rate}
# percentage_difference: {percentage_difference}%
# profit_activating_tsl: {profit_activating_tsl}
# Is percentage_difference < profit_activating_tsl? {percentage_difference < profit_activating_tsl}
# """)
# Check if the percentage difference is below the threshold to activate trailing stop loss
if not take_profit_hit and percentage_difference < profit_activating_tsl:
# print(f"""
# current_profit: {current_profit}
# profit_activating_tsl: {profit_activating_tsl}
# loose_trailing_stop_loss: {loose_trailing_stop_loss}
# stoploss_from_open(-hard_stop_loss, current_profit, is_short=trade.is_short, leverage=trade.leverage): {-loose_trailing_stop_loss}
# """)
# at start or Negative profit, set hard stoploss as default
return -loose_trailing_stop_loss / 100 # convert to ratio
else: # HIT! turn on TSL
self.set_dfile_arg(pair, 'take_profit_hit', True)
return -tight_trailing_stop_loss / 100 # convert to ratio
except ValueError as e:
print(f"Error: get_dfile_arg in custom_stoploss: {e}")
return None
def input_strategy_data(self, pair: str):
print(f"How-to:\nUses LOOSE trailing stop loss initially. Once PROFIT-TARGET hit, TIGHT trailing stop loss is activated.\n")
loose_trailing_stop_loss = float(
input("Initial (LOOSE) trailing stop loss % (1 for -1%); this applies until your PROFIT-TARGET is hit: "))
tight_trailing_stop_loss = float(
input("Secondary (TIGHT) trailing stop loss % (1 for -1%): "))
profit_activating_tsl = float(
input("PROFIT-TARGET profit % to switch LOOSE TSL -> TIGHT TSL (1 for activation at 1% profit): "))
stake_amount = float(input("Enter the amount you wish to invest in this trade (leave blank for $10 default): "))
# New section for order confirmation
order_data = {
"profit_activating_tsl": profit_activating_tsl,
"take_profit_hit": False, # default "off"
"tight_trailing_stop_loss": tight_trailing_stop_loss,
"loose_trailing_stop_loss": loose_trailing_stop_loss,
"stake_amount": stake_amount
}
print("\nPlease review your order details:")
print(json.dumps(order_data, indent=4))
confirmation = input("Type 'Y' to confirm and submit your order, anything else to cancel: ").upper()
if confirmation == 'Y':
self.order_handler.update_strategy_data(pair, order_data, OrderStatus.PENDING)
print("\nSubmitted order!")
print(json.dumps(order_data, indent=4))
else:
print("\nCancelled placing order!")
time.sleep(3)
def set_entry_signal(self, pair: str, dataframe: DataFrame, data: Dict[str, Any]):
try:
loose_trailing_stop_loss = self.get_dfile_arg(
pair, 'loose_trailing_stop_loss')
tight_trailing_stop_loss = self.get_dfile_arg(
pair, 'tight_trailing_stop_loss')
profit_activating_tsl = self.get_dfile_arg(
pair, 'profit_activating_tsl')
dataframe.loc[dataframe.index[-1], ['enter_long',
'enter_tag']] = (1, f"TP&TSL&SL_user_enter_(TP={profit_activating_tsl}, Loose_TSL={loose_trailing_stop_loss}, Tight_TSL={tight_trailing_stop_loss})")
except Exception as e:
print(f"Error: set_entry_signal: {e}")
return None