328 lines
14 KiB
Python
328 lines
14 KiB
Python
# --- 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=20250901-
|
|
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_30.json -t 1m --pairs BTC/USDT:USDT --timerange=20250405-
|
|
# 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 = 2880
|
|
time3 = 3
|
|
time5 = 5
|
|
time15 = 15
|
|
time30 = 30
|
|
time60 = 60
|
|
time2h = 120
|
|
time4h = 240
|
|
time1d = 1440
|
|
last_time = datetime.now()
|
|
chan = ChanLun()
|
|
last_order = None
|
|
last_trade = None
|
|
|
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
|
|
dataframe = self.add_indicators(dataframe)
|
|
# 仅保留15m(用于BSP)与60m(用于ATR过滤/止损)两个重采样
|
|
dataframe_15 = resample_to_interval(dataframe, self.get_ticker_indicator() * 15)
|
|
dataframe_60 = resample_to_interval(dataframe, self.get_ticker_indicator() * 60)
|
|
# 计算多周期BSP(以15m为基准),并合并到15m数据上
|
|
# 先给重采样帧补指标
|
|
dataframe_15 = self.add_indicators(dataframe_15)
|
|
dataframe_60 = self.add_indicators(dataframe_60)
|
|
# 计算15m BSP
|
|
bsp_15 = self.chan.cal_bsp(dataframe, self.get_ticker_indicator())
|
|
# 合并15m与60m到主DF,生成 resample_*_* 列
|
|
dataframe = resampled_merge(dataframe, dataframe_15)
|
|
dataframe = resampled_merge(dataframe, dataframe_60)
|
|
return dataframe
|
|
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.get_ticker_indicator()*self.time15)
|
|
ema52_val = float(last_candle.get(ema52_str, 0) or 0)
|
|
close_str = 'resample_{}_close'.format(self.get_ticker_indicator()*self.time15)
|
|
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.get_ticker_indicator()*self.time60)
|
|
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(self.get_ticker_indicator()*self.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.time15
|
|
shift60 = self.time60
|
|
bsp_col = 'resample_{}_bsp_mtf'.format(self.get_ticker_indicator()*shift15)
|
|
score_col = 'resample_{}_mtf_score'.format(self.get_ticker_indicator()*shift15)
|
|
macdh_col = 'resample_{}_macdhist'.format(self.get_ticker_indicator()*shift15)
|
|
c60_col = 'resample_{}_close'.format(self.get_ticker_indicator()*shift60)
|
|
e60_col = 'resample_{}_ema52'.format(self.get_ticker_indicator()*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.time15
|
|
shift60 = self.time60
|
|
bsp_col = 'resample_{}_bsp_mtf'.format(self.get_ticker_indicator()*shift15)
|
|
score_col = 'resample_{}_mtf_score'.format(self.get_ticker_indicator()*shift15)
|
|
c60_col = 'resample_{}_close'.format(self.get_ticker_indicator()*shift60)
|
|
e60_col = 'resample_{}_ema52'.format(self.get_ticker_indicator()*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
|
|
|
|
def get_ticker_indicator(self):
|
|
return int(self.timeframe[:-1]) |