# --- Do not remove these libs --- from statistics import median from freqtrade.strategy import IStrategy, stoploss_from_absolute import sys import os # 添加父目录到系统路径 sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from ChanLun import ChanLun from ChanEnum import Chan_FX_TYPE, Chan_KLC_FX, Chan_BI_DIR, Chan_KLC_FX # -------------------------------- from technical.util import resample_to_interval, resampled_merge import talib.abstract as ta from pandas import DataFrame import pandas as pd from datetime import datetime, timedelta from freqtrade.persistence import Trade, Order from typing import Optional import logging logger = logging.getLogger(__name__) ### Now you can use logger.info('asfd') to log # freqtrade plot-dataframe --strategy ChanLun_BTC --datadir user_data/data/binance -c ./user_data/ChanLun_SOL_30.json --timerange=20250309- # freqtrade trade -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies # freqtrade backtesting -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies --timerange=20251008- # freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_30.json -t 1m 1m 1h 1d 1M --pairs BTC/USDT:USDT --timerange=20250405- # freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_30.json -t 1m 1h 1d 1M --pairs BTC/USDT --timerange=20170101- # freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies -c ./user_data/Chan/config/ChanLun_BTC_30.json -e 200 --timerange=20250201-20250901 # freqtrade edge -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901 # freqtrade plot-dataframe -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901 # sudo docker compose run --rm chanlun_btc backtesting -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies --timerange=20250721- # sudo docker compose run --rm chanlun_btc download-data -c ./user_data/Chan/config/ChanLun_BTC_30.json --pairs BTC/USDT:USDT -t 1m --timerange 20240101- # sudo docker compose run --rm chanlun_btc trade -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy ChanLun_BTC --strategy-path ./user_data/Chan/strategies class ChanLun_BTC(IStrategy): INTERFACE_VERSION: int = 3 # Minimal ROI designed for the strategy. # This attribute will be overridden if the config file contains "minimal_roi" # 30m and 1h minimal_roi = { "0": 0.15, "360": 0.2, "640": 0.1, "1200": 0 } # 5m and 15m minimal_roi_1 = { "0": 0.1, "60": 0.05, "120": 0.02, "240": 0 } # 15m and 30m minimal_roi_1 = { "0": 0.1, "240": 0.05, "480": 0.03, "600": 0 } minimal_roi_1 = { "0": 1.50, "120": 0.05, "240": 0.025, "360": 0 } can_short = True lev = 1.0 stoploss = -0.3 # 设置为很大的负值,让custom_stoploss来控制 use_custom_stoploss = True # 启用自定义止损 trailing_stop = False trailing_stop_positive = 0.03 trailing_stop_positive_offset = 0.06 trailing_only_offset_is_reached = False # 关闭分批止盈/仓位调整 position_adjustment_enable = False startup_candle_count = 1600 time3m = 3 time5m = 5 time10m = 10 time15m = 15 time30m = 30 time_m = [3, 5, 10, 15, 30] time1h = 60 time2h = 2 time4h = 4 time6h = 6 time8h = 8 time12h = 12 time16h = 16 time_h = [2, 4, 6, 8, 12, 16] time2d = 2 time3d = 3 time1w = 7 time_d = [2, 3, 7] time2M = 2 time3M = 3 time_M = [2, 3] last_time = datetime.now() chan = ChanLun() last_order = None last_trade = None pair = 'BTC/USDT:USDT' def informative_pairs(self): timeframes = ['1h', '1d', '1M'] informative_pairs = [(self.pair, tf) for tf in timeframes] return informative_pairs def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: self.init_dataframes(dataframe) return dataframe def init_dataframes(self, dataframe_1m): 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_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'] 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 if trade: if trade.is_short: new_entryprice = proposed_rate - 50 else: new_entryprice = proposed_rate + 50 return new_entryprice def custom_exit_price(self, pair: str, trade: Trade, current_time: datetime, proposed_rate: float, current_profit: float, exit_tag: str | None, **kwargs) -> float: new_exitprice = proposed_rate if trade: if trade.is_short: new_exitprice = proposed_rate + 50 else: new_exitprice = proposed_rate - 50 return new_exitprice def adjust_trade_position(self, trade: Trade, current_time: datetime, current_rate: float, current_profit: float, min_stake: Optional[float], max_stake: float, current_entry_rate: float, current_exit_rate: float, current_entry_profit: float, current_exit_profit: float, **kwargs) -> Optional[float]: # 关闭分批止盈,始终不调整仓位 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') 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') 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, **kwargs) -> float: return self.lev