From 42dac07274ccfd77e519da38be4f05ef0871125c Mon Sep 17 00:00:00 2001 From: jackyu66git Date: Mon, 2 Feb 2026 00:35:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=96=B0=E7=9A=84=E5=91=A8?= =?UTF-8?q?=E6=9C=9F=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ChanBIZS.py | 2 +- ChanLun.py | 37 +++++-- TF_DF.py | 12 +- strategies/ChanLun_EMA52.py | 214 ++++-------------------------------- web/app.py | 2 +- 5 files changed, 64 insertions(+), 203 deletions(-) diff --git a/ChanBIZS.py b/ChanBIZS.py index 32245e9..464f3a6 100644 --- a/ChanBIZS.py +++ b/ChanBIZS.py @@ -25,7 +25,7 @@ class ChanBIZS(): self.set_end_time(end_bi.end_klc.end_time) self.is_sure = True self.sure_time = sure_bi.sure_time - print(self.start_time, self.is_sure, len(self.bi_list), self.dir) + # print(self.start_time, self.is_sure, len(self.bi_list), self.dir) def set_end_time(self, end_time): self.end_time = end_time def set_zg(self, zg): diff --git a/ChanLun.py b/ChanLun.py index 3ecf133..e1c099b 100644 --- a/ChanLun.py +++ b/ChanLun.py @@ -18,13 +18,17 @@ from TF_DF import TF_DF class ChanLun(): def __init__(self): + self.time2m = 2 self.time3m = 3 self.time5m = 5 self.time10m = 10 - self.time15m = 15 + self.time20m = 20 + self.time_m_intervals = [2, 3, 5, 10, 20] + self.time_m_symbols = ['2m', '3m', '5m', '10m', '20m'] self.time30m = 30 - self.time_m_intervals = [2, 3, 5, 10, 15, 20, 30] - self.time_m_symbols = ['2m', '3m', '5m', '10m', '15m', '20m','30m'] + self.time45m = 45 + self.time_m15_intervals = [30, 45] + self.time_m15_symbols = ['30m', '45m'] self.time2h = 2*60 self.time4h = 4*60 self.time6h = 6*60 @@ -35,35 +39,43 @@ class ChanLun(): self.time_h_symbols = ['2h', '4h', '6h', '8h', '12h', '16h'] self.time2d = 2*24*60 self.time3d = 3*24*60 + self.time_d_intervals = [2*24*60, 3*24*60] + self.time_d_symbols = ['2d', '3d'] self.time1w = 7*24*60 self.time2w = 14*24*60 - self.time_d_intervals = [2*24*60, 3*24*60, 7*24*60, 14*24*60] - self.time_d_symbols = ['2d', '3d', '1w', '2w'] + self.time_w_intervals = [14*24*60] + self.time_w_symbols = ['2w'] self.time2M = 2*30*24*60 self.time3M = 3*30*24*60 self.time6M = 6*30*24*60 self.time1y = 12*30*24*60 self.time_M_intervals = [2*30*24*60, 3*30*24*60, 6*30*24*60, 12*30*24*60] self.time_M_symbols = ['2M', '3M', '6M', '1y'] - self.time_symbols = ['1m', '2m', '3m', '5m', '10m', '15m', '20m','30m', '1h', '2h', '4h', '6h', '8h', '12h', '16h', '1d', '2d', '3d', '1w', '2w', '1M', '3M', '6M', '1y'] + self.time_symbols = ['1m', '2m', '3m', '5m', '10m', '15m', '20m', '30m', '45m','1h', '2h', '4h', '6h', '8h', '12h', '16h', '1d', '2d', '3d', '1w', '2w', '1M', '3M', '6M', '1y'] self.tf_df_dict = {} - self.ema_symbols = ['1m', '2m', '3m', '5m', '10m', '15m', '20m','30m', '1h', '2h', '4h', '6h', '8h', '12h', '16h', '1d', '2d', '3d'] + self.ema_symbols = ['1m', '2m', '3m', '5m', '10m', '15m', '20m', '30m', '45m', '1h', '2h', '4h', '6h', '8h', '12h', '16h', '1d', '2d', '3d'] self.tf_df = TF_DF() def init_data(self, dataframe, intervals, timeframes): for index in range(0, len(intervals)): timeframe = timeframes[index] interval = intervals[index] self.tf_df_dict[timeframe] = TF_DF(dataframe, interval, timeframe) - def init_dataframes(self, dataframe_m=None, dataframe_h=None, dataframe_d=None, dataframe_M=None): + def init_dataframes(self, dataframe_m=None, dataframe_15m=None, dataframe_h=None, dataframe_d=None, dataframe_w=None, dataframe_M=None): if dataframe_m is not None: self.tf_df_dict['1m'] = TF_DF(dataframe_m, 1, '1m') self.init_data(dataframe_m, self.time_m_intervals, self.time_m_symbols) + if dataframe_15m is not None: + self.tf_df_dict['15m'] = TF_DF(dataframe_15m, 1, '15m') + self.init_data(dataframe_15m, self.time_m15_intervals, self.time_m15_symbols) if dataframe_h is not None: self.tf_df_dict['1h'] = TF_DF(dataframe_h, 1, '1h') self.init_data(dataframe_h, self.time_h_intervals, self.time_h_symbols) if dataframe_d is not None: self.tf_df_dict['1d'] = TF_DF(dataframe_d, 1, '1d') self.init_data(dataframe_d, self.time_d_intervals, self.time_d_symbols) + if dataframe_w is not None: + self.tf_df_dict['1w'] = TF_DF(dataframe_w, 1, '1w') + self.init_data(dataframe_w, self.time_w_intervals, self.time_w_symbols) if dataframe_M is not None: self.tf_df_dict['1M'] = TF_DF(dataframe_M, 1, '1M') self.init_data(dataframe_M, self.time_M_intervals, self.time_M_symbols) @@ -79,13 +91,18 @@ class ChanLun(): if len(self.tf_df_dict) > 0: return {key: self.tf_df_dict[key].get_current_klc() for key in self.ema_symbols} return None + def get_tf_df_by_timeframe(self, timeframe): + if timeframe in self.tf_df_dict: + return self.tf_df_dict[timeframe] + return None def check_price_ema52(self, price): key_list = [] if len(self.tf_df_dict) > 0: ema52_dict = self.get_ema52_dict() for key in self.ema_symbols: - if abs(price - ema52_dict[key]) < 100: - key_list.append(key) + if ema52_dict[key] is not None: + if abs(price - ema52_dict[key]) < 100: + key_list.append(key) return key_list diff --git a/TF_DF.py b/TF_DF.py index fb4d3ca..5d027ed 100644 --- a/TF_DF.py +++ b/TF_DF.py @@ -22,7 +22,17 @@ class TF_DF(): def init_TF_DF(self, df, interval, timeframe): self.timeframe = timeframe self.interval = interval - self.dataframe = resample_to_interval(df, interval) + # 检查 DataFrame 是否为空或没有 date 列 + if df is None or df.empty: + raise ValueError(f"DataFrame for {timeframe} is empty. Please download data first.") + if 'date' not in df.columns: + raise ValueError(f"DataFrame for {timeframe} missing 'date' column. Columns: {df.columns.tolist()}") + # interval=1 时不需要重采样 + if interval == 1: + self.dataframe = df.copy() + else: + self.dataframe = resample_to_interval(df, interval) + #print(self.timeframe, len(self.dataframe)) self.dataframe = self.add_indicators(self.dataframe) self.klu_list = [] self.klc_list = [] diff --git a/strategies/ChanLun_EMA52.py b/strategies/ChanLun_EMA52.py index e375cfd..69c3b85 100644 --- a/strategies/ChanLun_EMA52.py +++ b/strategies/ChanLun_EMA52.py @@ -77,7 +77,7 @@ class ChanLun_EMA52(IStrategy): can_short = True lev = 1.0 stoploss = -0.3 # 设置为很大的负值,让custom_stoploss来控制 - use_custom_stoploss = True # 启用自定义止损 + use_custom_stoploss = False # 启用自定义止损 trailing_stop = False trailing_stop_positive = 0.03 @@ -86,87 +86,35 @@ class ChanLun_EMA52(IStrategy): # 关闭分批止盈/仓位调整 position_adjustment_enable = False - startup_candle_count = 1600 - + # startup_candle_count = 1600 + big_tf = '1h' + small_tf = '15m' last_time = datetime.now() chan = ChanLun() last_order = None last_trade = None pair = 'BTC/USDT:USDT' + def informative_pairs(self): + return [(self.pair, "1h"), + (self.pair, "1d"), + (self.pair, "1M"), + (self.pair, "15m"), + (self.pair, "1w"), + ] def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: self.init_dataframes(dataframe) + dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) + last_price = dataframe.iloc[-1]['close'] + tf_ema52_list = self.chan.check_price_ema52(last_price) + print(tf_ema52_list) return dataframe def init_dataframes(self, dataframe_1m): + dataframe_15m = self.dp.get_pair_dataframe(pair=self.pair, timeframe='15m') dataframe_1h = self.dp.get_pair_dataframe(pair=self.pair, timeframe='1h') dataframe_1d = self.dp.get_pair_dataframe(pair=self.pair, timeframe='1d') + dataframe_1w = self.dp.get_pair_dataframe(pair=self.pair, timeframe='1w') dataframe_1M = self.dp.get_pair_dataframe(pair=self.pair, timeframe='1M') - self.chan.init_dataframes(dataframe_1m, dataframe_1h, dataframe_1d, dataframe_1M) - current_price = dataframe_1m.iloc[-1]['close'] - print("Current Price: ", current_price) - self.print_all_current_klc() - def print_all_ema52(self): - for key, value in self.chan.get_ema52_dict().items(): - print(key, value) - def print_all_ema24(self): - for key, value in self.chan.get_ema24_dict().items(): - print(key, value) - def print_all_current_klc(self): - for key, value in self.chan.get_current_klc_dict().items(): - print(key, value.to_string()) - def add_indicators(self, df): - fast = 12 - slow = 26 - period = 9 - macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period) - bb365 = ta.BBANDS(df, timeperiod=365, nbdevup=3.0, nbdevdn=3.0, matype=0) - bb120 = ta.BBANDS(df, timeperiod=120, nbdevup=3.0, nbdevdn=3.0, matype=0) - bb30 = ta.BBANDS(df, timeperiod=41, nbdevup=2.3, nbdevdn=2.3, matype=0) - bb302 = ta.BBANDS(df, timeperiod=41, nbdevup=2.0, nbdevdn=2.0, matype=0) - bb30 = ta.BBANDS(df, timeperiod=20, nbdevup=2.0, nbdevdn=2.0, matype=0) - bb302 = ta.BBANDS(df, timeperiod=20, nbdevup=2.0, nbdevdn=2.0, matype=0) - # 计算布林带中轨(移动平均线) - bb30_middle = ta.SMA(df, timeperiod=90) - - # 手动计算布林带 %B 指标 (BBP) - # %B = (Price - Lower Band) / (Upper Band - Lower Band) - bbp365 = (df['close'] - bb365['lowerband']) / (bb365['upperband'] - bb365['lowerband']) - bbp120 = (df['close'] - bb120['lowerband']) / (bb120['upperband'] - bb120['lowerband']) - bbp30 = (df['close'] - bb30['lowerband']) / (bb30['upperband'] - bb30['lowerband']) - bbp302 = (df['close'] - bb302['lowerband']) / (bb302['upperband'] - bb302['lowerband']) - df['atr'] = ta.ATR(df, timeperiod=14) - df['bbup365'] = bb365['upperband'] - df['bblow365'] = bb365['lowerband'] - df['bbp365'] = bbp365 - df['bbup120'] = bb120['upperband'] - df['bblow120'] = bb120['lowerband'] - df['bbp120'] = bbp120 - df['bbup30'] = bb30['upperband'] - df['bblow30'] = bb30['lowerband'] - df['bbmiddle30'] = bb30_middle # 添加bb30中轨 - df['bbp30'] = bbp30 - df['bbup302'] = bb302['upperband'] - df['bblow302'] = bb302['lowerband'] - df['bbp302'] = bbp302 - df['macd'] = macd['macd'] - df['macdsignal'] = macd['macdsignal'] - df['macdhist'] = macd['macdhist'] - df['ema5'] = ta.EMA(df, timeperiod=5) - df['ema10'] = ta.EMA(df, timeperiod=10) - df['ema24'] = ta.EMA(df, timeperiod=24) - df['ema26'] = ta.EMA(df, timeperiod=26) - df['ema52'] = ta.EMA(df, timeperiod=52) - df['rsi'] = ta.RSI(df, timeperiod=14) - df['volume_ratio'] = self.cal_volume_ratio(df) - return df - def cal_volume_ratio(self, dataframe, window=10): - df = dataframe.copy() - # 计算过去N根K线的平均成交量 - df['avg_volume'] = df['volume'].rolling(window=window).mean() - # 计算量比 - df['volume_ratio'] = df['volume'] / df['avg_volume'] - # 填充缺失值(前N根K线) - df['volume_ratio'] = df['volume_ratio'].fillna(1.0) - return df['volume_ratio'] + self.chan.init_dataframes(dataframe_1m, dataframe_15m,dataframe_1h, dataframe_1d, dataframe_1w, dataframe_1M) def custom_entry_price(self, pair: str, trade: Trade | None, current_time: datetime, proposed_rate: float, entry_tag: str | None, side: str, **kwargs) -> float: new_entryprice = proposed_rate @@ -197,134 +145,20 @@ class ChanLun_EMA52(IStrategy): # 关闭分批止盈,始终不调整仓位 return None - def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime, - current_rate: float, current_profit: float, after_fill: bool, - **kwargs) -> float | None: - """ - 止损 = 开仓价 ± 1 * ATR(开仓时的ATR)。 - 多单: 开仓价 - ATR;空单: 开仓价 + ATR。 - """ - # 保本止损:当浮盈达到或超过 1% 时,将止损提至开仓价 - #if current_profit is not None and current_profit >= 0.14: - #return stoploss_from_absolute(trade.open_rate, current_rate, is_short=trade.is_short) - - entry_atr = trade.get_custom_data(key="entry_atr") - if entry_atr is None: - # 回退:取当前数据的 ATR 估算 - dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe) - if dataframe is not None and len(dataframe) > 0 and 'atr' in dataframe.columns: - entry_atr = float(dataframe.iloc[-1]['atr']) - else: - # 最保守的回退:5% - return -0.05 - dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe) - last_candle = dataframe.iloc[-1].squeeze() - ema52_str = 'resample_{}_ema52'.format(self.time15m) - ema52_val = float(last_candle.get(ema52_str, 0) or 0) - close_str = 'resample_{}_close'.format(self.time15m) - close_val = float(last_candle.get(close_str, 0) or 0) - if close_val < ema52_val: - return -0.01 - if trade.is_short: - stop_price = trade.open_rate + float(entry_atr) - else: - stop_price = trade.open_rate - float(entry_atr) - return stoploss_from_absolute(stop_price, current_rate, is_short=trade.is_short) - def custom_exit(self, pair: str, trade: Trade, current_time: datetime, current_rate: float, current_profit: float, **kwargs): # 不做分批止盈/最终止盈处理,退出由策略信号/ROI/止损决定 return None - def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, - time_in_force: str, current_time: datetime, entry_tag: str | None, - side: str, **kwargs) -> bool: - """ - ATR 过滤:atr < 100 不开单。 - """ - try: - dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) - if dataframe is None or len(dataframe) == 0: - return False - last = dataframe.iloc[-1] - atr_str = 'resample_{}_atr'.format(self.time1h) - atr_val = float(last.get(atr_str, 0) or 0) - if atr_val < 0.001: - #logger.info(f"ATR过滤:atr={atr_val:.2f} < 100, 拒绝进场 {pair}") - return False - return True - except Exception as e: - logger.warning(f"confirm_trade_entry 异常: {e}") - return True - - def order_filled(self, pair: str, trade: Trade, order: Order, current_time: datetime, **kwargs) -> None: - """ - Called right after an order fills. - Will be called for all order types (entry, exit, stoploss, position adjustment). - :param pair: Pair for trade - :param trade: trade object. - :param order: Order object. - :param current_time: datetime object, containing the current datetime - :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. - """ - # Obtain pair dataframe (just to show how to access it) - dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe) - last_candle = dataframe.iloc[-1].squeeze() - atr_str = 'resample_{}_atr'.format(elf.time15) - # 保存开仓时的ATR值用于止损计算 - if (trade.nr_of_successful_entries == 1) and (order.ft_order_side == trade.entry_side): - entry_atr = last_candle[atr_str] * 4 - trade.set_custom_data(key="entry_atr", value=entry_atr) - #logger.info(f"保存开仓时ATR值: {entry_atr}") - return None def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - shift15 = self.time15m - shift60 = self.time1h - bsp_col = 'resample_{}_bsp_mtf'.format(shift15) - score_col = 'resample_{}_mtf_score'.format(shift15) - macdh_col = 'resample_{}_macdhist'.format(shift15) - c60_col = 'resample_{}_close'.format(shift60) - e60_col = 'resample_{}_ema52'.format(shift60) - # 强化过滤:15m BSP + 分数阈值 + 60m 趋势同向 + 15m MACD柱同向 - if all(col in dataframe.columns for col in [bsp_col, score_col, macdh_col, c60_col, e60_col]): - dataframe.loc[ - ( - (dataframe[bsp_col].shift(shift15) == 1) & - (dataframe[score_col].shift(shift15) >= 1.2) & - (dataframe[c60_col].shift(shift60) >= dataframe[e60_col].shift(shift60)) & - (dataframe[macdh_col].shift(shift15) > 0) - ), - ['enter_long', 'enter_tag']] = (1, 'long_bsp15_v2') - dataframe.loc[ - ( - (dataframe[bsp_col].shift(shift15) == -1) & - (dataframe[score_col].shift(shift15) <= -1.2) & - (dataframe[c60_col].shift(shift60) <= dataframe[e60_col].shift(shift60)) & - (dataframe[macdh_col].shift(shift15) < 0) - ), - ['enter_short', 'enter_tag']] = (1, 'short_bsp15_v2') + dataframe.loc[ + (dataframe['rsi'] < 30), + 'enter_long'] = 1 return dataframe def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - shift15 = self.time15m - shift60 = self.time1h - bsp_col = 'resample_{}_bsp_mtf'.format(shift15) - score_col = 'resample_{}_mtf_score'.format(shift15) - c60_col = 'resample_{}_close'.format(shift60) - e60_col = 'resample_{}_ema52'.format(shift60) - # 反向强信号或60m趋势反向时平仓 - if all(col in dataframe.columns for col in [bsp_col, score_col, c60_col, e60_col]): - dataframe.loc[ - ( - ((dataframe[bsp_col].shift(shift15) == -1) & (dataframe[score_col].shift(shift15) <= -0.8)) | - (dataframe[c60_col].shift(shift60) < dataframe[e60_col].shift(shift60)) - ), - ['exit_long', 'exit_tag']] = (1, 'long_close_bsp15') - dataframe.loc[ - ( - ((dataframe[bsp_col].shift(shift15) == 1) & (dataframe[score_col].shift(shift15) >= 0.8)) | - (dataframe[c60_col].shift(shift60) > dataframe[e60_col].shift(shift60)) - ), - ['exit_short', 'exit_tag']] = (1, 'short_close_bsp15') + dataframe.loc[ + (dataframe['rsi'] > 70), + 'exit_long'] = 1 return dataframe def leverage(self, pair: str, current_time: datetime, current_rate: float, proposed_leverage: float, max_leverage: float, entry_tag: Optional[str], side: str, diff --git a/web/app.py b/web/app.py index fd1f92a..cfdcc30 100644 --- a/web/app.py +++ b/web/app.py @@ -45,7 +45,7 @@ china_stock = ChinaStockData() logger = logging.getLogger(__name__) DATA_SERVICE_URL = os.environ.get("DATA_SERVICE_URL", os.environ.get("DATASVC_URL", "http://127.0.0.1:9009")) - +DATA_SERVICE_URL = os.environ.get("DATA_SERVICE_URL", os.environ.get("DATASVC_URL", "http://192.168.1.9:9009")) DEFAULT_TIMEFRAME_LABELS = OrderedDict([ ("1m", "1分钟"), ("3m", "3分钟"),