Zeus_11 clean

This commit is contained in:
Jérôme Delacotte
2025-04-17 13:52:29 +02:00
parent 53beffc6d7
commit 7e169a9fe6
3 changed files with 227 additions and 190 deletions

View File

@@ -16,63 +16,7 @@
"max_open_trades": { "max_open_trades": {
"max_open_trades": 3 "max_open_trades": 3
}, },
"buy": {
"buy_rsi_1d": 45,
"buy_rsi_1h": 49,
"buy_sum_rsi_1d": 17.9,
"buy_sum_rsi_1h": 11.5
},
"sell": {
"pHSL": -0.99,
"pPF_1": 0.022,
"pSL_1": 0.015,
"pPF_2": 0.05,
"pSL_2": 0.03,
"profit_b_no_change": false,
"profit_b_old_sma10": false,
"profit_b_over_rsi": true,
"profit_b_quick_gain": false,
"profit_b_quick_gain_3": true,
"profit_b_quick_lost": true,
"profit_b_short_loss": false,
"profit_b_sma10": true,
"profit_b_sma20": false,
"profit_b_sma5": true,
"profit_b_very_old_sma10": false,
"profit_h_no_change": false,
"profit_h_old_sma10": false,
"profit_h_over_rsi": true,
"profit_h_quick_gain": true,
"profit_h_quick_gain_3": false,
"profit_h_quick_lost": true,
"profit_h_short_loss": true,
"profit_h_sma10": true,
"profit_h_sma20": true,
"profit_h_sma5": true,
"profit_h_very_old_sma10": false,
"sell_b_RSI": 87,
"sell_b_RSI2": 82,
"sell_b_RSI2_percent": 0.007,
"sell_b_RSI3": 75,
"sell_b_candels": 23,
"sell_b_percent": 0.014,
"sell_b_percent3": 0.018,
"sell_b_profit_no_change": 0.003,
"sell_b_profit_percent10": 0.0011,
"sell_b_too_old_day": 10,
"sell_b_too_old_percent": 0.013,
"sell_h_RSI": 82,
"sell_h_RSI2": 75,
"sell_h_RSI2_percent": 0.011,
"sell_h_RSI3": 97,
"sell_h_candels": 6,
"sell_h_percent": 0.009,
"sell_h_percent3": 0.016,
"sell_h_profit_no_change": 0.017,
"sell_h_profit_percent10": 0.0014,
"sell_h_too_old_day": 300,
"sell_h_too_old_percent": 0.004
},
"protection": { "protection": {
"protection_fibo": 9, "protection_fibo": 9,
"protection_percent_buy_lost": 3 "protection_percent_buy_lost": 3

View File

@@ -28,6 +28,11 @@ import talib.abstract as talib
import freqtrade.vendor.qtpylib.indicators as qtpylib import freqtrade.vendor.qtpylib.indicators as qtpylib
import requests import requests
from datetime import timezone, timedelta from datetime import timezone, timedelta
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -47,10 +52,7 @@ class Zeus_11(IStrategy):
# ROI table: # ROI table:
minimal_roi = { minimal_roi = {
"0": 0.564, "0": 10
"567": 0.273,
"2814": 0.12,
"7675": 0
} }
# Stoploss: # Stoploss:
@@ -112,72 +114,6 @@ class Zeus_11(IStrategy):
trades = list() trades = list()
max_profit_pairs = {} max_profit_pairs = {}
profit_b_no_change = BooleanParameter(default=True, space="sell")
profit_b_quick_lost = BooleanParameter(default=True, space="sell")
profit_b_sma5 = BooleanParameter(default=True, space="sell")
profit_b_sma10 = BooleanParameter(default=True, space="sell")
profit_b_sma20 = BooleanParameter(default=True, space="sell")
profit_b_quick_gain = BooleanParameter(default=True, space="sell")
profit_b_quick_gain_3 = BooleanParameter(default=True, space="sell")
profit_b_old_sma10 = BooleanParameter(default=True, space="sell")
profit_b_very_old_sma10 = BooleanParameter(default=True, space="sell")
profit_b_over_rsi = BooleanParameter(default=True, space="sell")
profit_b_short_loss = BooleanParameter(default=True, space="sell")
sell_b_percent = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
sell_b_percent3 = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
sell_b_candels = IntParameter(0, 48, default=12, space='sell')
sell_b_too_old_day = IntParameter(0, 10, default=300, space='sell')
sell_b_too_old_percent = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
sell_b_profit_no_change = DecimalParameter(0, 0.02, decimals=3, default=0.005, space='sell')
sell_b_profit_percent12 = DecimalParameter(0, 0.002, decimals=4, default=0.001, space='sell')
sell_b_RSI = IntParameter(70, 98, default=88, space='sell')
sell_b_RSI2 = IntParameter(70, 98, default=88, space='sell')
sell_b_RSI3 = IntParameter(70, 98, default=80, space='sell')
sell_b_RSI2_percent = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
# sell_b_expected_profit = DecimalParameter(0, 0.01, decimals=3, default=0.01, space='sell')
profit_h_no_change = BooleanParameter(default=True, space="sell")
profit_h_quick_lost = BooleanParameter(default=True, space="sell")
profit_h_sma5 = BooleanParameter(default=True, space="sell")
profit_h_sma10 = BooleanParameter(default=True, space="sell")
profit_h_sma20 = BooleanParameter(default=True, space="sell")
profit_h_quick_gain = BooleanParameter(default=True, space="sell")
profit_h_quick_gain_3 = BooleanParameter(default=True, space="sell")
profit_h_old_sma10 = BooleanParameter(default=True, space="sell")
profit_h_very_old_sma10 = BooleanParameter(default=True, space="sell")
profit_h_over_rsi = BooleanParameter(default=True, space="sell")
profit_h_short_loss = BooleanParameter(default=True, space="sell")
sell_h_percent = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
sell_h_percent3 = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
sell_h_candels = IntParameter(0, 48, default=12, space='sell')
sell_h_too_old_day = IntParameter(0, 10, default=300, space='sell')
sell_h_too_old_percent = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
sell_h_profit_no_change = DecimalParameter(0, 0.02, decimals=3, default=0.005, space='sell')
sell_h_profit_percent12 = DecimalParameter(0, 0.002, decimals=4, default=0.001, space='sell')
sell_h_RSI = IntParameter(70, 98, default=88, space='sell')
sell_h_RSI2 = IntParameter(70, 98, default=88, space='sell')
sell_h_RSI3 = IntParameter(70, 98, default=80, space='sell')
sell_h_RSI2_percent = DecimalParameter(0, 0.02, decimals=3, default=0.01, space='sell')
protection_percent_buy_lost = IntParameter(1, 10, default=5, space='protection')
# protection_nb_buy_lost = IntParameter(1, 2, default=2, space='protection')
protection_fibo = IntParameter(1, 10, default=2, space='protection')
# trailing stoploss hyperopt parameters
# hard stoploss profit
sell_allow_decrease = DecimalParameter(0.005, 0.02, default=0.2, decimals=2, space='sell', optimize=True, load=True)
pairs = { pairs = {
pair: { pair: {
"first_buy": 0, "first_buy": 0,
@@ -199,13 +135,13 @@ class Zeus_11(IStrategy):
"BTC/USDT", "ETH/USDT", "DOGE/USDT", "XRP/USDT", "SOL/USDT"] "BTC/USDT", "ETH/USDT", "DOGE/USDT", "XRP/USDT", "SOL/USDT"]
} }
def min_max_scaling(self, series: pd.Series) -> pd.Series: # def min_max_scaling(self, series: pd.Series) -> pd.Series:
"""Normaliser les données en les ramenant entre 0 et 100.""" # """Normaliser les données en les ramenant entre 0 et 100."""
return 100 * (series - series.min()) / (series.max() - series.min()) # return 100 * (series - series.min()) / (series.max() - series.min())
#
def z_score_scaling(self, series: pd.Series) -> pd.Series: # def z_score_scaling(self, series: pd.Series) -> pd.Series:
"""Normaliser les données en utilisant Z-Score Scaling.""" # """Normaliser les données en utilisant Z-Score Scaling."""
return (series - series.mean()) / series.std() # return (series - series.mean()) / series.std()
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str,
current_time: datetime, entry_tag: Optional[str], **kwargs) -> bool: current_time: datetime, entry_tag: Optional[str], **kwargs) -> bool:
@@ -232,7 +168,7 @@ class Zeus_11(IStrategy):
self.pairs[pair]['current_profit'] = 0 self.pairs[pair]['current_profit'] = 0
print( print(
f"|{'-' * 18}+{'-' * 12}+{'-' * 12}+{'-' * 20}+{'-' * 14}+{'-' * 8}+{'-' * 10}+{'-' * 7}+{'-' * 13}+{'-' * 14}+{'-' * 14}+{'-' * 7}+{'-' * 12}|" f"|{'-' * 18}+{'-' * 12}+{'-' * 5}+{'-' * 20}+{'-' * 14}+{'-' * 8}+{'-' * 10}+{'-' * 7}+{'-' * 13}+{'-' * 14}+{'-' * 14}+{'-' * 7}+{'-' * 12}|"
) )
stake_amount = self.adjust_stake_amount(pair, last_candle) stake_amount = self.adjust_stake_amount(pair, last_candle)
@@ -305,7 +241,7 @@ class Zeus_11(IStrategy):
last_candle = dataframe.iloc[-1].squeeze() last_candle = dataframe.iloc[-1].squeeze()
before_last_candle = dataframe.iloc[-2].squeeze() before_last_candle = dataframe.iloc[-2].squeeze()
count_of_buys = trade.nr_of_successful_entries #count_of_buys = trade.nr_of_successful_entries
max_touch_before = self.pairs[pair]['max_touch'] max_touch_before = self.pairs[pair]['max_touch']
self.pairs[pair]['last_max'] = max(last_candle['haclose'], self.pairs[pair]['last_max']) self.pairs[pair]['last_max'] = max(last_candle['haclose'], self.pairs[pair]['last_max'])
@@ -317,16 +253,18 @@ class Zeus_11(IStrategy):
expected_profit = self.expectedProfit(pair, last_candle) expected_profit = self.expectedProfit(pair, last_candle)
if (last_candle['percent3'] < 0.0) & (current_profit > last_candle['min_max200'] / 3): if (last_candle['rsi_1d'] > 50) & (last_candle['percent12'] < 0.0):
self.trades = list() if (last_candle['percent3'] < 0.0) & (current_profit > last_candle['min_max200'] / 3):
return 'min_max200_' + str(count_of_buys) self.trades = list()
if (last_candle['percent12'] <= -0.01) & (current_profit >= expected_profit): return 'mx_' + str(count_of_buys)
self.trades = list() if (last_candle['percent12'] <= -0.01) & (current_profit >= expected_profit):
return 'profit_' + str(count_of_buys) self.trades = list()
if (current_profit >= expected_profit) & (last_candle['percent'] < 0.0) \ return 'profit_' + str(count_of_buys)
and ((last_candle['rsi'] >= 75) or before_last_candle['rsi'] >= 75): if (current_profit >= expected_profit) & (last_candle['percent'] < 0.0) \
self.trades = list() and ((last_candle['rsi'] >= 75) or before_last_candle['rsi'] >= 75):
return 'rsi_' + str(count_of_buys) self.trades = list()
return 'rsi_' + str(count_of_buys)
self.pairs[pair]['max_touch'] = max(last_candle['haclose'], self.pairs[pair]['max_touch'])
def informative_pairs(self): def informative_pairs(self):
# get access to all pairs available in whitelist. # get access to all pairs available in whitelist.
@@ -346,10 +284,10 @@ class Zeus_11(IStrategy):
# f"|{'-' * 18}+{'-' * 12}+{'-' * 12}+{'-' * 20}+{'-' * 14}+{'-' * 8}+{'-' * 10}+{'-' * 7}+{'-' * 13}+{'-' * 14}+{'-' * 14}+{'-' * 7}+{'-' * 12}|" # f"|{'-' * 18}+{'-' * 12}+{'-' * 12}+{'-' * 20}+{'-' * 14}+{'-' * 8}+{'-' * 10}+{'-' * 7}+{'-' * 13}+{'-' * 14}+{'-' * 14}+{'-' * 7}+{'-' * 12}|"
# ) # )
print( print(
f"| {'Date':<16} | {'Action':<10} | {'Pair':<10} | {'Trade Type':<18} | {'Rate':>12} | {'Dispo':>6} | {'Profit':>8} | {'Pct':>5} | {'max_touch':>11} | {'last_lost':>12} | {'last_max':>12} | {'Buys':>5} | {'Stake':>10} |" f"| {'Date':<16} | {'Action':<10} | {'Pair':<5} | {'Trade Type':<18} | {'Rate':>12} | {'Dispo':>6} | {'Profit':>8} | {'Pct':>5} | {'max_touch':>11} | {'last_lost':>12} | {'last_max':>12} | {'Buys':>5} | {'Stake':>10} |"
) )
print( print(
f"|{'-' * 18}+{'-' * 12}+{'-' * 12}+{'-' * 20}+{'-' * 14}+{'-' * 8}+{'-' * 10}+{'-' * 7}+{'-' * 13}+{'-' * 14}+{'-' * 14}+{'-' * 7}+{'-' * 12}|" f"|{'-' * 18}+{'-' * 12}+{'-' * 5}+{'-' * 20}+{'-' * 14}+{'-' * 8}+{'-' * 10}+{'-' * 7}+{'-' * 13}+{'-' * 14}+{'-' * 14}+{'-' * 7}+{'-' * 12}|"
) )
self.columns_logged += 1 self.columns_logged += 1
date = str(date)[:16] if date else "-" date = str(date)[:16] if date else "-"
@@ -380,12 +318,17 @@ class Zeus_11(IStrategy):
pct_max = round((last_candle['close'] - self.pairs[pair]['first_buy']) / self.pairs[pair]['first_buy'], 3) # round(100 * self.pairs[pair]['current_profit'], 1) pct_max = round((last_candle['close'] - self.pairs[pair]['first_buy']) / self.pairs[pair]['first_buy'], 3) # round(100 * self.pairs[pair]['current_profit'], 1)
if trade_type is not None: if trade_type is not None:
if np.isnan(last_candle['rsi_1d']):
string = ' '
else:
string = (str(int(last_candle['rsi_1d']))) + " " + str(int(last_candle['rsi_diff_1d']))
trade_type = trade_type \ trade_type = trade_type \
+ " " + str(round(100 * last_candle['sma5_pct_1d'], 0)) + " " + string \
# + " " + str(round(last_candle['sma5_diff_1h'], 1)) + " " + str(int(last_candle['rsi_1h'])) \
+ " " + str(int(last_candle['rsi_diff_1h']))
print( print(
f"| {date:<16} | {action:<10} | {pair:<10} | {trade_type or '-':<18} | {rate or '-':>12} | {dispo or '-':>6} | {profit or '-':>8} | {pct_max or '-':>5} | {max_touch or '-':>11} | {last_lost or '-':>12} | {round(self.pairs[pair]['last_max'], 2) or '-':>12} | {buys or '-':>5} | {stake or '-':>10} |" f"| {date:<16} | {action:<10} | {pair[0:3]:<3} | {trade_type or '-':<18} | {rate or '-':>12} | {dispo or '-':>6} | {profit or '-':>8} | {pct_max or '-':>5} | {max_touch or '-':>11} | {last_lost or '-':>12} | {round(self.pairs[pair]['last_max'], 2) or '-':>12} | {buys or '-':>5} | {stake or '-':>10} |"
) )
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
@@ -415,6 +358,7 @@ class Zeus_11(IStrategy):
dataframe['max50_diff'] = (dataframe['max50'] - dataframe['close']) / dataframe['close'] dataframe['max50_diff'] = (dataframe['max50'] - dataframe['close']) / dataframe['close']
dataframe['sma5'] = talib.SMA(dataframe, timeperiod=5) dataframe['sma5'] = talib.SMA(dataframe, timeperiod=5)
dataframe['sma5_pct'] = (dataframe['sma5'] - dataframe['sma5']) / dataframe['sma5']
dataframe['sma10'] = talib.SMA(dataframe, timeperiod=10) dataframe['sma10'] = talib.SMA(dataframe, timeperiod=10)
dataframe['sma20'] = talib.SMA(dataframe, timeperiod=20) dataframe['sma20'] = talib.SMA(dataframe, timeperiod=20)
dataframe["percent"] = (dataframe["close"] - dataframe["open"]) / dataframe["open"] dataframe["percent"] = (dataframe["close"] - dataframe["open"]) / dataframe["open"]
@@ -484,7 +428,7 @@ class Zeus_11(IStrategy):
# Normaliser les données de 'close' # Normaliser les données de 'close'
# normalized_close = self.min_max_scaling(dataframe['close']) # normalized_close = self.min_max_scaling(dataframe['close'])
################### INFORMATIVE 1h ################### INFORMATIVE 1h
# informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1h") informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1h")
# x_percent = 0.01 # x_percent = 0.01
# n_hours = 6 # n_hours = 6
# n_candles = n_hours * 60 # metadata["timeframe"] # Convertir en bougies # n_candles = n_hours * 60 # metadata["timeframe"] # Convertir en bougies
@@ -492,10 +436,17 @@ class Zeus_11(IStrategy):
# informative["max_profit"] = dataframe["informative"].rolling(n_candles).max() # informative["max_profit"] = dataframe["informative"].rolling(n_candles).max()
# informative["profit_hit"] = dataframe["informative"] >= informative["close"] * (1 + x_percent) # informative["profit_hit"] = dataframe["informative"] >= informative["close"] * (1 + x_percent)
# #
# dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "1h", ffill=True) informative['rsi'] = talib.RSI(informative['close'], length=7)
informative['rsi_diff'] = informative['rsi'] - informative['rsi'].shift(1)
informative['sma5'] = talib.SMA(informative, timeperiod=5)
informative['sma5_pct'] = 100 * (informative['sma5'] - informative['sma5'].shift(1)) / informative['sma5']
dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "1h", ffill=True)
################### INFORMATIVE 1d ################### INFORMATIVE 1d
informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1d") informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1d")
informative['rsi'] = talib.RSI(informative['close'], length=7)
informative['rsi_diff'] = informative['rsi'] - informative['rsi'].shift(1)
informative['sma5'] = talib.SMA(informative, timeperiod=5) informative['sma5'] = talib.SMA(informative, timeperiod=5)
informative['sma5_pct'] = 100 * (informative['sma5'] - informative['sma5'].shift(1)) / informative['sma5'] informative['sma5_pct'] = 100 * (informative['sma5'] - informative['sma5'].shift(1)) / informative['sma5']
sorted_close_prices = informative['close'].tail(365).sort_values() sorted_close_prices = informative['close'].tail(365).sort_values()
@@ -548,6 +499,7 @@ class Zeus_11(IStrategy):
# Order(id=2396, trade=1019, order_id=29870026652, side=buy, filled=0.00078, price=63921.01, # Order(id=2396, trade=1019, order_id=29870026652, side=buy, filled=0.00078, price=63921.01,
# status=closed, date=2024-08-26 02:20:11) # status=closed, date=2024-08-26 02:20:11)
dataframe['last_price'] = buy.price dataframe['last_price'] = buy.price
self.pairs[trade.pair]['last_buy'] = buy.price
print(buy) print(buy)
count = count + 1 count = count + 1
amount += buy.price * buy.filled amount += buy.price * buy.filled
@@ -610,11 +562,12 @@ class Zeus_11(IStrategy):
# ************** # **************
# Identifier le prix de début et de fin de chaque chute # # Identifier le prix de début et de fin de chaque chute
drop_stats = dataframe.groupby('drop_id').agg( # drop_stats = dataframe.groupby('drop_id').agg(
start_price=('close', 'first'), # Prix au début de la chute # start_price=('close', 'first'), # Prix au début de la chute
end_price=('close', 'last'), # Prix à la fin de la chute # end_price=('close', 'last'), # Prix à la fin de la chute
) # )
return dataframe return dataframe
@@ -639,12 +592,154 @@ class Zeus_11(IStrategy):
dataframe.loc[ dataframe.loc[
( (
(dataframe['down_count'].shift(1) < - 6) (dataframe['rsi_1h'] < 70)
& (dataframe['down_count'] == 0) & (dataframe['rsi_diff_1h'] > -5)
& (dataframe['down_pct'].shift(1) <= -0.5) # (dataframe['down_count'].shift(1) < - 6)
), ['enter_long', 'enter_tag']] = (1, 'buy_hapercent') # & (dataframe['down_count'] == 0)
# & (dataframe['down_pct'].shift(1) <= -0.5)
), ['enter_long', 'enter_tag']] = (1, 'down')
dataframe['test'] = np.where(dataframe['enter_long'] == 1, dataframe['close'] * 1.01, np.nan) dataframe['test'] = np.where(dataframe['enter_long'] == 1, dataframe['close'] * 1.01, np.nan)
# for i in range(len(dataframe) - 48):
# last_candle = dataframe.iloc[i]
# if last_candle['enter_long'] is not None:
# if last_candle['enter_long'] == 1:
# futur_candle = dataframe.iloc[i + 48]
# sma5pct_1h = last_candle['sma5_pct_1h']
# sma5pct_1d = last_candle['sma5_pct_1d']
# i = i + 48
# print(f"{i} ===> ;{sma5pct_1d:.2f};{sma5pct_1h:.2f};{100 * futur_candle['percent48']:.1f}")
# print(dataframe.columns)
#
# colonnes = [
# 'hapercent', 'close_02', 'pct_change', 'max200_diff',
# 'max50_diff', 'sma5_pct', 'percent', 'percent3',
# 'percent5', 'percent12', 'percent24', 'percent48', 'rsi',
# 'bb_percent', 'down_count',
# 'up_count', 'down_pct', 'up_pct', 'volume_1h', 'rsi_1h',
# 'sma5_pct_1h', 'volume_1d', 'rsi_1d', 'sma5_pct_1d',
# 'pct_min_max_1d']
#
# exclude_cols = ['date', 'enter_tag', 'close', 'open', 'low', 'high', 'haclose', 'haopen', 'halow', 'hahigh'
# , 'date_1h', 'close_1h', 'open_1h', 'low_1h', 'high_1h', 'haclose_1h', 'haopen_1h', 'halow_1h', 'hahigh_1h'
# , 'date_1d', 'close_1d', 'open_1d', 'low_1d', 'high_1d', 'haclose_1d', 'haopen_1d', 'halow_1d', 'hahigh_1d']
# for column in colonnes:
# for column2 in colonnes:
# print('===============================================')
# print(f"Colonne 1: {column} Colonne 2: {column2}")
# list_1 = []
# list_2 = []
# data = []
# key_1 = column
# key_2 = column2
# futur = 'percent48'
#
# for i in range(200, len(dataframe) - 48):
# last_candle = dataframe.iloc[i]
# if last_candle['enter_long'] is not None and last_candle['enter_long'] == 1:
# futur_candle = dataframe.iloc[i + 48]
# val_1 = last_candle[key_1]
# val_2 = last_candle[key_2]
# if not np.isnan(val_1) and not np.isnan(val_2):
# value = 100 * futur_candle[futur]
# list_1.append(val_2)
# list_2.append(val_1)
# data.append(value)
# i += 48 # skip to avoid overlapping trades
#
# # Tes données sous forme de listes
# x = np.array(list_1) # axe X
# y = np.array(list_2) # axe Y
# z = np.array(data) # valeur à afficher (performance future)
# # print(len(list_2), len(list_2), len(data))
# # print(f"Min/max H1: {min(list_1):.5f}, {max(list_1):.5f}")
# # print(f"Min/max 1D: {min(list_2):.5f}, {max(list_2):.5f}")
# # print(f"Min/max Data: {min(data):.5f}, {max(data):.5f}")
# # Fusionner X et Y comme variables indépendantes
# XY = np.column_stack((x, y))
# # Modèle
# model = LinearRegression()
# model.fit(XY, z)
# # Coefficients
# a, b = model.coef_
# c = model.intercept_
# r_squared = model.score(XY, z)
# print(f"Coefficient de détermination R² : {r_squared:.4f}")
# print(f"Équation estimée : Z = {a:.4f} * X + {b:.4f} * Y + {c:.4f}")
# degree = 2 # Pour inclure X², Y², XY
# poly_model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
# poly_model.fit(XY, z)
#
# # Pour afficher les coefficients :
# linreg = poly_model.named_steps['linearregression']
# print("Coefficients:", linreg.coef_)
# print("Intercept:", linreg.intercept_)
#
#
# # Données factices
# # x = np.random.uniform(-2, 2, 500)
# # y = np.random.uniform(-2, 2, 500)
# # z = np.sin(x) * np.cos(y) * 10 # variation factice
#
# # Discrétisation (binning)
# xbins = np.linspace(min(x), max(x), 20)
# ybins = np.linspace(min(y), max(y), 20)
#
# # Création des bins 2D
# H, xedges, yedges = np.histogram2d(x, y, bins=[xbins, ybins], weights=z)
# counts, _, _ = np.histogram2d(x, y, bins=[xbins, ybins]) # pour normaliser
#
# # Moyenne dans chaque bin (évite division par 0)
# H_avg = np.divide(H, counts, out=np.zeros_like(H), where=counts != 0)
#
# # Préparer coordonnées pour le graphique
# xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1], indexing="ij")
# xpos = xpos.ravel()
# ypos = ypos.ravel()
# zpos = np.zeros_like(xpos)
#
# dx = dy = (xedges[1] - xedges[0]) * 0.9
# dz = H_avg.ravel()
#
# # Affichage
# fig = plt.figure(figsize=(12, 8))
# ax = fig.add_subplot(111, projection='3d')
# colors = plt.cm.RdYlGn((dz - dz.min()) / (dz.max() - dz.min() + 1e-5)) # Normalisation
#
# ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors, shade=True)
#
# ax.set_xlabel(f"{key_1}")
# ax.set_ylabel(f"{key_2}")
# ax.set_zlabel('Perf. moyenne sur 48 bougies')
# ax.set_title('Performance 48 bougies (%)')
# plt.show()
# plt.figure(figsize=(10, 8))
# scatter = plt.scatter(
# list_1,
# list_2,
# c=data, # La couleur selon la performance future
# cmap='RdYlGn', # Dégradé rouge -> jaune -> vert
# alpha=0.8,
# edgecolors='k'
# )
# plt.xlabel(f"{key_1}")
# plt.ylabel(f"{key_2}")
# plt.title(f"Performance future")
# plt.colorbar(scatter, label="Performance 48 bougies (%)")
# plt.grid(True)
# plt.show()
# plt.figure(figsize=(10, 6))
# plt.scatter(list_1, data, c='blue', alpha=0.6)
# plt.xlabel("SMA5 % sur 1 jour")
# plt.ylabel("Variation du prix après 48 bougies (%)")
# plt.title("Lien entre variation SMA5 1j et performance 48h")
# plt.grid(True)
# plt.show()
return dataframe return dataframe
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
@@ -652,15 +747,17 @@ class Zeus_11(IStrategy):
def adjust_trade_position(self, trade: Trade, current_time: datetime, def adjust_trade_position(self, trade: Trade, current_time: datetime,
current_rate: float, current_profit: float, min_stake: float, current_rate: float, current_profit: float, min_stake: float,
max_stake: float, **kwargs): max_stake: float, **kwargs): # ne rien faire si ordre deja en cours
# ne rien faire si ordre deja en cours
if trade.has_open_orders: if trade.has_open_orders:
#print("has open orders : true")
return None return None
if (self.wallets.get_available_stake_amount() < 50): # or trade.stake_amount >= max_stake: if (self.wallets.get_available_stake_amount() < 50): # or trade.stake_amount >= max_stake:
#print("wallet too low")
return 0 return 0
dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe) dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe)
last_candle = dataframe.iloc[-1].squeeze() last_candle = dataframe.iloc[-1].squeeze()
last_candle_3 = dataframe.iloc[-4].squeeze()
# prépare les données # prépare les données
count_of_buys = trade.nr_of_successful_entries count_of_buys = trade.nr_of_successful_entries
current_time = current_time.astimezone(timezone.utc) current_time = current_time.astimezone(timezone.utc)
@@ -669,15 +766,18 @@ class Zeus_11(IStrategy):
hours = (current_time - trade.date_last_filled_utc).total_seconds() / 3600.0 hours = (current_time - trade.date_last_filled_utc).total_seconds() / 3600.0
if (len(dataframe) < 1): if (len(dataframe) < 1):
#print("dataframe empty")
return None return None
pair = trade.pair pair = trade.pair
if pair not in ('BTC/USDC', 'XRP/USDC', 'BTC/USDT', 'XRP/USDT'): if pair not in ('BTC/USDC', 'XRP/USDC', 'BTC/USDT', 'XRP/USDT'):
print(f"{pair} not in allowed pairs list")
return None return None
max_buys = 20 max_buys = 20
filled_buys = trade.select_filled_orders('buy') # filled_buys = trade.select_filled_orders('buy')
count_of_buys = len(filled_buys) # count_of_buys = len(filled_buys)
if count_of_buys >= max_buys: if count_of_buys >= max_buys:
#print(f"count_of_buys {count_of_buys} > {max_buys} max buys")
return None return None
# if 'buy' in last_candle: # if 'buy' in last_candle:
@@ -685,16 +785,20 @@ class Zeus_11(IStrategy):
# else: # else:
# condition = False # condition = False
# self.protection_nb_buy_lost.value # self.protection_nb_buy_lost.value
limit = last_candle['limit'] # limit = last_candle['limit']
stake_amount = self.config['stake_amount'] + 50 * self.fibo[count_of_buys] stake_amount = self.config['stake_amount'] + 50 * self.fibo[count_of_buys]
current_time_utc = current_time.astimezone(timezone.utc) # current_time_utc = current_time.astimezone(timezone.utc)
open_date = trade.open_date.astimezone(timezone.utc) # open_date = trade.open_date.astimezone(timezone.utc)
days_since_open = (current_time_utc - open_date).days # days_since_open = (current_time_utc - open_date).days
pct_max = round((last_candle['close'] - self.pairs[trade.pair]['last_buy']) / self.pairs[trade.pair]['last_buy'], 3) pct_max = round((last_candle['close'] - self.pairs[trade.pair]['last_buy']) / self.pairs[trade.pair]['last_buy'], 4)
# if (days_since_open > count_of_buys) & (0 < count_of_buys <= max_buys) & (current_rate <= limit) & (last_candle['enter_long'] == 1): # if (days_since_open > count_of_buys) & (0 < count_of_buys <= max_buys) & (current_rate <= limit) & (last_candle['enter_long'] == 1):
if ((last_candle['enter_long'] == 1) or last_candle['percent48'] < - 0.03) \ if (
(
last_candle['enter_long'] == 1)
or (last_candle['percent48'] < - 0.03 and last_candle['rsi_diff_1h'] > -5)
) \
and (pct_max < -0.012 - (count_of_buys * 0.001)): and (pct_max < -0.012 - (count_of_buys * 0.001)):
try: try:
@@ -702,7 +806,7 @@ class Zeus_11(IStrategy):
# stake_amount = stake_amount * pow(1.5, count_of_buys) # stake_amount = stake_amount * pow(1.5, count_of_buys)
# print( # print(
# f"Adjust {current_time} price={trade.pair} rate={current_rate:.4f} buys={count_of_buys} limit={limit:.4f} stake={stake_amount:.4f}") # f"Adjust {current_time} price={trade.pair} rate={current_rate:.4f} buys={count_of_buys} limit={limit:.4f} stake={stake_amount:.4f}")
trade_type = last_candle['enter_tag'] if last_candle['enter_long'] == 1 else 'pct48'
self.log_trade( self.log_trade(
last_candle=last_candle, last_candle=last_candle,
date=current_time, date=current_time,
@@ -710,7 +814,7 @@ class Zeus_11(IStrategy):
dispo=dispo, dispo=dispo,
pair=trade.pair, pair=trade.pair,
rate=current_rate, rate=current_rate,
trade_type=last_candle['enter_tag'], trade_type=trade_type,
profit=round(current_profit, 4), # round(current_profit * trade.stake_amount, 2), profit=round(current_profit, 4), # round(current_profit * trade.stake_amount, 2),
buys=trade.nr_of_successful_entries + 1, buys=trade.nr_of_successful_entries + 1,
stake=round(stake_amount, 2) stake=round(stake_amount, 2)
@@ -722,9 +826,13 @@ class Zeus_11(IStrategy):
except Exception as exception: except Exception as exception:
print(exception) print(exception)
return None return None
pcte=-0.012 - (count_of_buys * 0.001)
if not self.dp.runmode.value in ('backtest', 'hyperopt'):
logger.error(f"adjust_trade_position {trade.pair} tag={last_candle['enter_long']} pct48={last_candle['percent48']:.1f} pctmax={pct_max:.4f} pcte={pcte:.4f}")
return None return None
def adjust_stake_amount(self, pair: str, dataframe: DataFrame): def adjust_stake_amount(self, pair: str, dataframe: DataFrame):
# Calculer le minimum des 14 derniers jours # Calculer le minimum des 14 derniers jours
current_price = dataframe['close'] current_price = dataframe['close']

View File

@@ -1,15 +0,0 @@
[Achats]
BTC/USDT=63400
ETH/USDT=2570
ETC/USDT=10
DOGE/USDT=0.106
SOL/USDT=150
XRP/USDT=0.584
[Ventes]
BTC/USDT=63979
ETH/USDT=2542
ETC/USDT=70
DOGE/USDT=0.122
SOL/USDT=150.24
XRP/USDT=0.6