diff --git a/Zeus_8_3_2_B_4_2.py b/Zeus_8_3_2_B_4_2.py index f156145..c791678 100644 --- a/Zeus_8_3_2_B_4_2.py +++ b/Zeus_8_3_2_B_4_2.py @@ -228,11 +228,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): 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: - # count_buys = 0 - # trade = self.getTrade(pair) - # if trade: - # filled_buys = trade.select_filled_orders('buy') - # count_buys = len(filled_buys) minutes = 0 if self.pairs[pair]['last_date'] != 0: @@ -346,24 +341,10 @@ class Zeus_8_3_2_B_4_2(IStrategy): self.pairs[pair]['count_of_buys'] = count_of_buys self.pairs[pair]['current_profit'] = current_profit self.pairs[pair]['max_profit'] = max(self.pairs[pair]['max_profit'], current_profit) - pct_first = round((last_candle['close'] - self.pairs[pair]['first_buy']) / self.pairs[pair]['first_buy'], 3) - - # if (last_candle['close'] > last_candle['max3_1d']) and \ - # (current_profit >= expected_profit or (last_candle['rsi'] >= 80 and current_profit > 0)) & (last_candle['percent'] < 0.0) \ - # and ((last_candle['rsi'] >= 75) or before_last_candle['rsi'] >= 75)\ - # and (count_of_buys <= 2): - # self.trades = list() - # # self.pairs[pair]['stop'] = True - # return 'rsi_' + str(count_of_buys) if (last_candle['tendency'] in ('H++', 'H+')) and (last_candle['rsi'] < 80): - # and (last_candle['tendency_1h'] in ('H++', 'H+')): - # and (last_candle['tendency_1d'] in ('H++', 'H+')) : return None - # if (count_of_buys >= 4 and last_candle['sma5_diff_1h'] > 0): - # return None - # if (last_candle['rsi_1d'] > 50) & (last_candle['percent12'] < 0.0): baisse = self.pairs[pair]['max_profit'] - current_profit mx = self.pairs[pair]['max_profit'] / 5 if (baisse > mx) & (current_profit > expected_profit): #last_candle['min_max200'] / 3): @@ -373,13 +354,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): self.trades = list() return 'pft_' + str(count_of_buys) - # if (last_candle['percent3'] < -0.002) & (last_candle['percent12'] < 0) & ( - # current_profit > last_candle['min_max200'] / 3): - # self.trades = list() - # return 'mnmx_' + str(count_of_buys) - # if (last_candle['percent12'] <= -0.01) & (current_profit >= expected_profit): - # self.trades = list() - # return 'profit_' + str(count_of_buys) self.pairs[pair]['max_touch'] = max(last_candle['haclose'], self.pairs[pair]['max_touch']) def informative_pairs(self): @@ -582,20 +556,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): dataframe['average_line_288'] = talib.MIDPOINT(dataframe['close'], timeperiod=288) dataframe['average_line_288_098'] = dataframe['average_line_288'] * 0.98 dataframe['average_line_288_099'] = dataframe['average_line_288'] * 0.99 - # # Sort the close prices to find the 4 lowest values - # sorted_close_prices = dataframe['close'].rolling(576).sort_values() - # lowest_4 = sorted_close_prices.head(20) - # - # dataframe['lowest_4_average'] = lowest_4.mean() - # # Propagate this mean value across the entire dataframe - # # dataframe['lowest_4_average'] = dataframe['lowest_4_average'].iloc[0] - # - # # # Sort the close prices to find the 4 highest values - # sorted_close_prices = dataframe['close'].rolling(288).sort_values(ascending=False) - # highest_4 = sorted_close_prices.head(20) - # - # # # Calculate the mean of the 4 highest values - # dataframe['highest_4_average'] = highest_4.mean() # Compter les baisses consécutives self.calculateDownAndUp(dataframe, limit=0.0001) @@ -631,18 +591,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): self.calculateDownAndUp(informative, limit=0.0012) - # if self.dp.runmode.value in ('backtest'): - # self.test_signal_success(informative, percent=0.01, window_size=24) - - # if self.dp.runmode.value in ('backtest'): - # condition = (informative['sma5'].shift(2) > informative['sma5'].shift(1)) \ - # & (informative['sma5'].shift(1) < informative['sma5']) \ - # & (informative['down_pct'].shift(3) < -0.015) - # - # self.test_signal_success(informative, condition, percent=0.01, window_size=3) - # self.test_signal_success(informative, condition, percent=0.01, window_size=5) - # self.test_signal_success(informative, condition, percent=0.01, window_size=10) - dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "1h", ffill=True) ################### INFORMATIVE 1d @@ -703,80 +651,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): # dataframe['amount'] = amount print(f"amount= {amount}") - # # trades = Trade.get_trades([Trade.is_open is False]).all() - # trades = Trade.get_trades_proxy(is_open=False, pair=metadata['pair']) - # if trades: - # trade = trades[-1] - # print('closed trade pair is : ') - # print(trade) - # dataframe['expected_profit'] = (1 + self.expectedProfit(pair, dataframe.iloc[-1])) * dataframe[ - # 'last_price'] - # dataframe['lbp'] = dataframe['last_price'] - # dataframe['lbp_3'] = dataframe['lbp'] * 0.97 # 3 - # dataframe['lbp_6'] = dataframe['lbp'] * 0.94 # 6 - # dataframe['lbp_9'] = dataframe['lbp'] * 0.90 # 10 - # dataframe['lbp_12'] = dataframe['lbp'] * 0.85 # 15 - # dataframe['lbp_20'] = dataframe['lbp'] * 0.8 # 20 - # dataframe['fbp'] = trade.open_rate - # # else: - # # last_trade = self.get_trades(pair=pair).order_by('-close_date').first() - # # filled_buys = last_trade.select_filled_orders('buy') - # # print(last_trade) - # # for buy in filled_buys: - # # print(filled_buys) - - # dataframe['buy_level'] = dataframe['lowest_4_average'] * (1 - self.levels[count_buys] / 100) - # ---------------------------------------------------------- - # Calcul de la variation entre deux bougies successives - # dataframe['price_change'] = dataframe['close'].diff() - - # # Marquer les bougies en baisse - # dataframe['is_down'] = dataframe['price_change'] < 0 - # - # # Identifier les blocs consécutifs de baisses - # # dataframe['drop_id'] = (dataframe['is_down'] != dataframe['is_down'].shift(1)).cumsum() - # dataframe['drop_id'] = np.where(dataframe['is_down'], - # (dataframe['is_down'] != dataframe['is_down'].shift(12)).cumsum(), np.nan) - # - # # Identifier uniquement les blocs de baisse - # dataframe['drop_id'] = dataframe['drop_id'].where(dataframe['is_down']) - # # Grouper par les chutes détectées - # drop_info = dataframe.groupby('drop_id').agg( - # start=('close', 'first'), # Prix au début de la chute - # end=('close', 'last'), # Prix à la fin de la chute - # start_index=('close', 'idxmin'), # Début de la chute (index) - # end_index=('close', 'idxmax'), # Fin de la chute (index) - # ) - # - # # Calcul de l'ampleur de la chute en % - # drop_info['drop_amplitude_pct'] = ((drop_info['end'] - drop_info['start']) / drop_info['start']) * 100 - # # Filtrer les chutes avec une amplitude supérieure à 3% - # drop_info = drop_info[drop_info['drop_amplitude_pct'] < -3] - - # ************** - - # Identifier le prix de début et de fin de chaque chute - # drop_stats = dataframe.groupby('drop_id').agg( - # start_price=('close', 'first'), # Prix au début de la chute - # end_price=('close', 'last'), # Prix à la fin de la chute - # ) - - # Calculer l'amplitude en % - # drop_stats['amplitude_pct'] = ((drop_stats['end_price'] - drop_stats['start_price']) / drop_stats[ - # 'start_price']) * 100 - # # drop_stats = drop_stats[drop_stats['amplitude_pct'] < -1] - # # Associer les amplitudes calculées à chaque drop_id dans dataframe - # dataframe = dataframe.merge(drop_stats[['amplitude_pct']], on='drop_id', how='left') - # # Remplir les lignes sans drop_id par 0 - # dataframe['amplitude_pct'] = dataframe['amplitude_pct'].fillna(0) - # dataframe['amplitude_pct_60'] = dataframe['amplitude_pct'].rolling(60).sum() - # ---------------------------------------------------------- - - # self.getBinanceOrderBook(pair, dataframe) - - # if self.dp.runmode.value in ('backtest'): - # self.test_signal_success(dataframe, 0.005) - dataframe['futur_price_1h'] = dataframe['close'].shift(-12) dataframe['futur_price_2h'] = dataframe['close'].shift(-24) dataframe['futur_price_3h'] = dataframe['close'].shift(-36) @@ -812,15 +686,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): self.trades = Trade.get_open_trades() return self.trades - # def getTrade(self, pair): - # trades = self.getOpenTrades() - # trade_for_pair = None - # for trade in trades: - # if trade.pair == pair: - # trade_for_pair = trade - # break - # return trade_for_pair - def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: pair = metadata['pair'] @@ -849,48 +714,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): & (dataframe["bb_width"] > 0.01) ), ['enter_long', 'enter_tag']] = (1, 'mx200') - dataframe.loc[ - ( - ( - (dataframe['percent12'] < -0.015) | - (dataframe['percent24'] < -0.022) | - (dataframe['percent48'] < -0.030) - ) - & (dataframe['close'] <= dataframe['min50'] * 1.002) - & (dataframe['open'] < dataframe['average_line_50']) - & ( - (dataframe['close'] < dataframe['min12'] * 1.002) - | (dataframe['percent12'] < -0.022) - | (dataframe['percent24'] < -0.022) - ) - & ( - (dataframe['min50'].shift(2) == dataframe['min50']) - | (dataframe['percent12'] < -0.022) - | (dataframe['percent24'] < -0.022) - ) - & (dataframe['up_count'] > 0) - & (dataframe["bb_width"] > 0.01) - ), ['enter_long', 'enter_tag']] = (1, 'pct12') - - dataframe.loc[ - ( - (dataframe['close'] <= dataframe['min200'] * 1.002) - & (dataframe["bb_width"] > 0.01) - & (dataframe['min_max200'] > 0.015) - # & (dataframe['pct_change'] < 0) - & (dataframe['haopen'] < buy_level) - & (dataframe['open'] < dataframe['average_line_288']) - & (dataframe['up_count'] > 0) - ), ['enter_long', 'enter_tag']] = (1, 'mnmx200') - # dataframe.loc[ - # ( - # (dataframe['close'].shift(2) <= dataframe['min200']) - # & (dataframe['pct_change'] < 0) - # & (dataframe['min200'].shift(2) == dataframe['min200']) - # & (dataframe['close'] < dataframe['lowest_4_average']) - # & (dataframe['up_count'] > 0) - # ), ['enter_long', 'enter_tag']] = (1, 'min200') - dataframe.loc[ ( # (dataframe['rsi_1h'] < 70) @@ -911,7 +734,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): & (dataframe['tendency'] != "B-") ), ['enter_long', 'enter_tag']] = (1, 'low') - dataframe['test'] = np.where(dataframe['enter_long'] == 1, dataframe['close'] * 1.01, np.nan) if self.dp.runmode.value in ('backtest'): @@ -1028,14 +850,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): first_price = last_candle['close'] last_max = last_candle['max12_1d'] - # if self.pairs[pair]['last_max'] == 0: - # self.pairs[pair]['last_max'] = last_candle['max12_1d'] - # print(f"last_max set to {last_max}") - # - # if self.pairs[pair]['last_max'] > 0: - # last_max = self.pairs[pair]['last_max'] - # print(f"last_max is {last_max}") - pct = 5 if last_max > 0: pct = 100 * (last_max - first_price) / last_max @@ -1048,323 +862,14 @@ class Zeus_8_3_2_B_4_2(IStrategy): return adjusted_stake_amount - # def adjust_exit_price(self, dataframe: DataFrame): - # # Calculer le max des 14 derniers jours - # min_14_days = dataframe['lowest_1d'] - # max_14_days = dataframe['highest_1d'] - # entry_price = dataframe['fbp'] - # current_price = dataframe['close'] - # percent = 0.5 * (max_14_days - min_14_days) / min_14_days - # exit_price = (1 + percent) * entry_price - # - # print(f"Exit price ajusté price={current_price:.4f} max_14={max_14_days:.4f} exit_price={exit_price:.4f}") - # - # return exit_price - - # def adjust_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, - # current_rate: float, current_profit: float, **kwargs) -> float: - # dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe) - # # print(dataframe) - # last_candle = dataframe.iloc[-1].squeeze() - # - # # Utiliser l'ATR pour ajuster le stoploss - # atr_stoploss = current_rate - (last_candle['atr'] * 1.5) # Stoploss à 1.5x l'ATR - # - # # Retourner le stoploss dynamique en pourcentage du prix actuel - # return (atr_stoploss / current_rate) - 1 - def expectedProfit(self, pair: str, last_candle: DataFrame): - # first_price = last_candle['first_price'] - # first_max = 0.01 - # if first_price < last_candle['max200']: - # first_max = (last_candle['max200'] - first_price) / first_price - expected_profit = 0.004 #min(0.01, first_max) # print( # f"Expected profit price={current_price:.4f} min_max={min_max:.4f} min_14={min_14_days:.4f} max_14={max_14_days:.4f} percent={percent:.4f} expected_profit={expected_profit:.4f}") - - # self.analyze_conditions(pair, dataframe) return expected_profit - # def adjust_exit_price(self, dataframe: DataFrame): - # # Calculer le max des 14 derniers jours - # min_14_days = dataframe['lowest_1d'] - # max_14_days = dataframe['highest_1d'] - # entry_price = dataframe['fbp'] - # current_price = dataframe['close'] - # percent = 0.5 * (max_14_days - min_14_days) / min_14_days - # exit_price = (1 + percent) * entry_price - # - # print(f"Exit price ajusté price={current_price} max_14={max_14_days} exit_price={exit_price}") - # - # return exit_price - - # def adjust_entry_price(self, dataframe: DataFrame): - # # Calculer le max des 14 derniers jours - # min_14_days = dataframe['lowest_1d'] - # max_14_days = dataframe['highest_1d'] - # current_price = dataframe['close'] - # percent = 0.5 * (max_14_days - min_14_days) / min_14_days - # entry_price = (1 + percent) * entry_price - # - # print(f"Entry price ajusté price={current_price} max_14={max_14_days} exit_price={entry_price}") - # - # return entry_price - - # def adjust_stake_amount(self, dataframe: DataFrame): - # # Calculer le minimum des 14 derniers jours - # middle = dataframe['middle_1d'] - # - # # Récupérer la dernière cotation actuelle (peut être le dernier point de la série) - # current_price = dataframe['close'] - # - # # Calculer l'écart entre la cotation actuelle et le minimum des 14 derniers jours - # difference = middle - current_price - # # Ajuster la stake_amount en fonction de l'écart - # # Par exemple, augmenter la stake_amount proportionnellement à l'écart - # base_stake_amount = self.config.get('stake_amount', 100) # Montant de base configuré - # - # multiplier = 1 - (difference / current_price) # Exemple de logique d'ajustement - # - # adjusted_stake_amount = max(base_stake_amount / 2.5, base_stake_amount * multiplier) - # - # # difference = 346.07000000000016 - # # price = 2641.75 - # # min_14 = 2295.68 - # # amount = 56.5500141951358 - # - # print(f"Stack amount ajusté difference={difference} price={current_price} middle={middle} multiplier={multiplier} amount={adjusted_stake_amount}") - # - # return adjusted_stake_amount - - def getBinanceOrderBook(self, pair, dataframe: DataFrame): - """Fetch the order book (depth) from Binance.""" - # print(dataframe) - last_candle = dataframe.iloc[-1].squeeze() - symbol = pair.replace('/', '') - - try: - url = f"https://api.binance.com/api/v3/depth?symbol={symbol}&limit=5000" - response = requests.get(url) - data = response.json() - - # Extract bids and asks from the order book - asks, bids = self.calculateSMA(20, data['asks'], data['bids']) # Ventes List of [price, quantity] - # bids = data['bids'] - # asks = data['asks'] # Achats List of [price, quantity] - - # Process the depth data as you need it - # bid_volume = sum([float(bid[1]) for bid in bids]) # Sum of all bid volumes - # $ * nb / $ => nb - bid_volume = sum([float(bid[0]) * float(bid[1]) / float(last_candle['close']) for bid in bids[:10]]) - # ask_volume = sum([float(ask[1]) for ask in asks]) # Sum of all ask volumes - ask_volume = sum([float(ask[0]) * float(ask[1]) / float(last_candle['close']) for ask in asks[:10]]) - - # Example: add the difference in volumes as an indicator - if bid_volume and ask_volume: - self.updateLastValue(dataframe, 'depth_bid_ask_diff', round(bid_volume - ask_volume, 2)) - else: - self.updateLastValue(dataframe, 'depth_bid_ask_diff', 0) - - # probabilité baisse hausse sur les n premiers élements - for start in [0, 50, 100, 150]: - self.updateLastValue(dataframe, 'prob_hausse_' + str(start + 50), - self.calculateProbaNb(asks, bids, start, start + 50)) - # dataframe['prob_hausse_' + str(nb)] = self.calculateProbaNb(asks, bids, nb) - # Analyse des prix moyens pondérés par les volumes (VWAP) : - # - # Le VWAP (Volume Weighted Average Price) peut être utilisé pour comprendre la pression directionnelle. - # Si le VWAP basé sur les ordres d'achat est plus élevé que celui des ordres de vente, - # cela peut indiquer une probabilité de hausse. - nb = 50 - - bid_vwap = sum([float(bid[0]) * float(bid[1]) for bid in bids[:nb]]) / sum( - [float(bid[1]) for bid in bids[:nb]]) - ask_vwap = sum([float(ask[0]) * float(ask[1]) for ask in asks[:nb]]) / sum( - [float(ask[1]) for ask in asks[:nb]]) - - if bid_vwap > ask_vwap: - self.updateLastValue(dataframe, 'vwap_hausse', - round(100 * (bid_vwap - ask_vwap) / (bid_vwap + ask_vwap), 2)) - else: - self.updateLastValue(dataframe, 'vwap_hausse', - - round(100 * (ask_vwap - bid_vwap) / (bid_vwap + ask_vwap), 2)) - - current_price = last_candle['close'] # le prix actuel du marché - - # Calcul du seuil de variation de 1% - lower_threshold = current_price * 0.99 - upper_threshold = current_price * 1.01 - - # Volumes d'achat (bids) sous 1% du prix actuel - bid_volume_1percent = sum( - [float(bid[1]) for bid in bids if current_price >= float(bid[0]) >= lower_threshold]) - - # Volumes de vente (asks) au-dessus de 1% du prix actuel - ask_volume_1percent = sum( - [float(ask[1]) for ask in asks if current_price <= float(ask[0]) <= upper_threshold]) - - # Estimation de la probabilité basée sur le déséquilibre des volumes - total_volume = bid_volume_1percent + ask_volume_1percent - if total_volume > 0: - prob_hausse = bid_volume_1percent / total_volume - prob_baisse = ask_volume_1percent / total_volume - else: - prob_hausse = prob_baisse = 0 - - self.updateLastValue(dataframe, 'proba_hausse_1%', round(prob_hausse * 100, 2)) - self.updateLastValue(dataframe, 'proba_baisse_1%', round(prob_baisse * 100, 2)) - print(f"Probabilité de hausse de 1%: {prob_hausse * 100:.2f}%") - print(f"Probabilité de baisse de 1%: {prob_baisse * 100:.2f}%") - - self.calculateResistance(pair, asks, dataframe) - self.calculateSupport(pair, bids, dataframe) - - dataframe['r_s'] = 100 * (dataframe['r_min'] - dataframe['s_min']) / dataframe['s_min'] - - except Exception as e: - logger.error(f"Error fetching order book: {e}") - return None, None - - def calculateProbaNb(self, asks, bids, start, nb): - top_bids = sum([float(bid[1]) for bid in bids[start:nb]]) - top_asks = sum([float(ask[1]) for ask in asks[start:nb]]) - if top_bids > top_asks: - proba = round(100 * (top_bids - top_asks) / (top_bids + top_asks), 2) - else: - proba = - round(100 * (top_asks - top_bids) / (top_bids + top_asks), 2) - return proba - - def calculateResistance(self, pair, asks, dataframe: DataFrame): - last_candle = dataframe.iloc[-1].squeeze() - - # Filtrage +-5% - current_price = float(last_candle['close']) - lower_bound = current_price * 0.95 - upper_bound = current_price * 1.05 - ask_prices = [float(ask[0]) for ask in asks] - ask_volumes = [float(ask[1]) for ask in asks] - ask_df = pd.DataFrame({'price': ask_prices, 'volume': ask_volumes}) - filtered_ask_df = ask_df[(ask_df['price'] >= lower_bound) & (ask_df['price'] <= upper_bound)] - # Trier le DataFrame sur la colonne 'volume' en ordre décroissant - sorted_ask_df = filtered_ask_df.sort_values(by='volume', ascending=False) - - # Ne garder que les 3 premières lignes (les 3 plus gros volumes) - top_3_asks = sorted_ask_df.head(3) - print(top_3_asks) - - # Convertir les ordres de vente en numpy array pour faciliter le traitement - asks_array = np.array(filtered_ask_df, dtype=float) - - # Détecter les résistances : on peut définir qu'une résistance est un niveau de prix où la quantité est élevée - # Ex: seuil de résistance à partir des 10% des plus grosses quantités - resistance_threshold = np.percentile(asks_array[:, 1], 90) - resistances = asks_array[asks_array[:, 1] >= resistance_threshold] - - # Afficher les résistances trouvées - # print(f"{pair} Niveaux de résistance détectés:") - # for resistance in resistances: - # print(f"{pair} Prix: {resistance[0]}, Quantité: {resistance[1]}") - - # Exemple : somme des quantités sur des plages de prix - # Intervalles de 10 USDT - step = last_candle['close'] / 100 - price_intervals = np.arange(asks_array[:, 0].min(), asks_array[:, 0].max(), step=step) - - for start_price in price_intervals: - end_price = start_price + step - mask = (asks_array[:, 0] >= start_price) & (asks_array[:, 0] < end_price) - volume_in_range = asks_array[mask, 1].sum() - amount = volume_in_range * end_price - print( - f"Prix entre {start_price:.6f} et {end_price:.6f}: Volume total = {volume_in_range:.2f} amount={amount:.2f}") - - # Trier les asks par quantité en ordre décroissant - asks_sorted = asks_array[asks_array[:, 1].argsort()][::-1] - - # Sélectionner les trois plus gros resistances - top_3_resistances = asks_sorted[:3] - - # Afficher les trois plus gros resistances - print("Les trois plus grosses resistances détectées : ") - self.updateLastValue(dataframe, 'r3', top_3_resistances[0][0]) - self.updateLastValue(dataframe, 'r2', top_3_resistances[1][0]) - self.updateLastValue(dataframe, 'r1', top_3_resistances[2][0]) - self.updateLastValue(dataframe, 'r_min', - min(top_3_resistances[0][0], top_3_resistances[1][0], top_3_resistances[2][0])) - for resistance in top_3_resistances: - print(f"{pair} Prix: {resistance[0]}, Quantité: {resistance[1]}") - - def calculateSupport(self, pair, bids, dataframe: DataFrame): - last_candle = dataframe.iloc[-1].squeeze() - - # Convert to pandas DataFrame to apply moving average - current_price = float(last_candle['close']) - lower_bound = current_price * 0.95 - upper_bound = current_price * 1.05 - bid_prices = [float(bid[0]) for bid in bids] - bid_volumes = [float(bid[1]) for bid in bids] - bid_df = pd.DataFrame({'price': bid_prices, 'volume': bid_volumes}) - filtered_bid_df = bid_df[(bid_df['price'] >= lower_bound) & (bid_df['price'] <= upper_bound)] - # Trier le DataFrame sur la colonne 'volume' en ordre décroissant - sorted_bid_df = filtered_bid_df.sort_values(by='volume', ascending=False) - - # Ne garder que les 3 premières lignes (les 3 plus gros volumes) - top_3_bids = sorted_bid_df.head(3) - print(top_3_bids) - - # Convertir les ordres d'achat en numpy array pour faciliter le traitement - bids_array = np.array(filtered_bid_df, dtype=float) - - # Détecter les supports : on peut définir qu'un support est un niveau de prix où la quantité est élevée - # Ex: seuil de support à partir des 10% des plus grosses quantités - support_threshold = np.percentile(bids_array[:, 1], 90) - supports = bids_array[bids_array[:, 1] >= support_threshold] - - # Afficher les supports trouvés - # print(f"{pair} Niveaux de support détectés:") - # for support in supports: - # print(f"{pair} Prix: {support[0]}, Quantité: {support[1]}") - - step = last_candle['close'] / 100 - # Exemple : somme des quantités sur des plages de prix pour les bids - price_intervals = np.arange(bids_array[:, 0].min(), bids_array[:, 0].max(), step=step) # Intervalles de 10 USDT - - for start_price in price_intervals: - end_price = start_price + step - mask = (bids_array[:, 0] >= start_price) & (bids_array[:, 0] < end_price) - volume_in_range = bids_array[mask, 1].sum() - amount = volume_in_range * end_price - print( - f"Prix entre {start_price:.6f} et {end_price:.6f}: Volume total = {volume_in_range:.2f} amount={amount:.2f}") - - # Trier les bids par quantité en ordre décroissant - bids_sorted = bids_array[bids_array[:, 1].argsort()][::-1] - - # Sélectionner les trois plus gros supports - top_3_supports = bids_sorted[:3] - - # Afficher les trois plus gros supports - print("Les trois plus gros supports détectés:") - - self.updateLastValue(dataframe, 's1', top_3_supports[0][0]) - self.updateLastValue(dataframe, 's2', top_3_supports[1][0]) - self.updateLastValue(dataframe, 's3', top_3_supports[2][0]) - self.updateLastValue(dataframe, 's_min', max(top_3_supports[0][0], top_3_supports[1][0], top_3_supports[2][0])) - - for support in top_3_supports: - print(f"{pair} Prix: {support[0]}, Quantité: {support[1]}") - - def updateLastValue(self, df: DataFrame, col, value): - if col in df.columns: - print(f"update last col {col} {value}") - df.iloc[-1, df.columns.get_loc(col)] = value - else: - print(f"update all col {col} {value}") - df[col] = value - def smooth_series(self, series, alpha_low=0.1, alpha_high=0.5, threshold=0.2): """ Applique un lissage adaptatif sur une série Pandas. @@ -1384,43 +889,6 @@ class Zeus_8_3_2_B_4_2(IStrategy): return pd.Series(smoothed, index=series.index) - # def update_last_record(self, dataframe: DataFrame, new_data): - # # Vérifiez si de nouvelles données ont été reçues - # if new_data is not None: - # # Ne mettez à jour que la dernière ligne du dataframe - # last_index = dataframe.index[-1] # Sélectionne le dernier enregistrement - # dataframe.loc[last_index] = new_data # Met à jour le dernier enregistrement avec les nouvelles données - # return dataframe - - def calculateSMA(self, nb, asks, bids): - # Prepare data for plotting - bid_prices = [float(bid[0]) for bid in bids] - bid_volumes = [float(bid[1]) for bid in bids] - - ask_prices = [float(ask[0]) for ask in asks] - ask_volumes = [float(ask[1]) for ask in asks] - - # Convert to pandas DataFrame to apply moving average - bid_df = pd.DataFrame({'price': bid_prices, 'volume': bid_volumes}) - ask_df = pd.DataFrame({'price': ask_prices, 'volume': ask_volumes}) - - # Apply a rolling window to calculate a 10-value simple moving average (SMA) - bid_df['volume_sma'] = bid_df['volume'].rolling(window=nb).mean() - ask_df['volume_sma'] = ask_df['volume'].rolling(window=nb).mean() - - # Pour bid_df - bid_df = bid_df.dropna(subset=['volume_sma']) - bids_with_sma = list(zip(bid_df['price'], bid_df['volume_sma'])) - - # Pour ask_df - ask_df = ask_df.dropna(subset=['volume_sma']) - asks_with_sma = list(zip(ask_df['price'], ask_df['volume_sma'])) - - # print(bids_with_sma) - # print(asks_with_sma) - - return asks_with_sma, bids_with_sma - def calculateUpDownPct(self, dataframe, key): down_pct_values = np.full(len(dataframe), np.nan) # Remplir la colonne avec les bons calculs @@ -1506,33 +974,3 @@ class Zeus_8_3_2_B_4_2(IStrategy): return df - def test_signal_success(self, df, condition, percent=0.03, window_size=36): - """ - df : DataFrame avec colonnes ['close', 'high', ...] - percent : hausse recherchée (ex: 0.03 pour +3%) - window_size : nombre de bougies (ex: 36 pour 3h en 5m) - """ - # Exemple condition : RSI < 30 et EMA20 > SMA50 - hits = 0 - total = 0 - - for idx in df[condition].index: - price_now = df.loc[idx, 'close'] - idx_pos = df.index.get_loc(idx) - - # Fenêtre de h heures - future_idx = df.index[idx_pos + 1: idx_pos + 1 + window_size] - if len(future_idx) < window_size: - continue - - future_highs = df.loc[future_idx, 'close'] - if (future_highs >= price_now * (1 + percent)).any(): - # print(f"{price_now} ==> {df.loc[future_idx]['close']}") - hits += 1 - total += 1 - - prob = hits / total if total > 0 else 0 - print(f"✅ {hits}/{total} hausses >= {percent*100:.1f}% dans {window_size} bougies → probabilité : {prob:.2%}") - return prob - -