add more files

This commit is contained in:
jackyu66git
2025-04-25 21:39:24 +08:00
parent 761d73cdac
commit bb0b70fa44
12 changed files with 787 additions and 108 deletions
Vendored
BIN
View File
Binary file not shown.
+9 -9
View File
@@ -21,15 +21,15 @@ class ChanKLU:
def set_idx(self, idx): def set_idx(self, idx):
self.idx = idx self.idx = idx
self.index = idx self.index = idx
def set_indicators(self, dict): def set_indicators(self, item):
self.macd = dict['macd'] self.macd = float(item['macd']) if item['macd'] else 0
self.signal = dict['macdsignal'] self.signal = float(item['macdsignal']) if item['macdsignal'] else 0
self.macdhist = dict['macdhist'] self.macdhist = float(item['macdhist']) if item['macdhist'] else 0
self.ma5 = dict['ma5'] self.ma5 = float(item['ma5']) if item['ma5'] else 0
self.ma10 = dict['ma10'] self.ma10 = float(item['ma10']) if item['ma10'] else 0
self.ma30 = dict['ma30'] self.ma30 = float(item['ma30']) if item['ma30'] else 0
self.ma250 = dict['ma250'] self.ma250 = float(item['ma250']) if item['ma250'] else 0
self.rsi = dict['rsi'] self.rsi = float(item['rsi']) if item['rsi'] else 0
def get_feature_data(self): def get_feature_data(self):
features = dict() features = dict()
features['klu_close'] = self.close features['klu_close'] = self.close
+39 -13
View File
@@ -142,14 +142,28 @@ class ChanLun():
bi_list = self.cal_bi_list(klc_list) bi_list = self.cal_bi_list(klc_list)
klc_index = 0 klc_index = 0
state_list = [] state_list = []
bi_dir_list = []
for index in range(0, len(dataframe)): for index in range(0, len(dataframe)):
klc = klc_list[klc_index] klc = klc_list[klc_index]
if klc.bi and klc.bi.dir == Chan_BI_DIR.UP:
bi_dir_list.append(1)
else:
bi_dir_list.append(-1)
if klc.end_klu and klc.end_klu.idx == index: if klc.end_klu and klc.end_klu.idx == index:
klc.set_state("00")
if klc.klc_fx_type == Chan_KLC_FX.BOTTOM1:
klc.set_state("10")
elif klc.klc_fx_type == Chan_KLC_FX.TOP1:
klc.set_state("-10")
elif klc.klc_fx_type == Chan_KLC_FX.BOTTOM2:
klc.set_state("20")
elif klc.klc_fx_type == Chan_KLC_FX.TOP2:
klc.set_state("-20")
state_list.append(klc.state) state_list.append(klc.state)
klc_index += 1 klc_index += 1
else: else:
state_list.append("00") state_list.append("00")
return state_list return state_list, bi_dir_list
def get_bi_list(self, dataframe): def get_bi_list(self, dataframe):
bi_list = self.cal_bi_list(self.get_klc_list(dataframe)) bi_list = self.cal_bi_list(self.get_klc_list(dataframe))
return bi_list return bi_list
@@ -180,12 +194,24 @@ class ChanLun():
klu = ChanKLU(time_str, o, h, l, c, v) klu = ChanKLU(time_str, o, h, l, c, v)
klu.set_idx(i) klu.set_idx(i)
klu_list.append(klu) klu_list.append(klu)
if True: if 'macd' in item:
klu.set_indicators(item) klu.set_indicators(item)
return klu_list return klu_list
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 calculate_zs(self, bi_list, seg_list): def calculate_zs(self, bi_list, seg_list):
return self.get_zs_list(bi_list, seg_list) return self.get_zs_list(bi_list, seg_list)
def get_full_klc_list(self, dataframe):
klc_list = self.get_klc_list(dataframe)
bi_list = self.cal_bi_list(klc_list)
return klc_list
def get_seg_list(self, bi_list): def get_seg_list(self, bi_list):
seg_list = [] seg_list = []
up_bi_list = [] up_bi_list = []
@@ -573,7 +599,7 @@ class ChanLun():
# Second top lower to be second sell point # Second top lower to be second sell point
if last_top.high > klc.high: if last_top.high > klc.high:
#klc.set_fx(Chan_FX_TYPE.TT) #klc.set_fx(Chan_FX_TYPE.TT)
klc.set_state("20") #klc.set_state("20")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
#print(klc.start_time, klc.fx, "二类卖点Sell 1") #print(klc.start_time, klc.fx, "二类卖点Sell 1")
@@ -585,7 +611,7 @@ class ChanLun():
klc.set_klc_fx_type(Chan_KLC_FX.TOP1) klc.set_klc_fx_type(Chan_KLC_FX.TOP1)
#print(klc.start_time, klc.fx, "一类卖点Sell 1") #print(klc.start_time, klc.fx, "一类卖点Sell 1")
#klc.set_fx(fx) #klc.set_fx(fx)
klc.set_state("10") #klc.set_state("10")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
else: else:
@@ -634,7 +660,7 @@ class ChanLun():
last_top = klc last_top = klc
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Change 2") #print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Change 2")
klc.set_klc_fx_type(Chan_KLC_FX.TOP2) klc.set_klc_fx_type(Chan_KLC_FX.TOP2)
klc.set_state('30') #klc.set_state('30')
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
#print(klc.start_time, last_bottom.start_time, "Normal TOP Found, Confirm down bi 4") #print(klc.start_time, last_bottom.start_time, "Normal TOP Found, Confirm down bi 4")
@@ -652,7 +678,7 @@ class ChanLun():
#print(klc.start_time, klc.fx, "笔卖点Sell 3") #print(klc.start_time, klc.fx, "笔卖点Sell 3")
else: else:
klc.set_fx(Chan_FX_TYPE.TT) klc.set_fx(Chan_FX_TYPE.TT)
klc.set_state('20') #klc.set_state('20')
#print(klc.start_time, klc.fx, "二类卖点Sell 2") #print(klc.start_time, klc.fx, "二类卖点Sell 2")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
@@ -691,7 +717,7 @@ class ChanLun():
# Second bottom uppper to be second buy point and confirm last bi # Second bottom uppper to be second buy point and confirm last bi
if last_bottom.low < klc.low: if last_bottom.low < klc.low:
#klc.set_fx(Chan_FX_TYPE.BB) #klc.set_fx(Chan_FX_TYPE.BB)
klc.set_state("-20") #klc.set_state("-20")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
#print(klc.start_time, klc.fx, "二类买点Buy 1") #print(klc.start_time, klc.fx, "二类买点Buy 1")
@@ -702,7 +728,7 @@ class ChanLun():
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 1") #print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 1")
klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM1) klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM1)
#print(klc.start_time, klc.fx, "一类买点Buy 1") #print(klc.start_time, klc.fx, "一类买点Buy 1")
klc.set_state("-10") #klc.set_state("-10")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
else: else:
@@ -730,7 +756,7 @@ class ChanLun():
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Bottom Change 2") #print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Bottom Change 2")
klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2) klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2)
#print(klc.start_time, last_bi.start_klc.start_time, "New BOTTOM Found reset last bi") #print(klc.start_time, last_bi.start_klc.start_time, "New BOTTOM Found reset last bi")
klc.set_state("-10") #klc.set_state("-10")
#print(klc.start_time, klc.fx, "笔买点Buy 1") #print(klc.start_time, klc.fx, "笔买点Buy 1")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
@@ -753,7 +779,7 @@ class ChanLun():
last_bottom = klc last_bottom = klc
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 2") #print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 2")
klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2) klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2)
klc.set_state('-30') #klc.set_state('-30')
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
#print(klc.start_time, klc.fx, "笔买点Buy 2") #print(klc.start_time, klc.fx, "笔买点Buy 2")
@@ -771,7 +797,7 @@ class ChanLun():
#print(klc.start_time, klc.fx, "笔买点Buy 3") #print(klc.start_time, klc.fx, "笔买点Buy 3")
else: else:
klc.set_fx(Chan_FX_TYPE.BB) klc.set_fx(Chan_FX_TYPE.BB)
klc.set_state('-20') #klc.set_state('-20')
#print(klc.start_time, klc.fx, "二类买点Buy 2") #print(klc.start_time, klc.fx, "二类买点Buy 2")
bi_list[-1].add_klc(klc) bi_list[-1].add_klc(klc)
klc.set_bi(bi_list[-1]) klc.set_bi(bi_list[-1])
@@ -815,7 +841,7 @@ class ChanLun():
#for index in range(0, 10): #for index in range(0, 10):
#print(bi_list[index].start_time, bi_list[index].start_klc.start_time, bi_list[index].dir) #print(bi_list[index].start_time, bi_list[index].start_klc.start_time, bi_list[index].dir)
return bi_list return bi_list
def get_zs_list(self, bi_list, seg_list): def get_zs_list(self, bi_list, seg_list):
zs_list = [] zs_list = []
bsp_list = [] bsp_list = []
+78 -14
View File
@@ -49,17 +49,15 @@ class ChanLunClassifier:
train_df = dataframe.iloc[:train_size].copy() train_df = dataframe.iloc[:train_size].copy()
# 获取训练集特征和标签 # 获取训练集特征和标签
X_train, y_train = self.get_feature_data(train_df) save_csv = True if data_file_path else False
X_train, y_train = self.get_feature_data(train_df, save_csv=save_csv, csv_path=data_file_path if data_file_path else 'feature_data.csv')
if len(X_train) == 0: if len(X_train) == 0:
print("没有提取到足够的特征数据进行训练") print("没有提取到足够的特征数据进行训练")
return None return None
# 保存特征数据(可选) # 保存特征数据的步骤已经移到get_feature_data方法中处理
if data_file_path: # 以下是原有代码
feature_df = pd.DataFrame(X_train)
feature_df['label'] = y_train
feature_df.to_csv(data_file_path, index=False)
#{'eta': 0.03, 'max_depth': 4, 'subsample': 0.8, 'colsample_bytree': 0.8, 'gamma': 0.1, 'min_child_weight': 3, 'alpha': 1, 'lambda': 3}, #{'eta': 0.03, 'max_depth': 4, 'subsample': 0.8, 'colsample_bytree': 0.8, 'gamma': 0.1, 'min_child_weight': 3, 'alpha': 1, 'lambda': 3},
# 默认XGBoost参数 # 默认XGBoost参数
default_params = { default_params = {
@@ -210,10 +208,12 @@ class ChanLunClassifier:
else: else:
self.model = xgb.Booster() self.model = xgb.Booster()
self.model.load_model(model_file_path) self.model.load_model(model_file_path)
def find_best_params(self, dataframe=None): def find_best_params(self, dataframe=None, save_csv=False, csv_path_prefix='param_'):
""" """
寻找最佳参数组合 寻找最佳参数组合
:param dataframe: 输入的DataFrame,如果为None则使用初始化时的dataframe :param dataframe: 输入的DataFrame,如果为None则使用初始化时的dataframe
:param save_csv: 是否保存特征数据到CSV文件
:param csv_path_prefix: CSV文件保存路径前缀,会自动添加参数信息
:return: 最佳参数 :return: 最佳参数
""" """
# 不同参数组合 # 不同参数组合
@@ -234,9 +234,13 @@ class ChanLunClassifier:
best_params = None best_params = None
best_model = None best_model = None
for params in param_combinations: for i, params in enumerate(param_combinations):
print(f"\n尝试参数组合: {params}") print(f"\n尝试参数组合: {params}")
model = self.train_model(dataframe=dataframe, custom_params=params) # 生成CSV文件名,包含一些参数信息
param_info = f"eta{params['eta']}_depth{params['max_depth']}"
train_csv_path = f"{csv_path_prefix}train_{param_info}.csv" if save_csv else None
model = self.train_model(dataframe=dataframe, data_file_path=train_csv_path, custom_params=params)
# 分割数据集,后20%用于测试 # 分割数据集,后20%用于测试
if dataframe is None: if dataframe is None:
@@ -246,7 +250,8 @@ class ChanLunClassifier:
test_df = dataframe.iloc[train_size:].copy() test_df = dataframe.iloc[train_size:].copy()
# 获取测试集特征和标签 # 获取测试集特征和标签
X_test, y_test = self.get_validate_feature_data(test_df) test_csv_path = f"{csv_path_prefix}test_{param_info}.csv" if save_csv else None
X_test, y_test = self.get_validate_feature_data(test_df, save_csv=save_csv, csv_path=test_csv_path)
if len(X_test) == 0: if len(X_test) == 0:
print("没有提取到足够的测试特征数据") print("没有提取到足够的测试特征数据")
@@ -272,10 +277,12 @@ class ChanLunClassifier:
return best_params return best_params
def get_feature_data(self, dataframe): def get_feature_data(self, dataframe, save_csv=False, csv_path='feature_data.csv'):
""" """
从dataframe提取特征数据 从dataframe提取特征数据
:param dataframe: 输入的DataFrame :param dataframe: 输入的DataFrame
:param save_csv: 是否保存特征数据到CSV文件
:param csv_path: CSV文件保存路径
:return: 特征矩阵X和标签y :return: 特征矩阵X和标签y
""" """
# 使用ChanLun获取bi_list # 使用ChanLun获取bi_list
@@ -285,6 +292,7 @@ class ChanLunClassifier:
# 筛选方向为UP的bi的起始klc # 筛选方向为UP的bi的起始klc
feature_data = [] feature_data = []
labels = [] labels = []
feature_keys = [] # 用于保存特征名称
bi_index = 1 bi_index = 1
sample_list = [] sample_list = []
@@ -301,6 +309,10 @@ class ChanLunClassifier:
# 提取特征 # 提取特征
features = klc.get_feature_data() features = klc.get_feature_data()
# 保存第一个样本的特征名称,用于CSV列名
if len(feature_keys) == 0:
feature_keys = list(features.keys())
# 将特征转换为模型可用的格式 # 将特征转换为模型可用的格式
feature_vec = [] feature_vec = []
for key, value in features.items(): for key, value in features.items():
@@ -323,15 +335,38 @@ class ChanLunClassifier:
feature_data.append(feature_vec) feature_data.append(feature_vec)
labels.append(label) labels.append(label)
# 如果需要保存到CSV
if save_csv:
# 创建DataFrame保存特征数据
# 只保留数值型特征
numeric_feature_keys = [key for i, key in enumerate(feature_keys)
if i < len(feature_data[0]) if isinstance(feature_data[0][i], (int, float))]
# 创建特征数据的DataFrame
df_features = pd.DataFrame(feature_data, columns=numeric_feature_keys)
# 添加标签列
df_features['label'] = labels
# 添加时间信息便于分析
if len(sample_list) > 0:
times = [klc.start_time for klc in sample_list]
df_features['time'] = times
# 保存到CSV
df_features.to_csv(csv_path, index=False)
print(f"特征数据已保存到 {csv_path}")
# 在return前添加 # 在return前添加
positive_count = np.sum(labels) positive_count = np.sum(labels)
print(f"正样本数量: {positive_count}, 负样本数量: {len(labels) - positive_count}") print(f"正样本数量: {positive_count}, 负样本数量: {len(labels) - positive_count}")
print("Trainning data: ", len(feature_data), klc_list[-1].start_time, klc_list[-1].klc_fx_type , "---------------------") print("Trainning data: ", len(feature_data), klc_list[-1].start_time, klc_list[-1].klc_fx_type , "---------------------")
return np.array(feature_data), np.array(labels) return np.array(feature_data), np.array(labels)
def get_validate_feature_data(self, dataframe): def get_validate_feature_data(self, dataframe, save_csv=False, csv_path='validate_feature_data.csv'):
""" """
从dataframe提取特征数据 从dataframe提取特征数据
:param dataframe: 输入的DataFrame :param dataframe: 输入的DataFrame
:param save_csv: 是否保存特征数据到CSV文件
:param csv_path: CSV文件保存路径
:return: 特征矩阵X和标签y :return: 特征矩阵X和标签y
""" """
# 使用ChanLun获取bi_list # 使用ChanLun获取bi_list
@@ -341,6 +376,8 @@ class ChanLunClassifier:
# 筛选方向为UP的bi的起始klc # 筛选方向为UP的bi的起始klc
feature_data = [] feature_data = []
labels = [] labels = []
feature_keys = [] # 用于保存特征名称
bi_index = 1 bi_index = 1
sample_list = [] sample_list = []
for klc in klc_list: for klc in klc_list:
@@ -353,6 +390,10 @@ class ChanLunClassifier:
# 提取特征 # 提取特征
features = klc.get_feature_data() features = klc.get_feature_data()
# 保存第一个样本的特征名称,用于CSV列名
if len(feature_keys) == 0:
feature_keys = list(features.keys())
# 将特征转换为模型可用的格式 # 将特征转换为模型可用的格式
feature_vec = [] feature_vec = []
# 与get_feature_data保持一致,只使用相同的特征集 # 与get_feature_data保持一致,只使用相同的特征集
@@ -373,12 +414,35 @@ class ChanLunClassifier:
feature_data.append(feature_vec) feature_data.append(feature_vec)
labels.append(label) labels.append(label)
# 如果需要保存到CSV
if save_csv:
# 创建DataFrame保存特征数据
# 只保留数值型特征
numeric_feature_keys = [key for i, key in enumerate(feature_keys)
if i < len(feature_data[0]) if isinstance(feature_data[0][i], (int, float))]
# 创建特征数据的DataFrame
df_features = pd.DataFrame(feature_data, columns=numeric_feature_keys)
# 添加标签列
df_features['label'] = labels
# 添加时间信息便于分析
if len(sample_list) > 0:
times = [klc.start_time for klc in sample_list]
df_features['time'] = times
# 保存到CSV
df_features.to_csv(csv_path, index=False)
print(f"验证特征数据已保存到 {csv_path}")
print("Validating data: ", len(feature_data), klc_list[-1].start_time, klc_list[-1].klc_fx_type , "---------------------") print("Validating data: ", len(feature_data), klc_list[-1].start_time, klc_list[-1].klc_fx_type , "---------------------")
return np.array(feature_data), np.array(labels) return np.array(feature_data), np.array(labels)
def validate_model(self, dataframe=None): def validate_model(self, dataframe=None, save_csv=False, csv_path='validate_feature_data.csv'):
""" """
使用dataframe后20%的数据验证模型 使用dataframe后20%的数据验证模型
:param dataframe: 输入的DataFrame,如果为None则使用初始化时的dataframe :param dataframe: 输入的DataFrame,如果为None则使用初始化时的dataframe
:param save_csv: 是否保存特征数据到CSV文件
:param csv_path: CSV文件保存路径
:return: 验证结果 :return: 验证结果
""" """
if self.model is None: if self.model is None:
@@ -393,7 +457,7 @@ class ChanLunClassifier:
test_df = dataframe.iloc[train_size:].copy() test_df = dataframe.iloc[train_size:].copy()
# 获取测试集特征和标签 # 获取测试集特征和标签
X_test, y_test = self.get_validate_feature_data(test_df) X_test, y_test = self.get_validate_feature_data(test_df, save_csv=save_csv, csv_path=csv_path)
if len(X_test) == 0: if len(X_test) == 0:
print("没有提取到足够的测试特征数据") print("没有提取到足够的测试特征数据")
Binary file not shown.
Binary file not shown.
Binary file not shown.
+356
View File
@@ -0,0 +1,356 @@
# --- Do not remove these libs ---
from freqtrade.strategy import IStrategy
import sys
import os
# 添加父目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ChanLun import ChanLun
from ChanLun_Classifier import ChanLunClassifier
from ChanEnum import Chan_FX_TYPE, Chan_KLC_FX
# --------------------------------
from technical.util import resample_to_interval, resampled_merge
import talib.abstract as ta
from pandas import DataFrame
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
from typing import Optional
import logging
logger = logging.getLogger(__name__)
### Now you can use logger.info('asfd') to log
# freqtrade plot-dataframe --strategy ChanLun_SOL_5 --datadir user_data/data/binance -c ./user_data/ChanLun_SOL.json --timerange=20250309-
# freqtrade trade -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL_15 --strategy-path ./user_data/Chan/strategies
# freqtrade backtesting -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL_15 --strategy-path ./user_data/Chan/strategies --timerange=20250416-
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_SOL.json -t 1m --pairs SOL/USDT:USDT --timerange=20250405-
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss --strategy ChanLun_SOL_5 --strategy-path ./user _data/Chan/strategies -c ./user_data/Chan/config/ChanLun_SOL.json -e 200 --timerange=20250201-20250401
# sudo docker compose run --rm chan_btc backtesting -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL --strategy-path ./user_data/Chan/strategies --timerange=20250101-
# sudo docker compose run --rm chan_btc download-data -c ./user_data/Chan/config/ChanLun_SOL.json --pairs SOL/USDT:USDT -t 1m --timerange 20240101-
# sudo docker compose run --rm chan_btc trade -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL --strategy-path ./user_data/Chan/strategies
class ChanLun_SOL_15(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.10,
"360": 0.05,
"640": 0.025,
"1200": 0
}
# 5m and 15m
minimal_roi_1 = {
"0": 0.253,
"60": 0.159,
"120": 0.052,
"240": 0
}
# 15m and 30m
minimal_roi_2 = {
"0": 0.253,
"120": 0.159,
"240": 0.052,
"360": 0
}
can_short = True
stoploss = -0.20
trailing_stop = False
trailing_stop_positive = 0.015
trailing_stop_positive_offset = 0.043
trailing_only_offset_is_reached = False
position_adjustment_enable = True
max_entry_position_adjustment = 3
max_dca_multiplier = 5.5
startup_candle_count = 600
time5 = 5
time15 = 15
time30 = 30
time60 = 60
time4h = 240
small_time = 30
big_time = 60
last_time = datetime.now()
big_size = 0
big_state = "00"
big_state_list = []
chan = ChanLun()
small_size = 0
small_state = "00"
small_state_list = []
classifier = ChanLunClassifier(None)
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# resample our dataframes
dataframe_5 = resample_to_interval(dataframe, self.get_ticker_indicator() * 5)
dataframe_15 = resample_to_interval(dataframe, self.get_ticker_indicator() * 15)
dataframe_30 = resample_to_interval(dataframe, self.get_ticker_indicator() * 30)
dataframe_60 = resample_to_interval(dataframe, self.get_ticker_indicator() * 60)
dataframe_4h = resample_to_interval(dataframe, self.get_ticker_indicator() * 240)
#dataframe_1d = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe='1d')
#dataframe_1w = resample_to_interval(dataframe_1d, self.get_ticker_indicator() * 10080)
#dataframe_1m = resample_to_interval(dataframe_1d, self.get_ticker_indicator() * 43200)
dataframe_1d = resample_to_interval(dataframe, self.get_ticker_indicator() * 1440)
#dataframe_1w = resample_to_interval(dataframe, self.get_ticker_indicator() * 10080)
#dataframe_1m = resample_to_interval(dataframe, self.get_ticker_indicator() * 43200)
dataframe = self.add_indicators(dataframe)
dataframe_5 = self.add_indicators(dataframe_5)
dataframe_30 = self.add_indicators(dataframe_30)
dataframe_60 = self.add_indicators(dataframe_60)
dataframe_4h = self.add_indicators(dataframe_4h)
dataframe_1d = self.add_indicators(dataframe_1d)
dataframe['state'], dataframe['bi_dir'] = self.chan.cal_klu_state(dataframe)
dataframe_5['state'], dataframe_5['bi_dir'] = self.chan.cal_klu_state(dataframe_5)
dataframe_30['state'], dataframe_30['bi_dir'] = self.chan.cal_klu_state(dataframe_30)
dataframe_60['state'], dataframe_60['bi_dir'] = self.chan.cal_klu_state(dataframe_60)
dataframe['volume_ratio'] = self.chan.cal_volume_ratio(dataframe)
dataframe['volume_ratio_5'] = self.chan.cal_volume_ratio(dataframe_5)
dataframe['volume_ratio_30'] = self.chan.cal_volume_ratio(dataframe_30)
dataframe['volume_ratio_60'] = self.chan.cal_volume_ratio(dataframe_60)
#self.print_klc(dataframe, "1m: ")
#self.chan.plot_dual(dataframe_5, dataframe_30)
#dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
#self.print_macd_div_list(dataframe)
#self.print_resample_df(dataframe, 1, 50)
#self.chan.get_bi_list(dataframe_30)
#if self.last_time + timedelta(minutes=1) < datetime.now():
#print(informative.iloc[-1])
#self.print_klc(dataframe, "1m: ")
#self.print_klc(dataframe_5, "5m: ")
#self.print_klc(dataframe_30, "30m:")
#self.log_macd_div_list(dataframe)
#self.print_xgb(dataframe, "1m_model")
#self.print_xgb(dataframe_5, "5m_model")
#self.print_xgb(dataframe_30, "30m_model")
#self.print_xgb(dataframe_60, "1h_model")
#self.print_xgb(dataframe_4h, "4h_model")
#print("-------------------------------------------------------------------------------")
#self.last_time = datetime.now()
dataframe = resampled_merge(dataframe, dataframe_5)
#dataframe = resampled_merge(dataframe, dataframe_15)
dataframe = resampled_merge(dataframe, dataframe_30)
dataframe = resampled_merge(dataframe, dataframe_60)
#dataframe = resampled_merge(dataframe, dataframe_4h)
return dataframe
# This is called when placing the initial order (opening trade)
def print_xgb(self, dataframe, model_name):
self.classifier.load_model(model_name)
klc_list = self.chan.get_klc_list(dataframe)
klc1 = klc_list[-1]
klc2 = klc_list[-2]
klc3 = klc_list[-3]
if klc1.end_time == klc2.start_time:
print(model_name, klc1.end_time, klc1.fx, self.classifier.predict(klc1))
else:
print(model_name, klc1.start_time, klc1.fx, self.classifier.predict(klc1))
print(model_name, klc2.end_time, klc2.fx, self.classifier.predict(klc2))
print(model_name, klc3.end_time, klc3.fx, self.classifier.predict(klc3))
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
proposed_stake: float, min_stake: float | None, max_stake: float,
leverage: float, entry_tag: str | None, side: str,
**kwargs) -> float:
# We need to leave most of the funds for possible further DCA orders
# This also applies to fixed stakes
return proposed_stake / self.max_dca_multiplier
def adjust_trade_position1(self, trade: Trade, current_time: datetime,
current_rate: float, current_profit: float,
min_stake: float | None, max_stake: float,
current_entry_rate: float, current_exit_rate: float,
current_entry_profit: float, current_exit_profit: float,
**kwargs
) -> float | None | tuple[float | None, str | None]:
"""
Custom trade adjustment logic, returning the stake amount that a trade should be
increased or decreased.
This means extra entry or exit orders with additional fees.
Only called when `position_adjustment_enable` is set to True.
For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
When not implemented by a strategy, returns None
:param trade: trade object.
:param current_time: datetime object, containing the current datetime
:param current_rate: Current entry rate (same as current_entry_profit)
:param current_profit: Current profit (as ratio), calculated based on current_rate
(same as current_entry_profit).
:param min_stake: Minimal stake size allowed by exchange (for both entries and exits)
:param max_stake: Maximum stake allowed (either through balance, or by exchange limits).
:param current_entry_rate: Current rate using entry pricing.
:param current_exit_rate: Current rate using exit pricing.
:param current_entry_profit: Current profit using entry pricing.
:param current_exit_profit: Current profit using exit pricing.
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
:return float: Stake amount to adjust your trade,
Positive values to increase position, Negative values to decrease position.
Return None for no action.
Optionally, return a tuple with a 2nd element with an order reason
"""
#if trade.has_open_orders:
# Only act if no orders are open
#return
#if current_profit > 0.05 and trade.nr_of_successful_exits == 0:
# Take half of the profit at +5%
#return -(trade.stake_amount / 2), "half_profit_5%"
#if current_profit > -0.05:
#return None
# Obtain pair dataframe (just to show how to access it)
dataframe, _ = self.dp.get_analyzed_dataframe(trade.pair, self.timeframe)
# Only buy when not actively falling price.
#last_candle = dataframe.iloc[-1].squeeze()
#previous_candle = dataframe.iloc[-2].squeeze()
#if last_candle["close"] < previous_candle["close"]:
#return None
filled_entries = trade.select_filled_orders(trade.entry_side)
last_entry = filled_entries[-1]
count_of_entries = trade.nr_of_successful_entries
# Allow up to 3 additional increasingly larger buys (4 in total)
# Initial buy is 1x
# If that falls to -5% profit, we buy 1.25x more, average profit should increase to roughly -2.2%
# If that falls down to -5% again, we buy 1.5x more
# If that falls once again down to -5%, we buy 1.75x more
# Total stake for this trade would be 1 + 1.25 + 1.5 + 1.75 = 5.5x of the initial allowed stake.
# That is why max_dca_multiplier is 5.5
# Hope you have a deep wallet!
# This returns first order stake size
#print(dataframe.iloc[-1]['resample_{}_state'.format(self.get_ticker_indicator()*self.time60)])
# This returns first order stake size
stake_amount = filled_entries[0].stake_amount
# This then calculates current safety order size
stake_amount = stake_amount * (1 + (count_of_entries * 0.5))
dataframe_date = dataframe.iloc[-1]['date']
#print(stake_amount, "---------------------------------------------------")
if last_entry.order_filled_utc + timedelta(minutes=self.time5) < dataframe_date:
if dataframe.iloc[-self.time5]['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)] == "-10" and last_entry.side == "buy":
#print(dataframe.iloc[-self.time5])
#print(stake_amount)
return stake_amount, "1/3rd_increase"
if last_entry.order_filled_utc + timedelta(minutes=self.time5) < dataframe_date:
if dataframe.iloc[-self.time5]['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)] == "10" and last_entry.side == "sell":
#print(dataframe.iloc[-self.time5])
#print(stake_amount)
return stake_amount, "1/3rd_increase"
return None
def log_macd_div_list(self, dataframe):
bi_macd_div_list, bi_list, seg_macd_div_list, seg_list = self.chan.get_macd_div_list(dataframe)
logger.info(f"BI MACD DIV LIST")
for index in range(len(bi_list)-5, len(bi_list)):
bi = bi_list[index]
logger.info(f'{bi.start_time}, {bi.high}, {bi.low}, {bi.dir}, {bi.macd_div}')
logger.info(f"SEG MACD DIV LIST")
for index in range(len(seg_list)-5, len(seg_list)):
seg = seg_list[index]
logger.info(f'{seg.start_bi.start_time}, {seg.high}, {seg.low}, {seg.dir}, {seg.macd_div}')
def print_klc(self, df, label):
klc_list = self.chan.get_full_klc_list(df)
log_str = f""
for index in range(len(klc_list)-5, len(klc_list)):
klc = klc_list[index]
bi_dir = str(klc.bi.dir).replace("Chan_BI_DIR.", "")
klc_fx_type = str(klc.klc_fx_type).replace("Chan_KLC_FX.", "")
volume_ratio = df.iloc[index]['volume_ratio']
if klc.end_time:
log_str += f"{klc.end_time}E, {bi_dir}, {klc_fx_type}, {volume_ratio}, "
else:
log_str += f"{klc.start_time}S, {bi_dir}, {klc_fx_type}, {volume_ratio}, "
logger.info(label+log_str)
def print_resample_df(self, dataframe, time, limit=10):
df = dataframe.tail(limit)
if limit > 0:
if time == 1:
for index in range(len(dataframe) - limit, len(dataframe)):
cn1 = 'date'
cn2 = 'rsi'
cn3 = 'state'
logger.info(f'{df[cn1][index]}, {df[cn2][index]}, {df[cn3][index]}')
else:
for index in range(0, limit):
cn1 = 'resample_{}_date'.format(self.get_ticker_indicator()*time)
cn2 = 'resample_{}_rsi'.format(self.get_ticker_indicator()*time)
cn3 = 'resample_{}_state'.format(self.get_ticker_indicator()*time)
logger.info(f'{df[cn1][index]}, {df[cn2][index]}, {df[cn3][index]}')
def add_indicators(self, df):
fast = 9
slow = 24
period = 14
macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period)
df['macd'] = macd['macd']
df['macdsignal'] = macd['macdsignal']
df['macdhist'] = macd['macdhist']
df['ma5'] = ta.MA(df, timeperiod=5)
df['ma10'] = ta.MA(df, timeperiod=10)
df['ma30'] = ta.EMA(df, timeperiod=30)
df['ma250'] = ta.MA(df, timeperiod=250)
df['rsi'] = ta.RSI(df, timeperiod=14)
df['macd'] = df['macd'].fillna(0)
df['macdsignal'] = df['macdsignal'].fillna(0)
df['macdhist'] = df['macdhist'].fillna(0)
df['ma5'] = df['ma5'].fillna(0)
df['ma10'] = df['ma10'].fillna(0)
df['ma30'] = df['ma30'].fillna(0)
df['ma250'] = df['ma250'].fillna(0)
df['rsi'] = df['rsi'].fillna(0)
return df
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
#(dataframe['state'] == "-30")
((dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "10")) |
((dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "20"))
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "-10") &
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time30)] == "-10") &
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "-10")
#(qtpylib.crossed_above(dataframe['macd'], dataframe['macdsignal']))
),
['enter_long', 'enter_tag']] = (1, 'long_signal_chan')
dataframe.loc[
(
#(dataframe['state'] == "30")
((dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "99")) |
((dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "99"))
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "10") &
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time30)] == "10") &
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "10")
#(qtpylib.crossed_above(dataframe['macd'], dataframe['macdsignal']))
),
['enter_short', 'enter_tag']] = (1, 'short_signal_chan')
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
#(dataframe['state']== "-10").shift(1) |
#(dataframe['state']== "-20").shift(1)
((dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "-10")) |
((dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "-20"))
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "10")
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time30)] == "10") &
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time60)] == "10")
),
['exit_long', 'exit_tag']] = (1, 'long_close_signal_chan')
dataframe.loc[
(
(dataframe['state'] == "99").shift(1) |
(dataframe['state'] == "99").shift(1)
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time5)].shift(self.time5) == "-10")
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time30)] == "-10") &
#(dataframe['resample_{}_state'.format(self.get_ticker_indicator()*self.time60)] == "-10")
),
['exit_short', 'exit_tag']] = (1, 'short_close_signal_chan')
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 1.0
def get_ticker_indicator(self):
return int(self.timeframe[:-1])
+35 -21
View File
@@ -2,10 +2,8 @@
from freqtrade.strategy import IStrategy from freqtrade.strategy import IStrategy
import sys import sys
import os import os
#sys.setrecursionlimit(1000000) #例如这里设置为一百万 # 添加父目录到系统路径
#sys.path.append(os.path.abspath("/freqtrade/user_data/Chan")) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#sys.path.append(os.path.abspath("/Users/jack/Project/freqtrade/user_data/Chan"))
sys.path.append(os.path.abspath("/Users/jack/Documents/GitHub/freqtrade/user_data/Chan"))
from ChanLun import ChanLun from ChanLun import ChanLun
from ChanLun_Classifier import ChanLunClassifier from ChanLun_Classifier import ChanLunClassifier
from ChanEnum import Chan_FX_TYPE, Chan_KLC_FX from ChanEnum import Chan_FX_TYPE, Chan_KLC_FX
@@ -26,9 +24,9 @@ logger = logging.getLogger(__name__)
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_SOL.json -t 1m --pairs SOL/USDT:USDT --timerange=20250405- # freqtrade download-data -c ./user_data/Chan/config/ChanLun_SOL.json -t 1m --pairs SOL/USDT:USDT --timerange=20250405-
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss --strategy ChanLun_SOL_5 --strategy-path ./user _data/Chan/strategies -c ./user_data/Chan/config/ChanLun_SOL.json -e 200 --timerange=20250201-20250401 # freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss --strategy ChanLun_SOL_5 --strategy-path ./user _data/Chan/strategies -c ./user_data/Chan/config/ChanLun_SOL.json -e 200 --timerange=20250201-20250401
# sudo docker compose run --rm chan_btc backtesting -c ./user_data/ChanLun_SOL.json --strategy ChanLun_SOL --strategy-path ./user_data/strategies --timerange=20250101- # sudo docker compose run --rm chan_btc backtesting -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL --strategy-path ./user_data/Chan/strategies --timerange=20250101-
# sudo docker compose run --rm chan_btc download-data -c ./user_data/ChanLun_SOL.json --pairs SOL/USDT:USDT -t 1m --timerange 20240101- # sudo docker compose run --rm chan_btc download-data -c ./user_data/Chan/config/ChanLun_SOL.json --pairs SOL/USDT:USDT -t 1m --timerange 20240101-
# sudo docker compose run --rm chan_btc trade -c ./user_data/ChanLun_SOL.json --strategy ChanLun_SOL --strategy-path ./user_data/strategies # sudo docker compose run --rm chan_btc trade -c ./user_data/Chan/config/ChanLun_SOL.json --strategy ChanLun_SOL --strategy-path ./user_data/Chan/strategies
class ChanLun_SOL_5(IStrategy): class ChanLun_SOL_5(IStrategy):
INTERFACE_VERSION: int = 3 INTERFACE_VERSION: int = 3
@@ -72,7 +70,7 @@ class ChanLun_SOL_5(IStrategy):
time30 = 30 time30 = 30
time60 = 60 time60 = 60
time4h = 240 time4h = 240
time5 = 30 time5 = 5
last_time = datetime.now() last_time = datetime.now()
big_size = 0 big_size = 0
big_state = "00" big_state = "00"
@@ -117,11 +115,11 @@ class ChanLun_SOL_5(IStrategy):
self.classifier.train_model(dataframe, model_name="1m_model") self.classifier.train_model(dataframe, model_name="1m_model")
self.classifier.train_model(dataframe_1d, model_name="1d_model") self.classifier.train_model(dataframe_1d, model_name="1d_model")
""" """
"""
model_name = "60m_model" model_name = "30m_model"
df = dataframe_60 df = dataframe_30
if self.classifier.model is None: if self.classifier.model is None:
#self.classifier.train_model(df, model_name=model_name) #self.classifier.train_model(df, model_name=model_name, data_file_path=model_name + '_feature_data.csv')
self.classifier.load_model(model_name=model_name) self.classifier.load_model(model_name=model_name)
klc_list = self.chan.get_klc_list(df) klc_list = self.chan.get_klc_list(df)
bi_list = self.chan.cal_bi_list(klc_list) bi_list = self.chan.cal_bi_list(klc_list)
@@ -131,14 +129,14 @@ class ChanLun_SOL_5(IStrategy):
bottom_count = 0 bottom_count = 0
for index in range(int(len(klc_list) * 0.8), len(klc_list)): for index in range(int(len(klc_list) * 0.8), len(klc_list)):
klc = klc_list[index] klc = klc_list[index]
if self.classifier.predict(klc) > 0.37 and (klc.klc_fx_type == Chan_KLC_FX.BOTTOM1 or klc.klc_fx_type == Chan_KLC_FX.BOTTOM2): if self.classifier.predict(klc) > 0.4 and (klc.klc_fx_type == Chan_KLC_FX.BOTTOM1 or klc.klc_fx_type == Chan_KLC_FX.BOTTOM2):
features = klc.get_feature_data() features = klc.get_feature_data()
print(klc.bi.start_time, klc.start_time, klc.fx, self.classifier.predict(klc), features['klc_macd'], features['klc_macd_hist'], features['klc_rsi'], features['klc_macd_signal']) print(klc.end_time, klc.fx, self.classifier.predict(klc), features['klc_macd'], features['klc_macd_hist'], features['klc_rsi'], features['klc_macd_signal'])
bottom_avg += self.classifier.predict(klc) bottom_avg += self.classifier.predict(klc)
bottom_count += 1 bottom_count += 1
if self.classifier.predict(klc) > 0.42 and (klc.klc_fx_type == Chan_KLC_FX.TOP1 or klc.klc_fx_type == Chan_KLC_FX.TOP2): if self.classifier.predict(klc) > 0.35 and (klc.klc_fx_type == Chan_KLC_FX.TOP1 or klc.klc_fx_type == Chan_KLC_FX.TOP2):
features = klc.get_feature_data() features = klc.get_feature_data()
print(klc.bi.start_time, klc.start_time, klc.fx, self.classifier.predict(klc), features['klc_macd'], features['klc_macd_hist'], features['klc_rsi'], features['klc_macd_signal']) print(klc.end_time, klc.fx, self.classifier.predict(klc), features['klc_macd'], features['klc_macd_hist'], features['klc_rsi'], features['klc_macd_signal'])
top_avg += self.classifier.predict(klc) top_avg += self.classifier.predict(klc)
top_count += 1 top_count += 1
if bottom_count > 0: if bottom_count > 0:
@@ -147,7 +145,7 @@ class ChanLun_SOL_5(IStrategy):
top_avg /= top_count top_avg /= top_count
print(bottom_avg, top_avg) print(bottom_avg, top_avg)
print("-------------------------------------------------------------------------------") print("-------------------------------------------------------------------------------")
"""
""" """
self.print_xgb(dataframe, "1m_model") self.print_xgb(dataframe, "1m_model")
self.print_xgb(dataframe_5, "5m_model") self.print_xgb(dataframe_5, "5m_model")
@@ -167,13 +165,16 @@ class ChanLun_SOL_5(IStrategy):
#dataframe_60['state'] = self.chan.cal_klu_state(dataframe_60) #dataframe_60['state'] = self.chan.cal_klu_state(dataframe_60)
#dataframe_4h['state'] = self.chan.resample_klc_list(dataframe_4h) #dataframe_4h['state'] = self.chan.resample_klc_list(dataframe_4h)
self.chan.plot_dual(dataframe_30, dataframe_60) #self.chan.plot_dual(dataframe_5, dataframe_30)
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
#self.print_macd_div_list(dataframe) #self.print_macd_div_list(dataframe)
#self.print_resample_df(dataframe, 1, 50) #self.print_resample_df(dataframe, 1, 50)
#self.chan.get_bi_list(dataframe_30) #self.chan.get_bi_list(dataframe_30)
if self.last_time + timedelta(minutes=1) < datetime.now(): if self.last_time + timedelta(minutes=1) < datetime.now():
#print(informative.iloc[-1]) #print(informative.iloc[-1])
#self.print_klc(dataframe, "1m: ")
#self.print_klc(dataframe_5, "5m: ")
#self.print_klc(dataframe_30, "30m:")
#self.log_macd_div_list(dataframe) #self.log_macd_div_list(dataframe)
#self.print_xgb(dataframe, "1m_model") #self.print_xgb(dataframe, "1m_model")
#self.print_xgb(dataframe_5, "5m_model") #self.print_xgb(dataframe_5, "5m_model")
@@ -311,6 +312,19 @@ class ChanLun_SOL_5(IStrategy):
fx5 = fx_list[-5] fx5 = fx_list[-5]
#print(fx1.end_time, fx1.fx, fx2.end_time, fx2.fx, fx3.end_time, fx3.fx) #print(fx1.end_time, fx1.fx, fx2.end_time, fx2.fx, fx3.end_time, fx3.fx)
logger.info(f'\n{fx5.end_time} {fx5.state} {fx4.end_time} {fx4.state} {fx3.end_time} {fx3.state} {fx2.end_time} {fx2.state} {fx1.end_time} {fx1.state} TF: {label}') logger.info(f'\n{fx5.end_time} {fx5.state} {fx4.end_time} {fx4.state} {fx3.end_time} {fx3.state} {fx2.end_time} {fx2.state} {fx1.end_time} {fx1.state} TF: {label}')
def print_klc(self, df, label):
klc_list = self.chan.get_full_klc_list(df)
log_str = f""
for index in range(len(klc_list)-5, len(klc_list)):
klc = klc_list[index]
fx = str(klc.fx).replace("Chan_FX_TYPE.", "")
bi_dir = str(klc.bi.dir).replace("Chan_BI_DIR.", "")
klc_fx_type = str(klc.klc_fx_type).replace("Chan_KLC_FX.", "")
if klc.end_time:
log_str += f"{klc.end_time}E, {bi_dir}, {klc_fx_type}, "
else:
log_str += f"{klc.start_time}S, {bi_dir}, {klc_fx_type}, "
logger.info(label+log_str)
def print_fx_list(self, df): def print_fx_list(self, df):
bsp_list = self.chan.get_bsp_list(self.chan.get_klc_list(df)) bsp_list = self.chan.get_bsp_list(self.chan.get_klc_list(df))
for bsp in bsp_list: for bsp in bsp_list:
@@ -336,9 +350,9 @@ class ChanLun_SOL_5(IStrategy):
cn3 = 'resample_{}_state'.format(self.get_ticker_indicator()*time) cn3 = 'resample_{}_state'.format(self.get_ticker_indicator()*time)
logger.info(f'{df[cn1][index]}, {df[cn2][index]}, {df[cn3][index]}') logger.info(f'{df[cn1][index]}, {df[cn2][index]}, {df[cn3][index]}')
def add_indicators(self, df): def add_indicators(self, df):
fast = 8 fast = 9
slow = 16 slow = 24
period = 6 period = 14
macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period) macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period)
df['macd'] = macd['macd'] df['macd'] = macd['macd']
df['macdsignal'] = macd['macdsignal'] df['macdsignal'] = macd['macdsignal']
+16 -3
View File
@@ -128,6 +128,7 @@ def get_kl_data(symbol, timeframe, limit=1000, start_time=None, end_time=None):
# 按时间排序 # 按时间排序
df = df.sort_values('timestamp') df = df.sort_values('timestamp')
"""
chan = ChanLun() chan = ChanLun()
klc_list = chan.get_klc_list(df) klc_list = chan.get_klc_list(df)
klc_index = 0 klc_index = 0
@@ -140,13 +141,14 @@ def get_kl_data(symbol, timeframe, limit=1000, start_time=None, end_time=None):
if index == klc.start_klu.index: if index == klc.start_klu.index:
ret_df.loc[klc_index] = df_copy.loc[index] ret_df.loc[klc_index] = df_copy.loc[index]
klc_index += 1 klc_index += 1
"""
# 如果过滤后没有数据,返回None # 如果过滤后没有数据,返回None
if len(ret_df) == 0: if len(df) == 0:
print("过滤后无数据") print("过滤后无数据")
return None return None
print(f"获取到总共 {len(ret_df)} 条数据") print(f"获取到总共 {len(df)} 条数据")
return ret_df return df
except Exception as e: except Exception as e:
print(f"获取数据错误: {e}") print(f"获取数据错误: {e}")
@@ -471,6 +473,9 @@ def analyze():
'direction': convert_direction(bi.dir) 'direction': convert_direction(bi.dir)
} for bi in element_analysis['bi_list'] if bi.end_klc] } for bi in element_analysis['bi_list'] if bi.end_klc]
# 添加小周期K线数据
result['element_kline_data'] = element_df.to_dict('records')
result['element_seg_list'] = [{ result['element_seg_list'] = [{
'start_time': seg.start_bi.start_klc.end_time if isinstance(seg.start_bi.start_klc.end_time, str) else seg.start_bi.start_klc.end_time.astimezone(client_tz).isoformat(), 'start_time': seg.start_bi.start_klc.end_time if isinstance(seg.start_bi.start_klc.end_time, str) else seg.start_bi.start_klc.end_time.astimezone(client_tz).isoformat(),
'end_time': (seg.end_bi.end_klc.end_time if isinstance(seg.end_bi.end_klc.end_time, str) else seg.end_bi.end_klc.end_time.astimezone(client_tz).isoformat()) if seg.end_bi else None, 'end_time': (seg.end_bi.end_klc.end_time if isinstance(seg.end_bi.end_klc.end_time, str) else seg.end_bi.end_klc.end_time.astimezone(client_tz).isoformat()) if seg.end_bi else None,
@@ -503,6 +508,14 @@ def analyze():
'desc': point['desc'] 'desc': point['desc']
} for point in element_analysis['trade_points']] } for point in element_analysis['trade_points']]
# 添加小周期分型信息
result['element_klc_fx_info'] = [{
'time': format_time_safely(point['time'], client_tz),
'price': point['price'],
'fx_type': point['fx_type'],
'is_bottom': point['is_bottom']
} for point in element_analysis['klc_fx_info']]
print(f"小周期分析完成: {element_timeframe}, 笔数量: {len(result['element_bi_list'])}, {'仅元素数据' if elements_only else '包含主周期数据'}") print(f"小周期分析完成: {element_timeframe}, 笔数量: {len(result['element_bi_list'])}, {'仅元素数据' if elements_only else '包含主周期数据'}")
else: else:
print(f"无法获取小周期数据: {element_timeframe}") print(f"无法获取小周期数据: {element_timeframe}")
+13 -5
View File
@@ -1,5 +1,13 @@
flask==2.0.1 flask>=2.0.1
ccxt==4.4.70 ccxt>=4.4.70
pandas==1.3.3 pandas>=1.3.3
numpy==1.21.2 numpy>=1.21.2
plotly==5.3.1 plotly>=5.3.1
matplotlib>=3.4.3
pytz>=2021.1
python-dateutil>=2.8.2
xgboost>=1.5.0
scikit-learn>=1.0.1
ta-lib>=0.4.19
bootstrap-flask>=2.0.0
gunicorn>=20.1.0
+241 -43
View File
@@ -5,10 +5,12 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet"> <link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet"> <link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- TradingView Widget BEGIN --> <!-- TradingView Widget BEGIN -->
<script src="https://cdn.jsdelivr.net/npm/lightweight-charts@4.0.1/dist/lightweight-charts.standalone.production.js"></script> <script src="https://cdn.jsdelivr.net/npm/lightweight-charts@4.0.1/dist/lightweight-charts.standalone.production.js"></script>
<!-- TradingView Widget END --> <!-- TradingView Widget END -->
@@ -271,6 +273,23 @@
<input class="form-check-input" type="checkbox" id="showOriginalKline" checked> <input class="form-check-input" type="checkbox" id="showOriginalKline" checked>
<label class="form-check-label" for="showOriginalKline">原始K线</label> <label class="form-check-label" for="showOriginalKline">原始K线</label>
</div> </div>
<!-- 添加K线周期切换 -->
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="klinePeriod" id="mainPeriodKline" checked>
<label class="form-check-label" for="mainPeriodKline">主周期</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="klinePeriod" id="elementPeriodKline">
<label class="form-check-label" for="elementPeriodKline">小周期</label>
<i class="bi bi-info-circle" data-bs-toggle="tooltip" title="显示小周期K线,同时可以叠加大周期分型和笔段"></i>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="showVolume" checked>
<label class="form-check-label" for="showVolume">成交量</label>
</div>
<div class="form-check form-check-inline"> <div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="showMacd" checked> <input class="form-check-input" type="checkbox" id="showMacd" checked>
<label class="form-check-label" for="showMacd">MACD</label> <label class="form-check-label" for="showMacd">MACD</label>
@@ -279,8 +298,15 @@
<input class="form-check-input" type="checkbox" id="showKlcFxType"> <input class="form-check-input" type="checkbox" id="showKlcFxType">
<label class="form-check-label" for="showKlcFxType">分型类型</label> <label class="form-check-label" for="showKlcFxType">分型类型</label>
</div> </div>
<div class="form-check form-check-inline" style="display: none;">
<input class="form-check-input" type="checkbox" id="showTradePoints"> <!-- 添加小周期分型显示控制 -->
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="showElementKlcFxType" checked>
<label class="form-check-label" for="showElementKlcFxType">小周期分型</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="showTradePoints" checked>
<label class="form-check-label" for="showTradePoints">买卖点</label> <label class="form-check-label" for="showTradePoints">买卖点</label>
</div> </div>
</div> </div>
@@ -731,7 +757,7 @@
// 添加买卖点复选框变更事件 // 添加买卖点复选框变更事件
$('#showTradePoints').change(function() { $('#showTradePoints').change(function() {
updateChartDisplay(); refreshChart(currentData);
}); });
// 添加分型类型复选框变更事件 // 添加分型类型复选框变更事件
@@ -924,8 +950,11 @@
console.log('- 显示中枢:', $('#showMainZs').is(':checked')); console.log('- 显示中枢:', $('#showMainZs').is(':checked'));
console.log('- 显示未完成中枢:', $('#showMainUncompletedZs').is(':checked')); console.log('- 显示未完成中枢:', $('#showMainUncompletedZs').is(':checked'));
console.log('- 显示MACD:', $('#showMacd').is(':checked')); console.log('- 显示MACD:', $('#showMacd').is(':checked'));
console.log('- 显示买卖点:', $('#showTradePoints').is(':checked')); console.log('- 显示成交量:', $('#showVolume').is(':checked'));
console.log('- 显示分型类型:', $('#showKlcFxType').is(':checked')); console.log('- 显示分型类型:', $('#showKlcFxType').is(':checked'));
console.log('- 显示小周期分型:', $('#showElementKlcFxType').is(':checked'));
console.log('- 显示买卖点:', $('#showTradePoints').is(':checked'));
console.log('- 显示原始K线:', $('#showOriginalKline').is(':checked'));
// 重新初始化图表,这将清除旧图形并重新绘制 // 重新初始化图表,这将清除旧图形并重新绘制
initTradingView($('#symbol').val(), $('#timeframe').val()); initTradingView($('#symbol').val(), $('#timeframe').val());
@@ -1212,18 +1241,42 @@
macdChart = LightweightCharts.createChart(macdChartContainer, createChartOptions(false)); macdChart = LightweightCharts.createChart(macdChartContainer, createChartOptions(false));
} }
// 转换K线数据 - 始终使用主时间周期数据 // 转换K线数据 - 根据选中的周期使用主周期或小周期数据
const candles = currentData.kline_data.map((kline) => { let candles;
const date = new Date(kline.date); const useElementPeriod = $('#elementPeriodKline').is(':checked') &&
const timestamp = date.getTime() / 1000; currentData.element_timeframe &&
return { currentData.element_kline_data;
time: timestamp,
open: parseFloat(kline.open), // 输出K线周期选择状态
high: parseFloat(kline.high), console.log('K线周期选择:', useElementPeriod ? '小周期' : '主周期');
low: parseFloat(kline.low),
close: parseFloat(kline.close), if (useElementPeriod) {
}; // 使用小周期K线数据
}); candles = currentData.element_kline_data.map((kline) => {
const date = new Date(kline.date);
const timestamp = date.getTime() / 1000;
return {
time: timestamp,
open: parseFloat(kline.open),
high: parseFloat(kline.high),
low: parseFloat(kline.low),
close: parseFloat(kline.close),
};
});
} else {
// 使用主周期K线数据
candles = currentData.kline_data.map((kline) => {
const date = new Date(kline.date);
const timestamp = date.getTime() / 1000;
return {
time: timestamp,
open: parseFloat(kline.open),
high: parseFloat(kline.high),
low: parseFloat(kline.low),
close: parseFloat(kline.close),
};
});
}
// 创建蜡烛图系列并设置数据 // 创建蜡烛图系列并设置数据
if (showOriginalKline) { if (showOriginalKline) {
@@ -1257,14 +1310,23 @@
} }
// 转换成交量数据 - 始终使用主K线周期数据 // 转换成交量数据 - 始终使用主K线周期数据
const volumes = currentData.kline_data.map(kline => { const volumes = useElementPeriod ?
const timestamp = Math.floor(new Date(kline.date).getTime() / 1000); currentData.element_kline_data.map(kline => {
return { const timestamp = Math.floor(new Date(kline.date).getTime() / 1000);
time: timestamp, return {
value: parseFloat(kline.volume), time: timestamp,
color: parseFloat(kline.close) >= parseFloat(kline.open) ? 'rgba(220, 53, 69, 0.5)' : 'rgba(40, 167, 69, 0.5)', value: parseFloat(kline.volume),
}; color: parseFloat(kline.close) >= parseFloat(kline.open) ? 'rgba(220, 53, 69, 0.5)' : 'rgba(40, 167, 69, 0.5)',
}); };
}) :
currentData.kline_data.map(kline => {
const timestamp = Math.floor(new Date(kline.date).getTime() / 1000);
return {
time: timestamp,
value: parseFloat(kline.volume),
color: parseFloat(kline.close) >= parseFloat(kline.open) ? 'rgba(220, 53, 69, 0.5)' : 'rgba(40, 167, 69, 0.5)',
};
});
// 添加成交量图表 // 添加成交量图表
const volumeSeries = volumeChart.addHistogramSeries({ const volumeSeries = volumeChart.addHistogramSeries({
@@ -2440,6 +2502,66 @@
console.log('绘制分型类型标签 - 已禁用或无数据'); console.log('绘制分型类型标签 - 已禁用或无数据');
} }
// 绘制小周期分型标记
if ($('#showElementKlcFxType').is(':checked') && currentData.element_klc_fx_info && currentData.element_klc_fx_info.length > 0) {
console.log(`绘制小周期分型标记,共${currentData.element_klc_fx_info.length}条`);
currentData.element_klc_fx_info.forEach(function(fx) {
try {
// 直接使用UTC时间戳(秒)
const timestamp = Math.floor(new Date(fx.time).getTime() / 1000);
const price = parseFloat(fx.price);
if (isNaN(timestamp) || isNaN(price)) {
console.error('小周期分型时间或价格转换错误:', fx.time, fx.price);
return;
}
// 小周期分型使用红色标记,不同于主周期分型
const redColor = '#FF0000'; // 红色
// 创建标记系列
const markerSeries = mainChart.addLineSeries({
lastValueVisible: false,
priceLineVisible: false,
});
// 设置文本标记
markerSeries.setMarkers([
{
time: timestamp,
position: fx.is_bottom ? 'belowBar' : 'aboveBar',
color: redColor,
shape: 'arrowUp', // 使用箭头形状,与主周期分型区分
text: fx.is_bottom ? '↓' : '↑', // 显示箭头
size: 1
}
]);
// 为小周期分型添加明显的箭头标记
const arrowSeries = mainChart.addLineSeries({
lastValueVisible: false,
priceLineVisible: false,
lineWidth: 1,
color: redColor
});
// 计算标记位置,底分型在价格下方,顶分型在价格上方
const offset = fx.is_bottom ? -0.001 * price : 0.001 * price;
arrowSeries.setData([{
time: timestamp,
value: price + offset
}]);
} catch (e) {
console.error('绘制小周期分型标记出错:', e);
}
});
} else {
console.log('绘制小周期分型标记 - 已禁用或无数据');
}
// 调整所有图表以适应数据 // 调整所有图表以适应数据
mainChart.timeScale().fitContent(); mainChart.timeScale().fitContent();
volumeChart.timeScale().fitContent(); volumeChart.timeScale().fitContent();
@@ -2487,18 +2609,40 @@
// 检查是否显示原始K线 // 检查是否显示原始K线
const showOriginalKline = $('#showOriginalKline').is(':checked'); const showOriginalKline = $('#showOriginalKline').is(':checked');
// 检查是否使用小周期数据
const useElementPeriod = $('#elementPeriodKline').is(':checked') &&
currentData.element_timeframe &&
currentData.element_kline_data;
// 转换K线数据 // 转换K线数据
const candles = currentData.kline_data.map((kline) => { let candles;
const date = new Date(kline.date); if (useElementPeriod) {
const timestamp = date.getTime() / 1000; console.log('使用小周期K线数据');
return { candles = currentData.element_kline_data.map((kline) => {
time: timestamp, const date = new Date(kline.date);
open: parseFloat(kline.open), const timestamp = date.getTime() / 1000;
high: parseFloat(kline.high), return {
low: parseFloat(kline.low), time: timestamp,
close: parseFloat(kline.close), open: parseFloat(kline.open),
}; high: parseFloat(kline.high),
}); low: parseFloat(kline.low),
close: parseFloat(kline.close),
};
});
} else {
console.log('使用主周期K线数据');
candles = currentData.kline_data.map((kline) => {
const date = new Date(kline.date);
const timestamp = date.getTime() / 1000;
return {
time: timestamp,
open: parseFloat(kline.open),
high: parseFloat(kline.high),
low: parseFloat(kline.low),
close: parseFloat(kline.close),
};
});
}
// 更新K线数据 // 更新K线数据
if (showOriginalKline && tvWidget.series.candleSeries) { if (showOriginalKline && tvWidget.series.candleSeries) {
@@ -2514,14 +2658,23 @@
} }
// 更新成交量数据 // 更新成交量数据
const volumes = currentData.kline_data.map(kline => { const volumes = useElementPeriod ?
const timestamp = Math.floor(new Date(kline.date).getTime() / 1000); currentData.element_kline_data.map(kline => {
return { const timestamp = Math.floor(new Date(kline.date).getTime() / 1000);
time: timestamp, return {
value: parseFloat(kline.volume), time: timestamp,
color: parseFloat(kline.close) >= parseFloat(kline.open) ? 'rgba(220, 53, 69, 0.5)' : 'rgba(40, 167, 69, 0.5)', value: parseFloat(kline.volume),
}; color: parseFloat(kline.close) >= parseFloat(kline.open) ? 'rgba(220, 53, 69, 0.5)' : 'rgba(40, 167, 69, 0.5)',
}); };
}) :
currentData.kline_data.map(kline => {
const timestamp = Math.floor(new Date(kline.date).getTime() / 1000);
return {
time: timestamp,
value: parseFloat(kline.volume),
color: parseFloat(kline.close) >= parseFloat(kline.open) ? 'rgba(220, 53, 69, 0.5)' : 'rgba(40, 167, 69, 0.5)',
};
});
if (tvWidget.series.volumeSeries) { if (tvWidget.series.volumeSeries) {
tvWidget.series.volumeSeries.setData(volumes); tvWidget.series.volumeSeries.setData(volumes);
@@ -3572,6 +3725,51 @@
// 更新表格数据 // 更新表格数据
updateTables(data); updateTables(data);
} }
// 绑定分型类型显示开关
$('#showKlcFxType').change(function() {
refreshChart(currentData);
});
// 绑定小周期分型显示开关
$('#showElementKlcFxType').change(function() {
refreshChart(currentData);
});
// 绑定买卖点显示开关
$('#showTradePoints').change(function() {
refreshChart(currentData);
});
// 绑定K线周期切换
$('input[name="klinePeriod"]').change(function() {
refreshChart(currentData);
});
// 在控制台输出当前显示状态
console.log('当前显示状态:', {
'showOriginalKline': $('#showOriginalKline').is(':checked'),
'showMainBi': $('#showMainBi').is(':checked'),
'showMainSeg': $('#showMainSeg').is(':checked'),
'showMainZs': $('#showMainZs').is(':checked'),
'showMainUncompletedZs': $('#showMainUncompletedZs').is(':checked'),
'showVolume': $('#showVolume').is(':checked'),
'showMacd': $('#showMacd').is(':checked'),
'showKlcFxType': $('#showKlcFxType').is(':checked'),
'showElementKlcFxType': $('#showElementKlcFxType').is(':checked'),
'showTradePoints': $('#showTradePoints').is(':checked'),
'timeframe': $('#timeframe').val(),
'elementTimeframe': $('#elementTimeframe').val(),
'timezone': $('#timezone').val(),
'start_time': $('#start_time').val(),
'end_time': $('#end_time').val()
});
// 初始化提示工具
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script> </script>
</body> </body>
</html> </html>