Files
Chan/strategies/BB90331.py
T
2025-08-10 19:55:26 +08:00

295 lines
10 KiB
Python

# --- Do not remove these libs ---
from freqtrade.strategy import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
import numpy as np
import pandas as pd
# --------------------------------
# 设置pandas选项以避免FutureWarning
pd.set_option('future.no_silent_downcasting', True)
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
from technical.util import resample_to_interval, resampled_merge
from freqtrade.persistence import Trade, Order
from datetime import datetime, timedelta
from typing import Optional
import logging
logger = logging.getLogger(__name__)
# freqtrade plot-dataframe --strategy BB90331 --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 BB90331 --strategy-path ./user_data/Chan/strategies
# freqtrade backtesting -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy BB90331 --strategy-path ./user_data/Chan/strategies --timerange=20250623-
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_30.json -t 1m --pairs BTC/USDT:USDT --timerange=20250501-
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss --strategy BB90331 --strategy-path ./user_data/Chan/strategies -c ./user_data/Chan/config/ChanLun_BTC_30.json -e 200 --timerange=20250201-20250401
# sudo docker compose run --rm chan_btc backtesting -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy BB90331 --strategy-path ./user_data/Chan/strategies --timerange=20250101-
# sudo docker compose run --rm chan_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 chan_btc trade -c ./user_data/Chan/config/ChanLun_BTC_30.json --strategy BB90331 --strategy-path ./user_data/Chan/strategies
class BB90331(IStrategy):
"""
布林带ATR反转策略
基于ATR动态调整布林带轨道,实现反转交易
交易逻辑:
- 做多:价格跌破下轨后反转
- 做空:价格突破上轨后反转
- 止盈:价格触及对侧轨道
- 止损:基于ATR动态设置
"""
INTERFACE_VERSION: int = 3
# 策略参数
bb_length = 90 # 布林带长度
atr_multiplier = 3.0 # ATR乘数(轨道)
atr_stop_multiplier = 1 # ATR乘数(止损)
atr_length = 11 # ATR计算周期
# Minimal ROI designed for the strategy.
# This attribute will be overridden if the config file contains "minimal_roi"
minimal_roi = {
}
can_short = True
# Optimal stoploss designed for the strategy
# This attribute will be overridden if the config file contains "stoploss"
stoploss = -0.3
use_custom_stoploss = True
# Optimal timeframe for the strategy
time = 1
# Trailing stop loss
trailing_stop = False
lev = 1.0
# Run "populate_indicators" only for new candle
process_only_new_candles = False
# Number of candles the strategy requires before producing valid signals
startup_candle_count: int = max(bb_length*time, atr_length*time) + 10
# 存储每个交易的止损价格
trade_stop_prices: Dict[str, float] = {}
# 信号确认机制相关变量 - 已删除,不再使用确认机制
# first_signal_time: Optional = None
# first_signal_type: Optional[str] = None # 'long' 或 'short'
# signal_confirm_hours = 4 # 4小时内需要确认信号
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
计算技术指标
"""
# 计算ATR(用于止损计算)
dataframe['atr'] = ta.ATR(dataframe, timeperiod=self.atr_length)
# 计算布林带(使用标准方法:移动平均线 ± 标准差倍数)
bb_upper, bb_middle, bb_lower = ta.BBANDS(dataframe['close'], timeperiod=self.bb_length, nbdevup=self.atr_multiplier, nbdevdn=self.atr_multiplier, matype=0)
dataframe['bb_upper'] = bb_upper
dataframe['bb_middle'] = bb_middle
dataframe['bb_lower'] = bb_lower
#for i in range(1700, 1800):
#print(dataframe_3.iloc[i])
# 计算突破条件(与Pine Script保持一致)
# 确保所有用于计算的数据都不是NaN
valid_data = (
dataframe['close'].notna() &
dataframe['bb_upper'].notna() &
dataframe['bb_lower'].notna() &
dataframe['close'].shift(1).notna() &
dataframe['bb_upper'].shift(1).notna() &
dataframe['bb_lower'].shift(1).notna()
)
dataframe['break_above_upper'] = (
(dataframe['close'] > dataframe['bb_upper']) &
(dataframe['close'].shift(1) <= dataframe['bb_upper'].shift(1)) &
valid_data
)
dataframe['break_below_lower'] = (
(dataframe['close'] < dataframe['bb_lower']) &
(dataframe['close'].shift(1) >= dataframe['bb_lower'].shift(1)) &
valid_data
)
return dataframe
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
Based on TA indicators, populates the entry trend columns
直接开仓策略:检测到信号立即开仓,不需要确认机制
"""
break_below_lower = 'break_below_lower'
break_above_upper = 'break_above_upper'
# 多头信号:价格跌破下轨后直接开仓
dataframe.loc[
(
(dataframe[break_below_lower] == True) &
(dataframe[break_below_lower].notna())
),
['enter_long', 'enter_tag']
] = (1, 'long_signal_chan_direct')
# 空头信号:价格突破上轨后直接开仓
dataframe.loc[
(
(dataframe[break_above_upper] == True) &
(dataframe[break_above_upper].notna())
),
['enter_short', 'enter_tag']
] = (1, 'short_signal_chan_direct')
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
Based on TA indicators, populates the exit trend columns
"""
bb_middle_str = 'bb_middle'
# 多头止盈:价格回到中轨时平仓
dataframe.loc[
(
(dataframe['close'] >= dataframe[bb_middle_str]) & # 当前价格回到中轨
(dataframe[bb_middle_str].notna()) & # 确保布林带中轨不是NaN
(dataframe['close'].notna()) & # 确保收盘价不是NaN
(len(self.trade_stop_prices) > 0)
),
['exit_long', 'exit_tag']] = (1, 'long_close_signal_chan')
# 空头止盈:价格回到中轨时平仓
dataframe.loc[
(
(dataframe['close'] <= dataframe[bb_middle_str]) & # 当前价格回到中轨
(dataframe[bb_middle_str].notna()) & # 确保布林带中轨不是NaN
(dataframe['close'].notna()) & # 确保收盘价不是NaN
(len(self.trade_stop_prices) > 0)
),
['exit_short', 'exit_tag']] = (1, 'short_close_signal_chan')
return dataframe
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime,
current_rate: float, current_profit: float,
after_fill: bool, **kwargs) -> float:
"""
自定义止损逻辑:使用开单时记录的ATR止损价格
"""
# 检查是否有存储的止损价格
trade_id = str(trade.id)
if trade_id not in self.trade_stop_prices:
return self.stoploss
# 获取最新的K线数据
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
if len(dataframe) < 2:
return self.stoploss
# 使用上一个K线的收盘价
last_close = dataframe.iloc[-2]['close'] # 上一个完整K线的收盘价
stop_price = self.trade_stop_prices[trade_id]
if trade.is_short:
# 空头止损:上一个K线收盘价超过止损价格时触发止损
if last_close >= stop_price:
stop_loss_pct = -abs((last_close - stop_price) / last_close)
else:
stop_loss_pct = 1.0 # 不触发止损
else:
# 多头止损:上一个K线收盘价低于止损价格时触发止损
if last_close <= stop_price:
stop_loss_pct = -abs((stop_price - last_close) / last_close)
else:
stop_loss_pct = 1.0 # 不触发止损
# 确保止损不会比默认止损更宽松
return max(stop_loss_pct, self.stoploss)
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
time_in_force: str, current_time: datetime, entry_tag: str,
side: str, **kwargs) -> bool:
"""
确认交易进场
"""
# 获取最新数据进行最终确认
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
if len(dataframe) == 0:
return False
latest_candle = dataframe.iloc[-1]
# 使用重采样后的字段名
bb_upper_str = 'bb_upper'
bb_lower_str = 'bb_lower'
atr_str = 'atr'
# 确保技术指标有效
if (np.isnan(latest_candle[bb_upper_str]) or
np.isnan(latest_candle[bb_lower_str]) or
np.isnan(latest_candle[atr_str])):
return False
return True
def order_filled(self, pair: str, trade: Trade, order: Order, current_time: datetime,
**kwargs) -> None:
"""
当订单填充时的回调函数
在开仓时记录基于开单时ATR的止损价格
"""
# 处理开仓订单(包括做多和做空)
if (order.ft_order_side == 'buy' or order.ft_order_side == 'sell') and trade.is_open:
# 获取开仓时的数据
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
if len(dataframe) == 0:
return
# 获取开仓时的ATR值
atr_str = 'atr'
# 找到最接近开仓时间的K线
open_candle = dataframe.iloc[-1] # 使用最新的K线作为开仓时的数据
atr_value = open_candle[atr_str]
if not np.isnan(atr_value) and atr_value > 0:
# 计算止损价格并存储
atr_stop_distance = self.atr_stop_multiplier * atr_value
if trade.is_short:
# 空头止损:入场价 + ATR止损距离
stop_price = trade.open_rate + atr_stop_distance
else:
# 多头止损:入场价 - ATR止损距离
stop_price = trade.open_rate - atr_stop_distance
# 使用trade_id作为key存储止损价格
self.trade_stop_prices[str(trade.id)] = stop_price
#logger.info(f"交易 {trade.id} 开仓,记录止损价格: {stop_price}, ATR: {atr_value}, 开仓价: {trade.open_rate}")
logger.info(f"{current_time} {pair} {trade.open_rate} {stop_price} {atr_value}")
def trade_exit(self, pair: str, trade: Trade, order: Order, current_time: datetime,
**kwargs) -> None:
"""
当交易退出时的回调函数
清理存储的止损价格记录
"""
trade_id = str(trade.id)
if trade_id in self.trade_stop_prices:
del self.trade_stop_prices[trade_id]
logger.info(f"交易 {trade.id} 已关闭,清理止损价格记录")
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])