add fx strentth
This commit is contained in:
+283
-268
@@ -1,9 +1,10 @@
|
||||
# --- Do not remove these libs ---
|
||||
from freqtrade.strategy import IStrategy
|
||||
from typing import Dict, List
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
from functools import reduce
|
||||
from pandas import DataFrame, pandas
|
||||
from pandas import DataFrame
|
||||
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||
import pandas as pd
|
||||
|
||||
# --------------------------------
|
||||
from technical.util import resample_to_interval, resampled_merge
|
||||
@@ -12,329 +13,343 @@ import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from freqtrade.persistence import Trade, Order
|
||||
from typing import Optional
|
||||
import numpy as np
|
||||
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
### Now you can use logger.info('asfd') to log
|
||||
# freqtrade backtesting -c ./user_data/Chan/config/ChanLun_SOL.json --strategy Chan_SOL_2 --strategy-path ./user_data/Chan/strategies --timerange=20240801-20241201
|
||||
|
||||
# freqtrade trade -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL_2 --strategy-path ./user_data/Chan/strategies
|
||||
# freqtrade backtesting -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL_2 --strategy-path ./user_data/Chan/strategies --timerange=20250309-
|
||||
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_SOL.json -t 1m --pairs SOL/USDT:USDT --timerange=20250501-
|
||||
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss --strategy ChanLun_SOL_2 --strategy-path ./user_data/strategies -c ./user_data/ChanLun_SOL.json -e 200 --timerange=20250101-20250215
|
||||
|
||||
# sudo docker compose run --rm chan_btc backtesting -c ./user_data/Chan.json --strategy Chan_SOL_2 --strategy-path ./user_data/strategies --timerange=20250101-
|
||||
# sudo docker compose run --rm chan_btc download-data -c ./user_data/Chan.json --pairs SOL/USDT:USDT -t 1m --timerange 20240101-
|
||||
# sudo docker compose run --rm chan_btc trade -c ./user_data/Chan.json --strategy Chan_SOL_2 --strategy-path ./user_data/strategies
|
||||
|
||||
class ChanLun_SOL_2(IStrategy):
|
||||
class Chan_SOL_2(IStrategy):
|
||||
"""
|
||||
稳定盈利交易策略 - 基于多重技术分析
|
||||
结合趋势跟踪、动量指标和风险管理
|
||||
"""
|
||||
INTERFACE_VERSION: int = 3
|
||||
|
||||
# 优化的ROI设置 - 更快速获利
|
||||
# 优化的ROI设置 - 阶梯式获利了结
|
||||
minimal_roi = {
|
||||
"0": 0.012, # 立即获利1.2%
|
||||
"5": 0.01, # 5分钟后获利1%
|
||||
"15": 0.007, # 15分钟后获利0.7%
|
||||
"30": 0.005 # 30分钟后获利0.5%
|
||||
"0": 0.15, # 15%快速获利
|
||||
"30": 0.08, # 30分钟后8%
|
||||
"60": 0.05, # 1小时后5%
|
||||
"120": 0.03, # 2小时后3%
|
||||
"240": 0.02, # 4小时后2%
|
||||
"480": 0.015, # 8小时后1.5%
|
||||
"960": 0.01 # 16小时后1%
|
||||
}
|
||||
|
||||
can_short = True
|
||||
stoploss = -0.007 # 降低止损为0.7%
|
||||
stoploss = -0.08 # 8%止损
|
||||
|
||||
# 追踪止损设置 - 更积极的追踪止损
|
||||
# 动态追踪止损
|
||||
trailing_stop = True
|
||||
trailing_stop_positive = 0.003 # 0.3%
|
||||
trailing_stop_positive_offset = 0.005 # 0.5%
|
||||
trailing_stop_positive = 0.015 # 1.5%开始追踪
|
||||
trailing_stop_positive_offset = 0.025 # 2.5%偏移
|
||||
trailing_only_offset_is_reached = True
|
||||
|
||||
# 时间周期
|
||||
# 仓位管理
|
||||
position_adjustment_enable = True
|
||||
max_entry_position_adjustment = 2
|
||||
max_dca_multiplier = 3.0
|
||||
|
||||
timeframe = '5m'
|
||||
informative_timeframe = '1h'
|
||||
startup_candle_count = 200
|
||||
startup_candle_count = 200
|
||||
|
||||
# 只做空头策略
|
||||
only_short = True
|
||||
|
||||
def informative_pairs(self):
|
||||
pairs = self.dp.current_whitelist()
|
||||
informative_pairs = [(pair, self.informative_timeframe) for pair in pairs]
|
||||
return informative_pairs
|
||||
# 自定义参数
|
||||
buy_volume_threshold = 1.5
|
||||
sell_volume_threshold = 1.2
|
||||
rsi_oversold = 25
|
||||
rsi_overbought = 75
|
||||
adx_trend_threshold = 25
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
# 获取更高时间周期的数据
|
||||
informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.informative_timeframe)
|
||||
"""
|
||||
添加技术指标 - 多维度分析
|
||||
"""
|
||||
# === 趋势指标 ===
|
||||
# 多周期移动平均线
|
||||
dataframe['ema_8'] = ta.EMA(dataframe, timeperiod=8)
|
||||
dataframe['ema_21'] = ta.EMA(dataframe, timeperiod=21)
|
||||
dataframe['ema_50'] = ta.EMA(dataframe, timeperiod=50)
|
||||
dataframe['ema_200'] = ta.EMA(dataframe, timeperiod=200)
|
||||
|
||||
# === 高时间周期指标 ===
|
||||
# 三均线系统
|
||||
informative['ema50'] = ta.EMA(informative, timeperiod=50)
|
||||
informative['ema100'] = ta.EMA(informative, timeperiod=100)
|
||||
informative['ema200'] = ta.SMA(informative, timeperiod=200) # 使用SMA作为长期趋势
|
||||
# === 动量指标 ===
|
||||
# RSI - 超买超卖
|
||||
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
|
||||
dataframe['rsi_fast'] = ta.RSI(dataframe, timeperiod=9)
|
||||
dataframe['rsi_slow'] = ta.RSI(dataframe, timeperiod=21)
|
||||
|
||||
# 趋势方向
|
||||
informative['uptrend'] = (
|
||||
(informative['ema50'] > informative['ema100']) &
|
||||
(informative['ema100'] > informative['ema200']) &
|
||||
(informative['close'] > informative['ema50'])
|
||||
).astype(int)
|
||||
# MACD - 趋势动量
|
||||
macd = ta.MACD(dataframe, fastperiod=12, slowperiod=26, signalperiod=9)
|
||||
dataframe['macd'] = macd['macd']
|
||||
dataframe['macdsignal'] = macd['macdsignal']
|
||||
dataframe['macdhist'] = macd['macdhist']
|
||||
|
||||
informative['downtrend'] = (
|
||||
(informative['ema50'] < informative['ema100']) &
|
||||
(informative['ema100'] < informative['ema200']) &
|
||||
(informative['close'] < informative['ema50'])
|
||||
).astype(int)
|
||||
# === 波动率指标 ===
|
||||
# ATR - 真实波动幅度
|
||||
dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
|
||||
|
||||
# 强下降趋势
|
||||
informative['strong_downtrend'] = (
|
||||
(informative['ema50'] < informative['ema100']) &
|
||||
(informative['ema100'] < informative['ema200']) &
|
||||
(informative['close'] < informative['ema50']) &
|
||||
(informative['ema50'].shift(3) < informative['ema50']) # 确认EMA50下降
|
||||
).astype(int)
|
||||
|
||||
# 添加高时间周期的ADX指标
|
||||
informative['adx'] = ta.ADX(informative, timeperiod=14)
|
||||
|
||||
# 添加高时间周期的波动率
|
||||
informative['atr'] = ta.ATR(informative, timeperiod=14)
|
||||
informative['atr_percent'] = (informative['atr'] / informative['close']) * 100
|
||||
|
||||
# 高时间周期RSI
|
||||
informative['rsi'] = ta.RSI(informative, timeperiod=14)
|
||||
|
||||
# 将informative数据帧中的列重命名,以便在合并后区分
|
||||
for col in informative.columns:
|
||||
if col not in ['date', 'open', 'high', 'low', 'close', 'volume']:
|
||||
informative[f"{col}_{self.informative_timeframe}"] = informative[col]
|
||||
|
||||
# 删除原始列,只保留重命名后的列和必要的日期、OHLCV列
|
||||
for col in list(informative.columns):
|
||||
if col not in ['date', 'open', 'high', 'low', 'close', 'volume'] and not col.endswith(f"_{self.informative_timeframe}"):
|
||||
del informative[col]
|
||||
|
||||
# 打印列名以便调试
|
||||
logger.info(f"Informative columns after renaming: {informative.columns.tolist()}")
|
||||
|
||||
# 合并数据 - 使用正确的参数
|
||||
dataframe = resampled_merge(dataframe, informative, self.informative_timeframe)
|
||||
|
||||
# 打印合并后的列名以便调试
|
||||
logger.info(f"Dataframe columns after merge: {dataframe.columns.tolist()}")
|
||||
|
||||
# === 主时间周期指标 ===
|
||||
# 布林带
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_middleband'] = bollinger['mid']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
dataframe['bb_width'] = ((bollinger['upper'] - bollinger['lower']) / bollinger['mid'])
|
||||
dataframe['bb_percent'] = (dataframe['close'] - dataframe['bb_lowerband']) / (dataframe['bb_upperband'] - dataframe['bb_lowerband'])
|
||||
dataframe['bb_width'] = (dataframe['bb_upperband'] - dataframe['bb_lowerband']) / dataframe['bb_middleband']
|
||||
|
||||
# 动量指标
|
||||
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
|
||||
dataframe['mfi'] = ta.MFI(dataframe, timeperiod=14)
|
||||
|
||||
# MACD
|
||||
macd = ta.MACD(dataframe)
|
||||
dataframe['macd'] = macd['macd']
|
||||
dataframe['macdsignal'] = macd['macdsignal']
|
||||
dataframe['macdhist'] = macd['macdhist']
|
||||
|
||||
# 均线
|
||||
dataframe['ema9'] = ta.EMA(dataframe, timeperiod=9)
|
||||
dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21)
|
||||
dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
|
||||
dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)
|
||||
|
||||
# 成交量
|
||||
dataframe['volume_mean'] = dataframe['volume'].rolling(window=20).mean()
|
||||
dataframe['volume_ratio'] = dataframe['volume'] / dataframe['volume_mean']
|
||||
|
||||
# 波动率
|
||||
dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
|
||||
|
||||
# ADX - 趋势强度指标
|
||||
# === 趋势强度指标 ===
|
||||
# ADX - 趋势强度
|
||||
dataframe['adx'] = ta.ADX(dataframe, timeperiod=14)
|
||||
dataframe['plus_di'] = ta.PLUS_DI(dataframe, timeperiod=14)
|
||||
dataframe['minus_di'] = ta.MINUS_DI(dataframe, timeperiod=14)
|
||||
|
||||
# 价格突破
|
||||
dataframe['upper_break'] = (
|
||||
(dataframe['close'] > dataframe['bb_upperband']) &
|
||||
(dataframe['close'].shift() <= dataframe['bb_upperband'].shift())
|
||||
).astype(int)
|
||||
# === 成交量指标 ===
|
||||
# 成交量移动平均
|
||||
dataframe['volume_sma_20'] = dataframe['volume'].rolling(window=20).mean()
|
||||
dataframe['volume_ratio'] = dataframe['volume'] / dataframe['volume_sma_20']
|
||||
|
||||
dataframe['lower_break'] = (
|
||||
(dataframe['close'] < dataframe['bb_lowerband']) &
|
||||
(dataframe['close'].shift() >= dataframe['bb_lowerband'].shift())
|
||||
).astype(int)
|
||||
# OBV - 能量潮
|
||||
dataframe['obv'] = ta.OBV(dataframe)
|
||||
dataframe['obv_ema'] = ta.EMA(dataframe['obv'], timeperiod=20)
|
||||
|
||||
# 均线交叉
|
||||
dataframe['ema_cross_up'] = (
|
||||
(dataframe['ema9'] > dataframe['ema21']) &
|
||||
(dataframe['ema9'].shift() <= dataframe['ema21'].shift())
|
||||
).astype(int)
|
||||
# === 价格行为指标 ===
|
||||
# 价格变化率
|
||||
dataframe['price_change'] = dataframe['close'].pct_change()
|
||||
dataframe['price_change_5'] = dataframe['close'].pct_change(periods=5)
|
||||
|
||||
dataframe['ema_cross_down'] = (
|
||||
(dataframe['ema9'] < dataframe['ema21']) &
|
||||
(dataframe['ema9'].shift() >= dataframe['ema21'].shift())
|
||||
).astype(int)
|
||||
# 高低点分析
|
||||
dataframe['high_20'] = dataframe['high'].rolling(window=20).max()
|
||||
dataframe['low_20'] = dataframe['low'].rolling(window=20).min()
|
||||
|
||||
# 超买超卖区域
|
||||
dataframe['rsi_oversold'] = (dataframe['rsi'] < 30).astype(int)
|
||||
dataframe['rsi_overbought'] = (dataframe['rsi'] > 70).astype(int)
|
||||
# === 自定义复合指标 ===
|
||||
# 趋势确认信号
|
||||
dataframe['trend_up'] = (
|
||||
(dataframe['ema_8'] > dataframe['ema_21']) &
|
||||
(dataframe['ema_21'] > dataframe['ema_50']) &
|
||||
(dataframe['close'] > dataframe['ema_8'])
|
||||
)
|
||||
|
||||
# 价格与均线的关系
|
||||
dataframe['price_above_ema50'] = (dataframe['close'] > dataframe['ema50']).astype(int)
|
||||
dataframe['price_below_ema50'] = (dataframe['close'] < dataframe['ema50']).astype(int)
|
||||
dataframe['trend_down'] = (
|
||||
(dataframe['ema_8'] < dataframe['ema_21']) &
|
||||
(dataframe['ema_21'] < dataframe['ema_50']) &
|
||||
(dataframe['close'] < dataframe['ema_8'])
|
||||
)
|
||||
|
||||
# 趋势强度
|
||||
dataframe['strong_trend'] = (dataframe['adx'] > 25).astype(int)
|
||||
# 动量强度评分
|
||||
dataframe['momentum_score'] = (
|
||||
((dataframe['rsi'] > 50).astype(int) * 1) +
|
||||
((dataframe['macd'] > dataframe['macdsignal']).astype(int) * 1) +
|
||||
((dataframe['adx'] > self.adx_trend_threshold).astype(int) * 1) +
|
||||
((dataframe['volume_ratio'] > 1.0).astype(int) * 1)
|
||||
)
|
||||
|
||||
# 添加蜡烛图形态识别
|
||||
dataframe['doji'] = ta.CDLDOJI(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close'])
|
||||
dataframe['engulfing'] = ta.CDLENGULFING(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close'])
|
||||
dataframe['hammer'] = ta.CDLHAMMER(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close'])
|
||||
dataframe['shooting_star'] = ta.CDLSHOOTINGSTAR(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close'])
|
||||
|
||||
# 价格动量
|
||||
dataframe['momentum'] = dataframe['close'] - dataframe['close'].shift(5)
|
||||
# 波动率适应性指标
|
||||
dataframe['volatility_high'] = dataframe['atr'] > dataframe['atr'].rolling(window=20).mean() * 1.5
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
# 检查列名是否存在
|
||||
downtrend_col = 'resample_60_downtrend_1h'
|
||||
strong_downtrend_col = 'resample_60_strong_downtrend_1h'
|
||||
adx_col = 'resample_60_adx_1h'
|
||||
rsi_col = 'resample_60_rsi_1h'
|
||||
"""
|
||||
入场信号 - 多条件确认系统
|
||||
"""
|
||||
# === 多头入场条件 ===
|
||||
|
||||
# 如果列名不存在,使用替代方案
|
||||
for col, default_value in [
|
||||
(downtrend_col, 0),
|
||||
(strong_downtrend_col, 0),
|
||||
(adx_col, 25),
|
||||
(rsi_col, 50)
|
||||
]:
|
||||
if col not in dataframe.columns:
|
||||
logger.warning(f"Column {col} not found in dataframe. Creating with default value {default_value}.")
|
||||
dataframe[col] = default_value
|
||||
# 条件1: 强势突破入场
|
||||
dataframe.loc[
|
||||
(
|
||||
# 趋势确认
|
||||
(dataframe['trend_up']) &
|
||||
(dataframe['close'] > dataframe['ema_21']) &
|
||||
|
||||
# 动量确认
|
||||
(dataframe['rsi'] > 45) & (dataframe['rsi'] < 75) &
|
||||
(dataframe['macd'] > dataframe['macdsignal']) &
|
||||
(dataframe['macdhist'] > dataframe['macdhist'].shift(1)) &
|
||||
|
||||
# 成交量确认
|
||||
(dataframe['volume_ratio'] > self.buy_volume_threshold) &
|
||||
(dataframe['obv'] > dataframe['obv_ema']) &
|
||||
|
||||
# 价格行为确认
|
||||
(dataframe['close'] > dataframe['bb_middleband']) &
|
||||
(dataframe['bb_percent'] > 0.2) & (dataframe['bb_percent'] < 0.8) &
|
||||
|
||||
# 趋势强度确认
|
||||
(dataframe['adx'] > self.adx_trend_threshold) &
|
||||
(dataframe['plus_di'] > dataframe['minus_di'])
|
||||
),
|
||||
['enter_long', 'enter_tag']] = (1, 'breakout_long')
|
||||
|
||||
# 禁用多头入场
|
||||
dataframe['enter_long'] = 0
|
||||
# 条件2: 超卖反弹入场
|
||||
dataframe.loc[
|
||||
(
|
||||
# 超卖反弹
|
||||
(dataframe['rsi'] < self.rsi_oversold + 10) &
|
||||
(dataframe['rsi'] > dataframe['rsi'].shift(1)) &
|
||||
(dataframe['bb_percent'] < 0.2) &
|
||||
|
||||
# 趋势不能太差
|
||||
(dataframe['ema_8'] >= dataframe['ema_50']) &
|
||||
(dataframe['close'] > dataframe['low_20'] * 1.02) &
|
||||
|
||||
# 成交量支持
|
||||
(dataframe['volume_ratio'] > 1.2) &
|
||||
|
||||
# MACD底背离迹象
|
||||
(dataframe['macdhist'] > dataframe['macdhist'].shift(1)) &
|
||||
|
||||
# 不与第一个条件重复
|
||||
(~dataframe['enter_long'].astype(bool))
|
||||
),
|
||||
['enter_long', 'enter_tag']] = (1, 'oversold_long')
|
||||
|
||||
# 空头入场条件 - 专注于空头策略
|
||||
short_conditions = (
|
||||
# 高时间周期处于下降趋势
|
||||
(dataframe[downtrend_col] > 0) &
|
||||
|
||||
# 趋势强度确认
|
||||
(dataframe[adx_col] > 25) &
|
||||
|
||||
# 条件1: 价格突破上轨后回落 + 成交量确认
|
||||
(
|
||||
(dataframe['upper_break'].rolling(window=5).sum() > 0) & # 最近5根K线内有突破上轨
|
||||
(dataframe['close'] < dataframe['close'].shift(2)) & # 价格开始下跌
|
||||
(dataframe['close'] < dataframe['ema9']) & # 价格在短期均线下方
|
||||
(dataframe['volume_ratio'] > 1.3) & # 成交量放大
|
||||
(dataframe['rsi'] < 70) & # RSI不在极度超买区
|
||||
(dataframe['rsi'] > 40) & # RSI不在超卖区
|
||||
(dataframe[rsi_col] < 60) # 高时间周期RSI不过高
|
||||
) |
|
||||
|
||||
# 条件2: 均线死叉 + RSI超买回落 + 趋势确认
|
||||
(
|
||||
(dataframe['ema_cross_down'] > 0) & # 均线死叉
|
||||
(dataframe['rsi'] > 55) & # RSI相对较高
|
||||
(dataframe['rsi'] < dataframe['rsi'].shift(3)) & # RSI下降
|
||||
(dataframe['volume_ratio'] > 1.2) & # 成交量放大
|
||||
(dataframe['adx'] > 20) & # ADX显示有一定趋势强度
|
||||
((dataframe['shooting_star'] > 0) | (dataframe['engulfing'] < 0)) # 流星线或看跌吞没形态
|
||||
) |
|
||||
|
||||
# 条件3: 价格在高点回落 + 强趋势
|
||||
(
|
||||
(dataframe['close'] < dataframe['high'].shift()) &
|
||||
(dataframe['high'].shift() > dataframe['high'].shift(2)) &
|
||||
(dataframe['close'] < dataframe['ema21']) &
|
||||
(dataframe['adx'] > 30) &
|
||||
(dataframe['rsi'] < dataframe['rsi'].shift()) &
|
||||
(dataframe['rsi'].shift() > 65) &
|
||||
(dataframe['volume_ratio'] > 1.0)
|
||||
) |
|
||||
|
||||
# 条件4: 强下降趋势确认
|
||||
(
|
||||
(dataframe[strong_downtrend_col] > 0) &
|
||||
(dataframe['close'] < dataframe['ema21']) &
|
||||
(dataframe['close'] < dataframe['close'].shift(3)) &
|
||||
(dataframe['momentum'] < 0) &
|
||||
(dataframe['volume_ratio'] > 1.1) &
|
||||
(dataframe['adx'] > 25)
|
||||
)
|
||||
)
|
||||
# === 空头入场条件 ===
|
||||
|
||||
dataframe.loc[short_conditions, 'enter_short'] = 1
|
||||
dataframe.loc[short_conditions, 'enter_tag'] = 'chan_sol_short'
|
||||
# 条件1: 强势下跌入场
|
||||
dataframe.loc[
|
||||
(
|
||||
# 趋势确认
|
||||
(dataframe['trend_down']) &
|
||||
(dataframe['close'] < dataframe['ema_21']) &
|
||||
|
||||
# 动量确认
|
||||
(dataframe['rsi'] < 55) & (dataframe['rsi'] > 25) &
|
||||
(dataframe['macd'] < dataframe['macdsignal']) &
|
||||
(dataframe['macdhist'] < dataframe['macdhist'].shift(1)) &
|
||||
|
||||
# 成交量确认
|
||||
(dataframe['volume_ratio'] > self.sell_volume_threshold) &
|
||||
(dataframe['obv'] < dataframe['obv_ema']) &
|
||||
|
||||
# 价格行为确认
|
||||
(dataframe['close'] < dataframe['bb_middleband']) &
|
||||
(dataframe['bb_percent'] > 0.2) & (dataframe['bb_percent'] < 0.8) &
|
||||
|
||||
# 趋势强度确认
|
||||
(dataframe['adx'] > self.adx_trend_threshold) &
|
||||
(dataframe['minus_di'] > dataframe['plus_di'])
|
||||
),
|
||||
['enter_short', 'enter_tag']] = (1, 'breakdown_short')
|
||||
|
||||
# 条件2: 超买回调入场
|
||||
dataframe.loc[
|
||||
(
|
||||
# 超买回调
|
||||
(dataframe['rsi'] > self.rsi_overbought - 10) &
|
||||
(dataframe['rsi'] < dataframe['rsi'].shift(1)) &
|
||||
(dataframe['bb_percent'] > 0.8) &
|
||||
|
||||
# 趋势不能太好
|
||||
(dataframe['ema_8'] <= dataframe['ema_50']) &
|
||||
(dataframe['close'] < dataframe['high_20'] * 0.98) &
|
||||
|
||||
# 成交量支持
|
||||
(dataframe['volume_ratio'] > 1.2) &
|
||||
|
||||
# MACD顶背离迹象
|
||||
(dataframe['macdhist'] < dataframe['macdhist'].shift(1)) &
|
||||
|
||||
# 不与第一个条件重复
|
||||
(~dataframe['enter_short'].astype(bool))
|
||||
),
|
||||
['enter_short', 'enter_tag']] = (1, 'overbought_short')
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
# 禁用多头出场
|
||||
dataframe['exit_long'] = 0
|
||||
"""
|
||||
出场信号 - 及时止盈止损
|
||||
"""
|
||||
# === 多头出场条件 ===
|
||||
|
||||
# 空头出场条件 - 更精确的出场
|
||||
short_exit_conditions = (
|
||||
# 条件1: 趋势反转信号
|
||||
# 条件1: 趋势转弱
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['ema_cross_up'] > 0) & # 均线金叉
|
||||
(dataframe['volume_ratio'] > 1.0) # 成交量确认
|
||||
) |
|
||||
|
||||
# 条件2: 价格突破中期均线
|
||||
(
|
||||
(dataframe['close'] > dataframe['ema21']) &
|
||||
(dataframe['close'].shift() < dataframe['ema21'].shift()) & # 确认是刚刚突破
|
||||
(dataframe['volume_ratio'] > 1.2) # 成交量确认
|
||||
) |
|
||||
|
||||
# 条件3: 超卖信号
|
||||
(
|
||||
(dataframe['rsi'] < 30) & # RSI超卖
|
||||
(dataframe['close'] < dataframe['bb_lowerband']) # 价格突破下轨
|
||||
) |
|
||||
|
||||
# 条件4: 动量减弱
|
||||
(
|
||||
(dataframe['rsi'] < 35) &
|
||||
(dataframe['rsi'] > dataframe['rsi'].shift()) &
|
||||
(dataframe['rsi'].shift() > dataframe['rsi'].shift(2)) & # RSI连续两根K线上升
|
||||
(dataframe['momentum'] > 0) # 价格动量转为正
|
||||
) |
|
||||
|
||||
# 条件5: 锤子线形态 (潜在反转信号)
|
||||
(
|
||||
(dataframe['hammer'] > 0) &
|
||||
(dataframe['volume_ratio'] > 1.3)
|
||||
)
|
||||
)
|
||||
(
|
||||
(dataframe['rsi'] > self.rsi_overbought) |
|
||||
(dataframe['macd'] < dataframe['macdsignal']) |
|
||||
(dataframe['close'] < dataframe['ema_8']) |
|
||||
(dataframe['bb_percent'] > 0.95) |
|
||||
(dataframe['adx'] < 20)
|
||||
) &
|
||||
(dataframe['volume_ratio'] > 1.0)
|
||||
),
|
||||
['exit_long', 'exit_tag']] = (1, 'trend_weak_long')
|
||||
|
||||
dataframe.loc[short_exit_conditions, 'exit_short'] = 1
|
||||
dataframe.loc[short_exit_conditions, 'exit_tag'] = 'chan_sol_short_exit'
|
||||
# === 空头出场条件 ===
|
||||
|
||||
# 条件1: 趋势转强
|
||||
dataframe.loc[
|
||||
(
|
||||
(
|
||||
(dataframe['rsi'] < self.rsi_oversold) |
|
||||
(dataframe['macd'] > dataframe['macdsignal']) |
|
||||
(dataframe['close'] > dataframe['ema_8']) |
|
||||
(dataframe['bb_percent'] < 0.05) |
|
||||
(dataframe['adx'] < 20)
|
||||
) &
|
||||
(dataframe['volume_ratio'] > 1.0)
|
||||
),
|
||||
['exit_short', 'exit_tag']] = (1, 'trend_strong_short')
|
||||
|
||||
return dataframe
|
||||
|
||||
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||
time_in_force: str, current_time: datetime, entry_tag: Optional[str],
|
||||
side: str, **kwargs) -> bool:
|
||||
|
||||
def custom_stoploss(self, pair: str, trade: Trade, current_time: datetime,
|
||||
current_rate: float, current_profit: float, **kwargs) -> float:
|
||||
"""
|
||||
在进入交易前进行额外的确认
|
||||
动态止损策略
|
||||
"""
|
||||
# 只做空头交易
|
||||
if side == "sell" and entry_tag == "chan_sol_short":
|
||||
return True
|
||||
return False
|
||||
|
||||
# 基础止损
|
||||
if current_profit < -0.05: # 如果亏损超过5%,严格止损
|
||||
return -0.08
|
||||
|
||||
# 盈利后的动态止损
|
||||
if current_profit > 0.02: # 盈利超过2%后,调整止损至成本价附近
|
||||
return 0.005
|
||||
elif current_profit > 0.05: # 盈利超过5%后,保证1%利润
|
||||
return -current_profit + 0.01
|
||||
elif current_profit > 0.10: # 盈利超过10%后,保证5%利润
|
||||
return -current_profit + 0.05
|
||||
|
||||
return self.stoploss
|
||||
|
||||
def adjust_trade_position(self, trade: Trade, current_time: datetime,
|
||||
current_rate: float, current_profit: float,
|
||||
min_stake: float, max_stake: float,
|
||||
current_entry_rate: float, current_exit_rate: float,
|
||||
current_entry_profit: float, current_exit_profit: float,
|
||||
**kwargs) -> Optional[float]:
|
||||
"""
|
||||
仓位调整策略 - 金字塔加仓
|
||||
"""
|
||||
# 如果亏损超过3%,不加仓
|
||||
if current_profit < -0.03:
|
||||
return None
|
||||
|
||||
# 如果盈利超过2%且趋势持续,可以加仓
|
||||
if current_profit > 0.02 and len(trade.select_filled_orders(trade.entry_side)) < self.max_entry_position_adjustment:
|
||||
# 获取当前数据进行趋势确认
|
||||
try:
|
||||
# 简单的趋势确认逻辑
|
||||
if trade.is_short:
|
||||
return max_stake * 0.5 # 空头加仓
|
||||
else:
|
||||
return max_stake * 0.5 # 多头加仓
|
||||
except:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
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 1.0
|
||||
|
||||
def get_ticker_indicator(self):
|
||||
return int(self.timeframe[:-1])
|
||||
"""
|
||||
杠杆设置 - 保守策略
|
||||
"""
|
||||
# 根据入场类型调整杠杆
|
||||
if entry_tag and 'breakout' in entry_tag:
|
||||
return min(2.0, max_leverage) # 突破信号使用较高杠杆
|
||||
elif entry_tag and ('oversold' in entry_tag or 'overbought' in entry_tag):
|
||||
return min(1.5, max_leverage) # 超买超卖信号使用中等杠杆
|
||||
else:
|
||||
return 1.0 # 默认无杠杆
|
||||
Reference in New Issue
Block a user