From 914cb9c8e26322a41e4845040a6f3d70136964f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Delacotte?= Date: Wed, 2 Apr 2025 23:48:43 +0200 Subject: [PATCH] =?UTF-8?q?Zeus=5F11=20m=C3=A9nage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Zeus_11.py | 427 ++++------------------------------------------------- 1 file changed, 26 insertions(+), 401 deletions(-) diff --git a/Zeus_11.py b/Zeus_11.py index bdcf82a..c315124 100644 --- a/Zeus_11.py +++ b/Zeus_11.py @@ -191,11 +191,12 @@ class Zeus_11(IStrategy): 'expected_profit': 0, "last_candle": {}, "last_trade": None, + "last_count_of_buys": 0, 'base_stake_amount': 0, 'stop_buy': False } - for pair in ["BTC/USDC", "ETH/USDC", "DOGE/USDC", "DASH/USDC", "XRP/USDC", "SOL/USDC", - "BTC/USDT", "ETH/USDT", "DOGE/USDT", "DASH/USDT", "XRP/USDT", "SOL/USDT"] + for pair in ["BTC/USDC", "ETH/USDC", "DOGE/USDC", "XRP/USDC", "SOL/USDC", + "BTC/USDT", "ETH/USDT", "DOGE/USDT", "XRP/USDT", "SOL/USDT"] } def min_max_scaling(self, series: pd.Series) -> pd.Series: @@ -261,6 +262,7 @@ class Zeus_11(IStrategy): allow_to_sell = (last_candle['percent'] < 0) if allow_to_sell: + self.pairs[pair]['last_count_of_buys'] = self.pairs[pair]['count_of_buys'] self.pairs[pair]['last_sell'] = rate self.pairs[pair]['last_trade'] = trade self.pairs[pair]['last_candle'] = last_candle @@ -321,9 +323,10 @@ class Zeus_11(IStrategy): if (last_candle['percent12'] <= -0.01) & (current_profit >= expected_profit): self.trades = list() return 'profit_' + str(count_of_buys) - if (current_profit >= expected_profit) & (last_candle['percent'] < 0.0) and ((last_candle['rsi'] >= 75) or before_last_candle['rsi'] >= 75): + if (current_profit >= expected_profit) & (last_candle['percent'] < 0.0) \ + and ((last_candle['rsi'] >= 75) or before_last_candle['rsi'] >= 75): self.trades = list() - return 'min_max200_' + str(count_of_buys) + return 'rsi_' + str(count_of_buys) def informative_pairs(self): # get access to all pairs available in whitelist. @@ -378,8 +381,7 @@ class Zeus_11(IStrategy): if trade_type is not None: trade_type = trade_type \ - + " " + str(round(100 * self.pairs[pair]['expected_profit'], 1)) - # + " " + str(round(last_candle['sma5_diff_1d'], 1)) \ + + " " + str(round(100 * last_candle['sma5_pct_1d'], 0)) # + " " + str(round(last_candle['sma5_diff_1h'], 1)) print( @@ -405,7 +407,6 @@ class Zeus_11(IStrategy): dataframe['min200'] = talib.MIN(dataframe['close'], timeperiod=200) dataframe['max50'] = talib.MAX(dataframe['close'], timeperiod=50) - dataframe['max144'] = talib.MAX(dataframe['close'], timeperiod=144) dataframe['min_max50'] = (dataframe['max50'] - dataframe['min50']) / dataframe['min50'] dataframe['max200'] = talib.MAX(dataframe['close'], timeperiod=200) @@ -422,15 +423,7 @@ class Zeus_11(IStrategy): dataframe["percent12"] = (dataframe["close"] - dataframe["open"].shift(12)) / dataframe["open"].shift(12) dataframe["percent24"] = (dataframe["close"] - dataframe["open"].shift(24)) / dataframe["open"].shift(24) dataframe["percent48"] = (dataframe["close"] - dataframe["open"].shift(48)) / dataframe["open"].shift(48) - dataframe["percent_max_144"] = (dataframe["close"] - dataframe["max144"]) / dataframe["close"] - dataframe['sma10_s2'] = dataframe['sma10'].shift(1) - dataframe['sma20_s2'] = dataframe['sma20'].shift(1) - dataframe['percent12_s2'] = dataframe['percent12'].shift(1) - - dataframe['sma5_s5'] = dataframe['sma5'].shift(4) - dataframe['sma10_s5'] = dataframe['sma10'].shift(4) - dataframe['sma20_s5'] = dataframe['sma20'].shift(4) # print(metadata['pair']) dataframe['rsi'] = talib.RSI(dataframe['close'], length=14) @@ -450,8 +443,6 @@ class Zeus_11(IStrategy): dataframe['average_line_50'] = talib.MIDPOINT(dataframe['close'], timeperiod=50) 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'].tail(576).sort_values() lowest_4 = sorted_close_prices.head(20) @@ -470,9 +461,6 @@ class Zeus_11(IStrategy): # # Propagate this mean value across the entire dataframe # dataframe['highest_4_average'] = dataframe['highest_4_average'].iloc[0] - dataframe['volatility'] = talib.STDDEV(dataframe['close'], timeperiod=144) / dataframe['close'] - dataframe['atr'] = talib.ATR(dataframe['high'], dataframe['low'], dataframe['close'], timeperiod=144) / \ - dataframe['close'] # dataframe['pct_average'] = (dataframe['highest_4_average'] - dataframe['close']) / dataframe['lowest_4_average'] # dataframe['highest_4_average_1'] = dataframe['highest_4_average'] * 0.99 # dataframe['highest_4_average_2'] = dataframe['highest_4_average'] * 0.98 @@ -496,13 +484,20 @@ class Zeus_11(IStrategy): # Normaliser les données de 'close' # normalized_close = self.min_max_scaling(dataframe['close']) ################### INFORMATIVE 1h - informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1h") - informative['volatility'] = talib.STDDEV(informative['close'], timeperiod=14) / informative['close'] - informative['atr'] = (talib.ATR(informative['high'], informative['low'], informative['close'], timeperiod=14)) / informative['close'] - dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "1h", ffill=True) + # informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1h") + # x_percent = 0.01 + # n_hours = 6 + # n_candles = n_hours * 60 # metadata["timeframe"] # Convertir en bougies + # + # informative["max_profit"] = dataframe["informative"].rolling(n_candles).max() + # informative["profit_hit"] = dataframe["informative"] >= informative["close"] * (1 + x_percent) + # + # dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "1h", ffill=True) ################### INFORMATIVE 1d informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1d") + informative['sma5'] = talib.SMA(informative, timeperiod=5) + informative['sma5_pct'] = 100 * (informative['sma5'] - informative['sma5'].shift(1)) / informative['sma5'] sorted_close_prices = informative['close'].tail(365).sort_values() lowest_4 = sorted_close_prices.head(4) informative['lowest_4'] = lowest_4.mean() @@ -621,19 +616,6 @@ class Zeus_11(IStrategy): 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) - return dataframe def getOpenTrades(self): @@ -713,7 +695,7 @@ class Zeus_11(IStrategy): # 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) \ - and (pct_max < -0.015): + and (pct_max < -0.012 - (count_of_buys * 0.001)): try: # This then calculates current safety order size @@ -803,26 +785,22 @@ class Zeus_11(IStrategy): # # Retourner le stoploss dynamique en pourcentage du prix actuel # return (atr_stoploss / current_rate) - 1 - def expectedProfit(self, pair: str, dataframe: DataFrame): + def expectedProfit(self, pair: str, last_candle): - current_price = dataframe['last_price'] # dataframe['close'] + current_price = last_candle['last_price'] # dataframe['close'] # trade = self.getTrade(pair) # if trade: # current_price = trade.open_rate # Calculer le max des 14 derniers jours - min_14_days = dataframe['lowest_1d'] - max_14_days = dataframe['highest_1d'] + min_14_days = last_candle['lowest_1d'] + max_14_days = last_candle['highest_1d'] percent = (max_14_days - current_price) / (min_14_days) - min_max = dataframe['pct_min_max_1d'] # (max_14_days - min_14_days) / min_14_days - expected_profit = min(0.1, max(0.01, dataframe['min_max200'] * 0.5)) + min_max = last_candle['pct_min_max_1d'] # (max_14_days - min_14_days) / min_14_days + expected_profit = min(0.1, max(0.01, last_candle['min_max200'] * 0.5 + self.pairs[pair]['count_of_buys'] * 0.0005)) - # 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): @@ -876,359 +854,6 @@ class Zeus_11(IStrategy): # # return adjusted_stake_amount - def analyze_conditions(self, pair: str, row: DataFrame): - dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) - - if dataframe is None or dataframe.empty: - return - if row is None or row.empty: - return - # Créer un tableau pour stocker les résultats de l'analyse - results = [] - # row = dataframe.iloc[-1].squeeze() - # result = {'triggered': False, 'conditions_failed': []} - try: - buy_level = row['buy_level'] - except Exception as exception: - print(exception) - return None - # Première condition : 'buy_fractal' - print('------------------------------------------------') - print('Test buy fractal ' + pair + ' buy_level=' + str(buy_level)) - if not ( - (row['close'] <= (row['min200'] * 1.002)) and - (row['percent_max_144'] <= -0.012) and - (row['haopen'] < buy_level) and - (row['open'] < row['average_line_288']) and - (dataframe['min50'].shift(3).iloc[-1] == row['min50']) - ): - failed_conditions = [] - if row['close'] > (row['min200'] * 1.002): - print('close > min200 * 1.002') - if row['percent_max_144'] > -0.012: - print('percent_max_144 > -0.012') - if row['haopen'] >= buy_level: - print('haopen >= buy_level') - if row['open'] >= row['average_line_288']: - print('open >= average_line_288') - if dataframe['min50'].shift(3).iloc[-1] != row['min50']: - print('min50.shift(3) != min50') - # result['conditions_failed'].append({'buy_fractal': failed_conditions}) - print('------------------------------------------------') - print('Test buy_max_diff_015 ' + pair + ' buy_level=' + str(buy_level)) - # Deuxième condition : 'buy_max_diff_015' - if not ( - (dataframe['max200_diff'].shift(4).iloc[-1] >= 0.015) and - (row['close'] <= row['lowest_4_average'] * 1.002) and - (row['close'] <= row['min200'] * 1.002) and - (dataframe['max50_diff'].shift(4).iloc[-1] >= 0.01) and - (row['haclose'] < row['bb_middleband']) and - (row['close'] < buy_level) and - (row['open'] < row['average_line_288']) and - (dataframe['min50'].shift(3).iloc[-1] == row['min50']) - ): - if dataframe['max200_diff'].shift(4).iloc[-1] < 0.015: - print('max200_diff.shift(4) < 0.015') - if row['close'] > row['lowest_4_average'] * 1.002: - print('close > lowest_4_average * 1.002') - if row['close'] > row['min200'] * 1.002: - print('close > min200 * 1.002') - if dataframe['max50_diff'].shift(4).iloc[-1] < 0.01: - print('max50_diff.shift(4) < 0.01') - if row['haclose'] >= row['bb_middleband']: - print('haclose >= bb_middleband') - if row['close'] >= buy_level: - print('close >= buy_level') - if row['open'] >= row['average_line_288']: - print('open >= average_line_288') - if dataframe['min50'].shift(3).iloc[-1] != row['min50']: - print('min50.shift(3) != min50') - print('------------------------------------------------') - print('Test buy_min_max_200 ' + pair + ' buy_level=' + str(buy_level)) - if not ( - (row['close'] <= row['min200'] * 1.002) - and (row['min_max200'] > 0.015) - and (row['haopen'] < buy_level) - and (row['open'] < row['average_line_288']) - ): - if row['close'] > row['min200'] * 1.002: - print('close > row[min200] * 1.002') - if row['min_max200'] <= 0.015: - print('row[min_max200] <= 0.015') - if row['haopen'] < buy_level: - print('row[haopen] < buy_level') - if row['open'] < row['average_line_288']: - print('row[open] >= row[average_line_288]') - print('------------------------------------------------') - - # Ajouter le résultat à la liste des résultats - # results.append(result) - - # print(result) - - 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 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