新的策略,先开单,明天继续添加条件
This commit is contained in:
+9
-9
@@ -61,7 +61,7 @@ class ChanKLC():
|
||||
#print(self.start_time, klc_fx_type, self.get_feature_data()['klu_macd'], self.get_feature_data()['klu_macdhist'], self.get_feature_data()['klu_rsi'])
|
||||
self.klc_fx_type = klc_fx_type
|
||||
#self.cal_fx()
|
||||
#self.cal_bb_out()
|
||||
self.cal_bb_out()
|
||||
def add_klu(self, klu):
|
||||
self.klus.append(klu)
|
||||
def set_end_klu(self, klu):
|
||||
@@ -100,15 +100,16 @@ class ChanKLC():
|
||||
self.klc_fx_type = Chan_KLC_FX.BOTTOM8
|
||||
def cal_bb_out(self):
|
||||
for klu in self.klus:
|
||||
if self.high >= klu.bbup302 and klu.bbup302 > 0 and (self.klc_fx_type == Chan_KLC_FX.TOP1 or self.klc_fx_type == Chan_KLC_FX.TOP2):
|
||||
#print(self.end_time, self.high, klu.bbup302, self.klc_fx_type)
|
||||
if self.high >= klu.bbup30 and klu.bbup30 > 0 and self.next and (self.next.macd - self.macd) < 0:
|
||||
if self.klc_fx_type == Chan_KLC_FX.TOP1 or self.klc_fx_type == Chan_KLC_FX.TOP2:
|
||||
#print(self.start_time, self.klc_fx_type, klu.high, klu.bb52upper, self.macd, self.next.macd, klu.time)
|
||||
if self.high >= klu.bb52upper and klu.bb52upper > 0 and self.next and self.high > self.next.high:
|
||||
self.klc_fx_type = Chan_KLC_FX.TOP4
|
||||
#self.bb_out = True
|
||||
if self.low <= klu.bblow302 and klu.bblow302 > 0 and (self.klc_fx_type == Chan_KLC_FX.BOTTOM1 or self.klc_fx_type == Chan_KLC_FX.BOTTOM2):
|
||||
if self.low <= klu.bblow30 and klu.bblow30 > 0 and self.next and (self.macd - self.next.macd) < 0:
|
||||
print(self.end_time, self.klc_fx_type)
|
||||
if self.klc_fx_type == Chan_KLC_FX.BOTTOM1 or self.klc_fx_type == Chan_KLC_FX.BOTTOM2:
|
||||
#print(self.start_time, self.klc_fx_type, klu.low, klu.bb52lower, self.macd, self.next.macd, klu.time)
|
||||
if self.low <= klu.bb52lower and klu.bb52lower > 0 and self.next and self.low < self.next.low:
|
||||
self.klc_fx_type = Chan_KLC_FX.BOTTOM4
|
||||
#self.bb_out = True
|
||||
print(self.end_time, self.klc_fx_type)
|
||||
def cal_indicators(self):
|
||||
for index in range(1, len(self.klus)):
|
||||
self.volume += self.klus[index].volume
|
||||
@@ -126,7 +127,6 @@ class ChanKLC():
|
||||
if len(self.klus) > 0:
|
||||
self.macd = self.klus[-1].macd
|
||||
self.signal = self.klus[-1].signal
|
||||
|
||||
self.body = abs(self.close - self.open)
|
||||
self.upper_shadow = self.high - max(self.close, self.open)
|
||||
self.lower_shadow = min(self.close, self.open) - self.low
|
||||
|
||||
+5
-38
@@ -15,23 +15,10 @@ class ChanKLU:
|
||||
self.signal = 0
|
||||
self.macdhist = 0
|
||||
self.klc = None
|
||||
self.ma5 = 0
|
||||
self.ma10 = 0
|
||||
self.ma30 = 0
|
||||
self.ma50 = 0
|
||||
self.ma200 = 0
|
||||
self.ma250 = 0
|
||||
self.rsi = 0
|
||||
self.volume_ratio = 0
|
||||
self.bbp120 = 0
|
||||
self.bbp365 = 0
|
||||
self.bb120 = 0
|
||||
self.bb365 = 0
|
||||
self.bbp302 = 0
|
||||
self.bbup302 = 0
|
||||
self.bblow302 = 0
|
||||
self.bbup30 = 0
|
||||
self.bblow30 = 0
|
||||
self.bb52upper = 0
|
||||
self.bb52lower = 0
|
||||
# === 新增:K线类型 ===
|
||||
self.kline_type = None # K线类型:大阳线、大阴线、小阳线、小阴线
|
||||
|
||||
@@ -107,33 +94,13 @@ class ChanKLU:
|
||||
self.macd = float(item['macd']) if 'macd' in item and item['macd'] else 0
|
||||
self.signal = float(item['macdsignal']) if 'macdsignal' in item and item['macdsignal'] else 0
|
||||
self.macdhist = float(item['macdhist']) if 'macdhist' in item and item['macdhist'] else 0
|
||||
self.ma5 = float(item['ma5']) if 'ma5' in item and item['ma5'] else 0
|
||||
self.ma10 = float(item['ma10']) if 'ma10' in item and item['ma10'] else 0
|
||||
self.ma30 = float(item['ma30']) if 'ma30' in item and item['ma30'] else 0
|
||||
self.ema52 = float(item['ema52']) if 'ema52' in item and item['ema52'] else 0
|
||||
self.ema24 = float(item['ema24']) if 'ema24' in item and item['ema24'] else 0
|
||||
|
||||
# 安全检查 ma250、ma50 和 ma200
|
||||
self.ma250 = float(item['ma250']) if 'ma250' in item and item['ma250'] else 0
|
||||
self.ma50 = float(item['ma50']) if 'ma50' in item and item['ma50'] else 0
|
||||
self.ma200 = float(item['ma200']) if 'ma200' in item and item['ma200'] else 0
|
||||
|
||||
self.rsi = float(item['rsi']) if 'rsi' in item and item['rsi'] else 0
|
||||
self.volume_ratio = float(item['volume_ratio']) if 'volume_ratio' in item and item['volume_ratio'] else 0
|
||||
self.bbp120 = float(item['bbp120']) if 'bbp120' in item and item['bbp120'] else 0
|
||||
self.bbp365 = float(item['bbp365']) if 'bbp365' in item and item['bbp365'] else 0
|
||||
self.bb120 = float(item['bb120']) if 'bb120' in item and item['bb120'] else 0
|
||||
self.bb365 = float(item['bb365']) if 'bb365' in item and item['bb365'] else 0
|
||||
self.bbp30 = float(item['bbp30']) if 'bbp30' in item and item['bbp30'] else 0
|
||||
self.bbup30 = float(item['bbup30']) if 'bbup30' in item and item['bbup30'] else 0
|
||||
self.bblow30 = float(item['bblow30']) if 'bblow30' in item and item['bblow30'] else 0
|
||||
self.bbp302 = float(item['bbp302']) if 'bbp302' in item and item['bbp302'] else 0
|
||||
self.bbup302 = float(item['bbup302']) if 'bbup302' in item and item['bbup302'] else 0
|
||||
self.bblow302 = float(item['bblow302']) if 'bblow302' in item and item['bblow302'] else 0
|
||||
self.bbup120 = float(item['bbup120']) if 'bbup120' in item and item['bbup120'] else 0
|
||||
self.bblow120 = float(item['bblow120']) if 'bblow120' in item and item['bblow120'] else 0
|
||||
self.bbup365 = float(item['bbup365']) if 'bbup365' in item and item['bbup365'] else 0
|
||||
self.bblow365 = float(item['bblow365']) if 'bblow365' in item and item['bblow365'] else 0
|
||||
self.bb52upper = float(item['bb52upper']) if 'bb52upper' in item and item['bb52upper'] else 0
|
||||
self.bb52lower = float(item['bb52lower']) if 'bb52lower' in item and item['bb52lower'] else 0
|
||||
|
||||
def cal_macd_state(self):
|
||||
# 按定义精简实现:优先级 CROSS0 > 位置(HIGH/HE/RETURN_ZERO) > NEAR0 > UNKNOWN
|
||||
# 首条或缺前一根
|
||||
|
||||
+204
-5
@@ -75,6 +75,26 @@ class ChanLun():
|
||||
if len(self.tf_df_dict) > 0:
|
||||
return {key: self.tf_df_dict[key].get_ema24() for key in self.ema_symbols}
|
||||
return None
|
||||
def get_klu_state(self, dataframe):
|
||||
klc_list = self.get_klc_list(dataframe)
|
||||
bi_list = self.cal_bi_list(klc_list)
|
||||
klu_state_list = []
|
||||
klc_index = 0
|
||||
for index in range(0, len(dataframe)):
|
||||
if klc_index == len(klc_list):
|
||||
klc_index = len(klc_list) - 1
|
||||
klc = klc_list[klc_index]
|
||||
if klc.end_klu and klc.end_klu.idx == index:
|
||||
if klc.klc_fx_type == Chan_KLC_FX.TOP4:
|
||||
klu_state_list.append("10")
|
||||
elif klc.klc_fx_type == Chan_KLC_FX.BOTTOM4:
|
||||
klu_state_list.append("-10")
|
||||
else:
|
||||
klu_state_list.append("00")
|
||||
klc_index += 1
|
||||
else:
|
||||
klu_state_list.append("00")
|
||||
return klu_state_list
|
||||
def get_current_klc_dict(self):
|
||||
if len(self.tf_df_dict) > 0:
|
||||
return {key: self.tf_df_dict[key].get_current_klc() for key in self.ema_symbols}
|
||||
@@ -94,7 +114,7 @@ class ChanLun():
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "BOTTOM")
|
||||
return Chan_FX_TYPE.BOTTOM
|
||||
return Chan_FX_TYPE.UNKNOWN
|
||||
def add_indicators(self, df):
|
||||
def add_indicators1(self, df):
|
||||
fast = 12
|
||||
slow = 26
|
||||
period = 9
|
||||
@@ -474,6 +494,9 @@ class ChanLun():
|
||||
if not klc_list:
|
||||
return klc_list
|
||||
last_trend = Chan_PRICE_TREND.UNKNOWN
|
||||
# 趋势延续性:参考近 N 根已完成的KLC
|
||||
lookback_n = 5
|
||||
prev_klcs = []
|
||||
for klc in klc_list:
|
||||
price = getattr(klc, 'close', None)
|
||||
ema24 = getattr(klc, 'ema24', None)
|
||||
@@ -514,6 +537,76 @@ class ChanLun():
|
||||
spread_now = ema24 - ema52
|
||||
spread_pre = pre_ema24 - pre_ema52
|
||||
score += 1 if spread_now >= spread_pre else -1
|
||||
# 3.1) MACD柱体动量趋势:考虑 macdhist 的斜率与过零
|
||||
pre_hist = getattr(pre, 'macdhist', None)
|
||||
if pre_hist is not None and hist is not None:
|
||||
# 柱体斜率:上升加分,下降减分
|
||||
if hist > pre_hist:
|
||||
score += 1
|
||||
elif hist < pre_hist:
|
||||
score -= 1
|
||||
# 过零加权:负转正更偏多,正转负更偏空
|
||||
if pre_hist < 0 and hist > 0:
|
||||
score += 1
|
||||
elif pre_hist > 0 and hist < 0:
|
||||
score -= 1
|
||||
# 3.2) EMA52 突破/跌破加权
|
||||
if ema52_valid and price_valid and pre_close is not None and pre_ema52 not in (None, 0):
|
||||
# 看多突破:从均线下方上破且动量配合
|
||||
if pre_close <= pre_ema52 and price > ema52 and (hist is None or pre_hist is None or hist >= pre_hist):
|
||||
score += 1
|
||||
# 看空跌破:从均线上方下破且动量配合
|
||||
if pre_close >= pre_ema52 and price < ema52 and (hist is None or pre_hist is None or hist <= pre_hist):
|
||||
score -= 1
|
||||
# 3.3) EMA52 支撑/阻力触碰(非强穿越)
|
||||
if ema52_valid and price_valid:
|
||||
low_v = getattr(klc, 'low', None)
|
||||
high_v = getattr(klc, 'high', None)
|
||||
if low_v is not None and high_v is not None and ema52 not in (None, 0):
|
||||
# 触碰容差(相对EMA52的0.15%)
|
||||
touch_tol = 0.0015
|
||||
# 作为支撑:收盘在上,最低靠近EMA52
|
||||
near_support_touch = (price > ema52) and (abs(low_v - ema52) / abs(ema52) <= touch_tol)
|
||||
# 作为阻力:收盘在下,最高靠近EMA52
|
||||
near_resistance_touch = (price < ema52) and (abs(high_v - ema52) / abs(ema52) <= touch_tol)
|
||||
if near_support_touch:
|
||||
# 若动量不弱,则更偏多
|
||||
score += 1 if (hist is None or pre_hist is None or hist >= pre_hist) else 0
|
||||
if near_resistance_touch:
|
||||
# 若动量不强,则更偏空
|
||||
score -= 1 if (hist is None or pre_hist is None or hist <= pre_hist) else 0
|
||||
# 3.4) 多次对 EMA52 的“拒绝”配合 MACD 逆向:易形成压/支并反向
|
||||
# 统计近窗口内的上/下拒绝次数:
|
||||
# - 上拒绝:价格位于 EMA52 下方,最高触及/越过 EMA52 但收盘仍在下方
|
||||
# - 下拒绝:价格位于 EMA52 上方,最低触及/跌破 EMA52 但收盘仍在上方
|
||||
recent_up_rejects = 0
|
||||
recent_down_rejects = 0
|
||||
if ema52_valid:
|
||||
window_rej = prev_klcs[-lookback_n:] if len(prev_klcs) > 0 else []
|
||||
rej_tol = 0.0015
|
||||
for wk in window_rej:
|
||||
wk_close = getattr(wk, 'close', None)
|
||||
wk_ema52 = getattr(wk, 'ema52', None)
|
||||
wk_high = getattr(wk, 'high', None)
|
||||
wk_low = getattr(wk, 'low', None)
|
||||
if wk_close is None or wk_ema52 in (None, 0):
|
||||
continue
|
||||
# 上拒绝(阻力):下方多次试图上破但未站上
|
||||
if wk_close < wk_ema52 and wk_high is not None:
|
||||
if wk_high >= wk_ema52 or abs(wk_high - wk_ema52) / abs(wk_ema52) <= rej_tol:
|
||||
recent_up_rejects += 1
|
||||
# 下拒绝(支撑):上方多次试图下破但未跌破
|
||||
if wk_close > wk_ema52 and wk_low is not None:
|
||||
if wk_low <= wk_ema52 or abs(wk_low - wk_ema52) / abs(wk_ema52) <= rej_tol:
|
||||
recent_down_rejects += 1
|
||||
# 定义 MACD 的方向偏好
|
||||
macd_bias_up = (macd >= signal) and (hist is None or pre_hist is None or hist >= pre_hist)
|
||||
macd_bias_down = (macd <= signal) and (hist is None or pre_hist is None or hist <= pre_hist)
|
||||
# 若多次上拒绝且 MACD 偏空,则更偏向下行;若多次下拒绝且 MACD 偏多,则更偏向上行
|
||||
if recent_up_rejects >= 2 and macd_bias_down:
|
||||
score -= 2
|
||||
if recent_down_rejects >= 2 and macd_bias_up:
|
||||
score += 2
|
||||
# 4) RSI 辅助
|
||||
if rsi is not None:
|
||||
if rsi >= 55:
|
||||
@@ -551,17 +644,121 @@ class ChanLun():
|
||||
near_macd = abs(macd - signal) <= (abs(price) * 0.00005 if price_valid else 0)
|
||||
near_flat = near_ema52 and near_macd
|
||||
# 7) 动态阈值 + 趋势记忆(更强粘滞:趋势中容忍小幅反分)
|
||||
# 引入过去 N 根KLC 的趋势延续性来动态调整翻转阈值,并结合 EMA52 支撑/阻力触碰强化门槛
|
||||
force_flip_down = False
|
||||
force_flip_up = False
|
||||
if near_flat:
|
||||
trend = Chan_PRICE_TREND.FLAT
|
||||
else:
|
||||
if last_trend == Chan_PRICE_TREND.UP:
|
||||
# 仅当出现明显反向才翻转,否则维持UP
|
||||
if score <= -2:
|
||||
# 计算过去窗口的趋势一致性
|
||||
window = prev_klcs[-lookback_n:] if len(prev_klcs) > 0 else []
|
||||
persist_up = 0
|
||||
persist_down = 0
|
||||
for wk in window:
|
||||
if getattr(wk, 'trend', None) == Chan_PRICE_TREND.UP:
|
||||
persist_up += 1
|
||||
elif getattr(wk, 'trend', None) == Chan_PRICE_TREND.DOWN:
|
||||
persist_down += 1
|
||||
persist_ratio_up = (persist_up / len(window)) if len(window) > 0 else 0
|
||||
persist_ratio_down = (persist_down / len(window)) if len(window) > 0 else 0
|
||||
# 基准阈值
|
||||
down_flip_threshold = -2
|
||||
up_flip_threshold = 2
|
||||
# 若最近多为UP,则从UP翻转需更强反向信号;同理对DOWN
|
||||
if last_trend == Chan_PRICE_TREND.UP and persist_ratio_up >= 0.6:
|
||||
down_flip_threshold = -3
|
||||
elif last_trend == Chan_PRICE_TREND.DOWN and persist_ratio_down >= 0.6:
|
||||
up_flip_threshold = 3
|
||||
# EMA52 触碰强化门槛:UP时若出现支撑触碰,下翻更难;DOWN时若出现阻力触碰,上翻更难
|
||||
if ema52_valid and price_valid:
|
||||
low_v = getattr(klc, 'low', None)
|
||||
high_v = getattr(klc, 'high', None)
|
||||
if low_v is not None and high_v is not None and ema52 not in (None, 0):
|
||||
touch_tol = 0.0015
|
||||
near_support_touch = (price > ema52) and (abs(low_v - ema52) / abs(ema52) <= touch_tol)
|
||||
near_resistance_touch = (price < ema52) and (abs(high_v - ema52) / abs(ema52) <= touch_tol)
|
||||
if last_trend == Chan_PRICE_TREND.UP and near_support_touch:
|
||||
# 强化维持UP:进一步降低向下翻转阈值
|
||||
down_flip_threshold = min(down_flip_threshold - 1, -3)
|
||||
if last_trend == Chan_PRICE_TREND.DOWN and near_resistance_touch:
|
||||
# 强化维持DOWN:进一步提高向上翻转阈值
|
||||
up_flip_threshold = max(up_flip_threshold + 1, 3)
|
||||
# 7.1) 复合拐头信号:MACD/Signal 同向拐头 + hist 连续减弱 + 多次未能越过 EMA52
|
||||
pre_macd = getattr(pre, 'macd', None) if pre else None
|
||||
pre_signal = getattr(pre, 'signal', None) if pre else None
|
||||
macd_slope = (macd - pre_macd) if (pre_macd is not None and macd is not None) else 0
|
||||
signal_slope = (signal - pre_signal) if (pre_signal is not None and signal is not None) else 0
|
||||
# hist 连续减弱(绝对值缩小)
|
||||
hist_seq = []
|
||||
for wk in prev_klcs[-2:]:
|
||||
val = getattr(wk, 'macdhist', None)
|
||||
if val is not None:
|
||||
hist_seq.append(val)
|
||||
if hist is not None:
|
||||
hist_seq.append(hist)
|
||||
weaken_steps = 0
|
||||
for i in range(1, len(hist_seq)):
|
||||
if abs(hist_seq[i]) < abs(hist_seq[i-1]):
|
||||
weaken_steps += 1
|
||||
# 近窗口对 EMA52 的“未能站上/跌破”统计(放宽窗口与条件)
|
||||
window_ema = prev_klcs[-4:] if len(prev_klcs) > 0 else []
|
||||
no_up_break = False
|
||||
no_down_break = False
|
||||
if ema52_valid:
|
||||
# 未能有效上破:最近若干根收盘大多数不在 EMA52 上方,且高点多次触及/接近
|
||||
cnt_touch_up = 0
|
||||
cnt_close_above = 0
|
||||
for wk in window_ema:
|
||||
wk_close = getattr(wk, 'close', None)
|
||||
wk_high = getattr(wk, 'high', None)
|
||||
wk_ema = getattr(wk, 'ema52', None)
|
||||
if wk_close is not None and wk_ema not in (None, 0):
|
||||
if wk_close > wk_ema:
|
||||
cnt_close_above += 1
|
||||
if wk_high is not None and (wk_high >= wk_ema or abs(wk_high - wk_ema) / abs(wk_ema) <= 0.0015):
|
||||
cnt_touch_up += 1
|
||||
no_up_break = (cnt_close_above <= 1 and cnt_touch_up >= 1 and price <= ema52)
|
||||
# 未能有效下破:最近若干根收盘大多数不在 EMA52 下方,且低点多次触及/接近
|
||||
cnt_touch_down = 0
|
||||
cnt_close_below = 0
|
||||
for wk in window_ema:
|
||||
wk_close = getattr(wk, 'close', None)
|
||||
wk_low = getattr(wk, 'low', None)
|
||||
wk_ema = getattr(wk, 'ema52', None)
|
||||
if wk_close is not None and wk_ema not in (None, 0):
|
||||
if wk_close < wk_ema:
|
||||
cnt_close_below += 1
|
||||
if wk_low is not None and (wk_low <= wk_ema or abs(wk_low - wk_ema) / abs(wk_ema) <= 0.0015):
|
||||
cnt_touch_down += 1
|
||||
no_down_break = (cnt_close_below <= 1 and cnt_touch_down >= 1 and price >= ema52)
|
||||
# 若当前为UP趋势,出现明显拐头+hist减弱+未能上破EMA52,则加速看空
|
||||
if last_trend == Chan_PRICE_TREND.UP and macd_slope < 0 and signal_slope < 0 and weaken_steps >= 1 and no_up_break and macd_bias_down:
|
||||
score -= 3
|
||||
down_flip_threshold = max(down_flip_threshold, 0)
|
||||
force_flip_down = True
|
||||
# 若当前为DOWN趋势,出现明显拐头+hist减弱+未能下破EMA52,则加速看多
|
||||
if last_trend == Chan_PRICE_TREND.DOWN and macd_slope > 0 and signal_slope > 0 and weaken_steps >= 1 and no_down_break and macd_bias_up:
|
||||
score += 3
|
||||
up_flip_threshold = min(up_flip_threshold, 0)
|
||||
force_flip_up = True
|
||||
# 多次对 EMA52 的拒绝配合 MACD 逆向:加速反向翻转(降低相反方向阈值)
|
||||
if recent_up_rejects >= 2 and macd_bias_down:
|
||||
# 从 UP 向 DOWN 的翻转更容易
|
||||
down_flip_threshold = max(down_flip_threshold, -1)
|
||||
if recent_down_rejects >= 2 and macd_bias_up:
|
||||
# 从 DOWN 向 UP 的翻转更容易
|
||||
up_flip_threshold = min(up_flip_threshold, 1)
|
||||
if force_flip_down:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
elif force_flip_up:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
elif last_trend == Chan_PRICE_TREND.UP:
|
||||
if score <= down_flip_threshold:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
else:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
elif last_trend == Chan_PRICE_TREND.DOWN:
|
||||
if score >= 2:
|
||||
if score >= up_flip_threshold:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
else:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
@@ -583,6 +780,8 @@ class ChanLun():
|
||||
else:
|
||||
setattr(klc, 'trend', trend)
|
||||
last_trend = trend
|
||||
# 更新滑窗:仅向后看
|
||||
prev_klcs.append(klc)
|
||||
price_diff = klc.close - klc.pre.close if klc.pre else 0
|
||||
#if klc.index > len(klc_list) - 10:
|
||||
#print(klc.start_time, klc.end_time, klc.close, klc.ema24, klc.ema52, klc.macd, klc.signal, klc.macdhist, klc.trend, price_diff, score)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_60.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8814,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ logger = logging.getLogger(__name__)
|
||||
# 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 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
|
||||
@@ -115,11 +115,13 @@ class ChanLun_BTC(IStrategy):
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
self.init_dataframes(dataframe)
|
||||
return dataframe
|
||||
def init_dataframes(self, dataframe_m):
|
||||
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_m, dataframe_1h, dataframe_1d, dataframe_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():
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
# --- 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_60 --datadir user_data/data/binance -c ./user_data/ChanLun_SOL_30.json --timerange=20250309-
|
||||
|
||||
# freqtrade trade -c ./user_data/Chan/config/ChanLun_BTC_60.json --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies
|
||||
# freqtrade backtesting -c ./user_data/Chan/config/ChanLun_BTC_60.json --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies --timerange=20251008-
|
||||
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_60.json -t 1m 1m 1h 1d 1M --pairs BTC/USDT:USDT --timerange=20250405-
|
||||
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_60.json -t 1m 1h 1d 1M --pairs BTC/USDT --timerange=20170101-
|
||||
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies -c ./user_data/Chan/config/ChanLun_BTC_60.json -e 200 --timerange=20250201-20250901
|
||||
# freqtrade edge -c ./user_data/Chan/config/ChanLun_BTC_60.json --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901
|
||||
# freqtrade plot-dataframe -c ./user_data/Chan/config/ChanLun_BTC_60.json --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901
|
||||
|
||||
# sudo docker compose run --rm chanlun_btc backtesting -c ./user_data/Chan/config/ChanLun_BTC_60.json --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies --timerange=20250721-
|
||||
# sudo docker compose run --rm chanlun_btc download-data -c ./user_data/Chan/config/ChanLun_BTC_60.json --pairs BTC/USDT:USDT -t 1m --timerange 20240101-
|
||||
# sudo docker compose run --rm chanlun_btc trade -c ./user_data/Chan/config/ChanLun_BTC_60.json --strategy ChanLun_BTC_60 --strategy-path ./user_data/Chan/strategies
|
||||
|
||||
class ChanLun_BTC_60(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
|
||||
time5m = 5
|
||||
time15m = 15
|
||||
time30m = 30
|
||||
time1h = 60
|
||||
time2h = 120
|
||||
last_time = datetime.now()
|
||||
chan = ChanLun()
|
||||
last_order = None
|
||||
last_trade = None
|
||||
pair = 'BTC/USDT:USDT'
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
dataframe_5m = resample_to_interval(dataframe, self.get_ticker_indicator() * 5)
|
||||
dataframe_15m = resample_to_interval(dataframe, self.get_ticker_indicator() * 15)
|
||||
dataframe_30m = resample_to_interval(dataframe, self.get_ticker_indicator() * 30)
|
||||
dataframe_1h = resample_to_interval(dataframe, self.get_ticker_indicator() * 60)
|
||||
dataframe_2h = resample_to_interval(dataframe, self.get_ticker_indicator() * 120)
|
||||
dataframe = self.add_indicators(dataframe)
|
||||
dataframe_5m = self.add_indicators(dataframe_5m)
|
||||
dataframe_15m = self.add_indicators(dataframe_15m)
|
||||
dataframe_30m = self.add_indicators(dataframe_30m)
|
||||
dataframe_1h = self.add_indicators(dataframe_1h)
|
||||
dataframe_2h = self.add_indicators(dataframe_2h)
|
||||
dataframe_1h['state'] = self.chan.get_klu_state(dataframe_1h)
|
||||
dataframe = resampled_merge(dataframe, dataframe_1h)
|
||||
return dataframe
|
||||
def add_indicators(self, df):
|
||||
fast = 12
|
||||
slow = 26
|
||||
period = 9
|
||||
macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period)
|
||||
bb52 = ta.BBANDS(df, timeperiod=54, nbdevup=2.3, nbdevdn=2.3, matype=0)
|
||||
df['bb52upper'] = bb52['upperband']
|
||||
df['bb52lower'] = bb52['lowerband']
|
||||
df['atr'] = ta.ATR(df, timeperiod=14)
|
||||
df['macd'] = macd['macd']
|
||||
df['macdsignal'] = macd['macdsignal']
|
||||
df['macdhist'] = macd['macdhist']
|
||||
df['ema24'] = ta.EMA(df, timeperiod=24)
|
||||
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 populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
state_str = 'resample_{}_state'.format(self.get_ticker_indicator()*self.time1h)
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe[state_str].shift(self.time1h) == "10")
|
||||
),
|
||||
['enter_long', 'enter_tag']] = (1, 'long_signal_chan')
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe[state_str].shift(self.time1h) == "-10")
|
||||
),
|
||||
['enter_short', 'enter_tag']] = (1, 'short_signal_chan')
|
||||
return dataframe
|
||||
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
state_str = 'resample_{}_state'.format(self.get_ticker_indicator()*self.time1h)
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe[state_str].shift(self.time1h) == "-10")
|
||||
),
|
||||
['exit_long', 'exit_tag']] = (1, 'long_signal_chan')
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe[state_str].shift(self.time1h) == "10")
|
||||
),
|
||||
['exit_short', 'exit_tag']] = (1, 'short_signal_chan')
|
||||
return dataframe
|
||||
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.time1h)
|
||||
ema52_val = float(last_candle.get(ema52_str, 0) or 0)
|
||||
close_str = 'resample_{}_close'.format(self.time1h)
|
||||
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(self.time1h)
|
||||
# 保存开仓时的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 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])
|
||||
Reference in New Issue
Block a user