Files
jackyu66gitandCursor 74dec4e50b refactor: 缠论引擎包化与 Web 分层(ECR-001)
将根目录引擎迁入 chanlun/ 并保留兼容 shim;拆分 TF_DF 与 web 服务;
前端模块化;strategies 改用 chanlun 导入;补充 ESS 文档与 golden 回归。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 18:48:20 +08:00

197 lines
8.2 KiB
Python

# --- Do not remove these libs ---
from statistics import median
from freqtrade.strategy import IStrategy, stoploss_from_absolute
import sys
import os
# 添加父目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from chanlun import ChanLun
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLC_FX, Chan_BI_DIR, Chan_KLC_FX
# --------------------------------
from technical.util import resample_to_interval, resampled_merge
import talib.abstract as ta
from pandas import DataFrame
import pandas as pd
from datetime import datetime, timedelta
from freqtrade.persistence import Trade, Order
from typing import Optional
import logging
logger = logging.getLogger(__name__)
### Now you can use logger.info('asfd') to log
# freqtrade plot-dataframe --strategy ChanLun_BTC --datadir user_data/data/binance -c ./user_data/ChanLun_SOL_30.json --timerange=20250309-
# freqtrade trade -c ./user_data/Chan/config/Local_Test.json --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies
# freqtrade backtesting -c ./user_data/Chan/config/Local_Test.json --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies --timerange=20260304-
# freqtrade download-data -c ./user_data/Chan/config/Local_Test.json -t 1m 5m 15m 1h 1d 1w 1M --pairs SOL/USDT:USDT --timerange=20240101-
# freqtrade download-data -c ./user_data/Chan/config/Local_Test.json -t 1m 1h 1d 1M --pairs SOL/USDT:USDT --timerange=20170101-
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies -c ./user_data/Chan/config/Local_Test.json -e 200 --timerange=20250201-20250901
# freqtrade edge -c ./user_data/Chan/config/Local_Test.json --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901
# freqtrade plot-dataframe -c ./user_data/Chan/config/Local_Test.json --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901
# sudo docker compose run --rm chanlun_btc backtesting -c ./user_data/Chan/config/EMA26_EMA52_Cross.json --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies --timerange=20250721-
# sudo docker compose run --rm chanlun_btc download-data -c ./user_data/Chan/config/EMA26_EMA52_Cross.json --pairs BTC/USDT:USDT -t 1m --timerange 20240101-
# sudo docker compose run --rm chanlun_btc trade -c ./user_data/Chan/config/EMA26_EMA52_Cross.json --strategy EMA26_EMA52_Cross --strategy-path ./user_data/Chan/strategies
class EMA_Cross(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.05,
"50": 0.025,
"120": 0.015,
"180": 0.01,
"240": 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.1 # 设置为很大的负值,让custom_stoploss来控制
use_custom_stoploss = False # 启用自定义止损
startup_candle_count = 1600
trailing_stop = False
trailing_stop_positive = 0.03
trailing_stop_positive_offset = 0.06
trailing_only_offset_is_reached = False
price_offset = 0.01
df_dict = {}
tf_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 30]
time = 30
startup_candle_count: int = 1100
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe = self.merge_df_dict(dataframe)
return dataframe
def merge_df_dict(self, dataframe):
df_dict = self.init_df_dict(dataframe)
for tf in df_dict.keys():
dataframe = resampled_merge(dataframe, df_dict[tf])
return dataframe
def init_df_dict(self, dataframe):
df_dict = {}
if len(dataframe) > 1000:
for tf in self.tf_list:
df_dict[tf] = resample_to_interval(dataframe, self.get_ticker_indicator() * tf)
df_dict[tf] = self.add_indicators(df_dict[tf])
return df_dict
def add_indicators(self, dataframe):
dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
dataframe['ema13'] = ta.EMA(dataframe, timeperiod=26)
dataframe['ema26'] = ta.EMA(dataframe, timeperiod=26)
dataframe['ema52'] = ta.EMA(dataframe, timeperiod=52)
# 上穿:本根 26 > 52,上一根 26 ≤ 52
dataframe['ema26_cross_up_52'] = (
(dataframe['ema26'] > dataframe['ema52']) &
(dataframe['ema26'].shift(1) <= dataframe['ema52'].shift(1))
)
# 下穿:本根 26 < 52,上一根 26 ≥ 52
dataframe['ema26_cross_down_52'] = (
(dataframe['ema26'] < dataframe['ema52']) &
(dataframe['ema26'].shift(1) >= dataframe['ema52'].shift(1))
)
# 上穿:本根 2 > 13,上一根 2 ≤ 13
dataframe['ema5_cross_up_13'] = (
(dataframe['ema5'] > dataframe['ema13']) &
(dataframe['ema5'].shift(1) <= dataframe['ema13'].shift(1))
)
# 下穿:本根 2 < 13,上一根 2 ≥ 13
dataframe['ema5_cross_down_13'] = (
(dataframe['ema5'] < dataframe['ema13']) &
(dataframe['ema5'].shift(1) >= dataframe['ema13'].shift(1))
)
dataframe_macd = ta.MACD(dataframe, fast=12, slow=26, signal=9)
dataframe['macdsignal'] = dataframe_macd['macdsignal']
dataframe['macd'] = dataframe_macd['macd']
dataframe['macdhist'] = dataframe_macd['macdhist']
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 - self.price_offset
else:
new_entryprice = proposed_rate + self.price_offset
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 + self.price_offset
else:
new_exitprice = proposed_rate - self.price_offset
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_exit(self, pair: str, trade: Trade, current_time: datetime, current_rate: float,
current_profit: float, **kwargs):
# 不做分批止盈/最终止盈处理,退出由策略信号/ROI/止损决定
return None
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
cross_up = 'resample_{}_ema26_cross_up_52'.format(self.get_ticker_indicator() * self.time)
cross_down = 'resample_{}_ema26_cross_down_52'.format(self.get_ticker_indicator() * self.time)
#time = 1
#cross_up = 'ema26_cross_up_52'
#cross_down = 'ema26_cross_down_52'
dataframe.loc[
(dataframe[cross_up].shift(self.time) == True),
['enter_long', 'enter_tag']] = (1, 'long_signal')
dataframe.loc[
(dataframe[cross_down].shift(self.time) == True),
['enter_short', 'enter_tag']] = (1, 'short_signal')
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
cross_up = 'resample_{}_ema26_cross_up_52'.format(self.get_ticker_indicator() * self.time)
cross_down = 'resample_{}_ema26_cross_down_52'.format(self.get_ticker_indicator() * self.time)
#time = 1
#cross_up = 'ema26_cross_up_52'
#cross_down = 'ema26_cross_down_52'
dataframe.loc[
(dataframe[cross_down].shift(self.time) == True),
['exit_long', 'exit_tag']] = (1, 'long_signal')
dataframe.loc[
(dataframe[cross_up].shift(self.time) == True),
['exit_short', 'exit_tag']] = (1, 'short_signal')
return dataframe
def leverage(self, pair: str, current_time: datetime, current_rate: float,
proposed_leverage: float, max_leverage: float, entry_tag: Optional[str], side: str,
**kwargs) -> float:
return self.lev
def get_ticker_indicator(self):
return int(self.timeframe[:-1])