213 lines
9.8 KiB
Python
213 lines
9.8 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 ChanEnum import Chan_FX_TYPE, Chan_KLC_FX, Chan_BI_DIR, Chan_KLC_FX, Chan_BSP_TYPE
|
|
# --------------------------------
|
|
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 typing import Optional
|
|
import logging
|
|
logger = logging.getLogger(__name__)
|
|
### Now you can use logger.info('asfd') to log
|
|
# freqtrade plot-dataframe --strategy ChanLun_BTC_1m --datadir user_data/data/binance -c ./user_data/ChanLun_SOL_30.json --timerange=20250309-
|
|
|
|
# freqtrade trade -c ./user_data/Chan/config/ChanLun_BTC_1m.json --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies
|
|
# freqtrade backtesting -c ./user_data/Chan/config/ChanLun_BTC_1m.json --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies --timerange=20260501-
|
|
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_1m.json -t 1m 1m 1h 1d 1M --pairs BTC/USDT:USDT --timerange=20250405-
|
|
# freqtrade download-data -c ./user_data/Chan/config/ChanLun_BTC_1m.json -t 1m 1h 1d 1M --pairs BTC/USDT --timerange=20170101-
|
|
# freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies -c ./user_data/Chan/config/ChanLun_BTC_1m.json -e 200 --timerange=20250201-20250901
|
|
# freqtrade edge -c ./user_data/Chan/config/ChanLun_BTC_1m.json --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901
|
|
# freqtrade plot-dataframe -c ./user_data/Chan/config/ChanLun_BTC_1m.json --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies --timerange 20250721-20250901
|
|
|
|
# sudo docker compose run --rm chanlun_btc backtesting -c ./user_data/Chan/config/ChanLun_BTC_1m.json --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies --timerange=20250721-
|
|
# sudo docker compose run --rm chanlun_btc download-data -c ./user_data/Chan/config/ChanLun_BTC_1m.json --pairs BTC/USDT:USDT -t 1m --timerange 20240101-
|
|
# sudo docker compose run --rm chanlun_btc trade -c ./user_data/Chan/config/ChanLun_BTC_1m.json --strategy ChanLun_BTC_1m --strategy-path ./user_data/Chan/strategies
|
|
|
|
class ChanLun_BTC_1m(IStrategy):
|
|
"""
|
|
交易核心(缠论):
|
|
- 仅在缠论一/二/三类买卖点出现时交易。
|
|
- 信号触发条件:前一笔被确认(bi.is_sure)时,该笔 end_klc 已被标记为 B1/B2/B3 或 S1/S2/S3。
|
|
- 不使用未确认笔,不使用“状态猜测”列。
|
|
"""
|
|
INTERFACE_VERSION: int = 3
|
|
timeframe = '1m'
|
|
# Minimal ROI designed for the strategy.
|
|
# This attribute will be overridden if the config file contains "minimal_roi"
|
|
minimal_roi = {
|
|
"0": 100
|
|
}
|
|
|
|
can_short = True
|
|
enable_long = True
|
|
enable_short = False
|
|
lev = 1.0
|
|
stoploss = -0.3 # 兜底止损,实际由 custom_stoploss 基于中枢 zg/zd 控制
|
|
use_custom_stoploss = True
|
|
|
|
trailing_stop = False
|
|
trailing_stop_positive = 0.03
|
|
trailing_stop_positive_offset = 0.06
|
|
trailing_only_offset_is_reached = False
|
|
use_exit_signal = True
|
|
position_adjustment_enable = True
|
|
startup_candle_count = 500
|
|
# 以 1m 为基础周期时,1h = 60 根K线(用于读取 resample_60_* 列并做确认延迟)
|
|
chan = ChanLun()
|
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
dataframe = self.add_indicators(dataframe)
|
|
bsp_signal_data = self.chan.get_bsp_signal_data(dataframe)
|
|
for column, values in bsp_signal_data.items():
|
|
dataframe[column] = values
|
|
return dataframe
|
|
def add_indicators(self, df):
|
|
df = self.add_base_indicators(df)
|
|
base_interval = self.get_ticker_indicator()
|
|
for interval in (5, 15, 60):
|
|
if interval <= base_interval:
|
|
df = self.copy_base_indicators_to_resample(df, interval)
|
|
continue
|
|
resampled = resample_to_interval(df, interval)
|
|
resampled = self.add_base_indicators(resampled)
|
|
df = resampled_merge(df, resampled)
|
|
return df
|
|
def copy_base_indicators_to_resample(self, df, interval):
|
|
prefix = f'resample_{interval}_'
|
|
for column in (
|
|
'date', 'open', 'high', 'low', 'close', 'volume',
|
|
'atr', 'macd', 'macdsignal', 'macdhist', 'ema24', 'ema52',
|
|
'atr_ratio', 'resistance_240', 'support_240', 'trend'
|
|
):
|
|
if column in df.columns:
|
|
df[f'{prefix}{column}'] = df[column]
|
|
return df
|
|
def add_base_indicators(self, df):
|
|
fast = 12
|
|
slow = 26
|
|
period = 9
|
|
macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period)
|
|
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['atr_ratio'] = df['atr'] / df['close']
|
|
df['resistance_240'] = df['high'].rolling(240).max().shift(1)
|
|
df['support_240'] = df['low'].rolling(240).min().shift(1)
|
|
df['trend'] = 0
|
|
df.loc[(df['close'] > df['ema52']) & (df['ema24'] >= df['ema52']), 'trend'] = 1
|
|
df.loc[(df['close'] < df['ema52']) & (df['ema24'] <= df['ema52']), 'trend'] = -1
|
|
return df
|
|
|
|
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
min_atr_ratio = 0.0005
|
|
long_min_sr_distance_r = 1.0
|
|
short_min_sr_distance_r = 0.8
|
|
long_space_ratio = (dataframe['resistance_240'].shift(1) - dataframe['close'].shift(1)) / dataframe['close'].shift(1)
|
|
short_space_ratio = (dataframe['close'].shift(1) - dataframe['support_240'].shift(1)) / dataframe['close'].shift(1)
|
|
# 多周期趋势共振:3个周期中至少2个同向(而非全部3个)
|
|
long_tf_aligned = (
|
|
(dataframe['resample_5_trend'].shift(1) == 1).astype(int) +
|
|
(dataframe['resample_15_trend'].shift(1) == 1).astype(int) +
|
|
(dataframe['resample_60_trend'].shift(1) == 1).astype(int)
|
|
) >= 2
|
|
short_tf_aligned = (
|
|
(dataframe['resample_5_trend'].shift(1) == -1).astype(int) +
|
|
(dataframe['resample_15_trend'].shift(1) == -1).astype(int) +
|
|
(dataframe['resample_60_trend'].shift(1) == -1).astype(int)
|
|
) >= 2
|
|
dataframe.loc[
|
|
(
|
|
self.enable_long &
|
|
(dataframe['bsp_state'].shift(1) == -1) &
|
|
(dataframe['bsp_risk_ratio'].shift(1) > 0) &
|
|
(long_space_ratio >= dataframe['bsp_risk_ratio'].shift(1) * long_min_sr_distance_r) &
|
|
(dataframe['macdhist'].shift(1) > 0) &
|
|
(dataframe['atr_ratio'].shift(1) >= min_atr_ratio) &
|
|
(dataframe['trend'].shift(1) == 1) &
|
|
long_tf_aligned
|
|
),
|
|
['enter_long', 'enter_tag']] = (1, 'long_signal_chan')
|
|
dataframe.loc[
|
|
(
|
|
self.enable_short &
|
|
(dataframe['bsp_state'].shift(1) == 1) &
|
|
(dataframe['bsp_risk_ratio'].shift(1) > 0) &
|
|
(short_space_ratio >= dataframe['bsp_risk_ratio'].shift(1) * short_min_sr_distance_r) &
|
|
(dataframe['macdhist'].shift(1) < 0) &
|
|
(dataframe['atr_ratio'].shift(1) >= min_atr_ratio) &
|
|
(dataframe['trend'].shift(1) == -1) &
|
|
short_tf_aligned
|
|
),
|
|
['enter_short', 'enter_tag']] = (1, 'short_signal_chan')
|
|
return dataframe
|
|
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
dataframe['exit_long'] = 0
|
|
dataframe['exit_short'] = 0
|
|
return dataframe
|
|
def get_trade_risk_ratio(self, pair: str, trade) -> float:
|
|
risk_ratio = trade.get_custom_data('risk_ratio')
|
|
if risk_ratio:
|
|
return float(risk_ratio)
|
|
|
|
risk_ratio = 0.001
|
|
try:
|
|
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
|
if len(dataframe) > 0:
|
|
entry_rows = dataframe[dataframe['date'] <= trade.open_date_utc]
|
|
entry_candle = entry_rows.iloc[-1] if len(entry_rows) > 0 else dataframe.iloc[-1]
|
|
signal_rows = entry_rows.tail(3)
|
|
signal_rows = signal_rows[signal_rows['bsp_risk_ratio'] > 0]
|
|
if len(signal_rows) > 0:
|
|
signal_candle = signal_rows.iloc[-1]
|
|
risk_ratio = float(signal_candle['bsp_risk_ratio'])
|
|
trade.set_custom_data('bsp_stop_price', float(signal_candle['bsp_stop_price']))
|
|
trade.set_custom_data('bsp_zg', float(signal_candle['bsp_zg']))
|
|
trade.set_custom_data('bsp_zd', float(signal_candle['bsp_zd']))
|
|
else:
|
|
risk_ratio = max(0.001, min(float(entry_candle['atr_ratio']), 0.005))
|
|
except Exception:
|
|
risk_ratio = 0.001
|
|
|
|
trade.set_custom_data('risk_ratio', risk_ratio)
|
|
return risk_ratio
|
|
def adjust_trade_position(self, 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):
|
|
risk_ratio = self.get_trade_risk_ratio(trade.pair, trade)
|
|
if current_profit >= risk_ratio and trade.nr_of_successful_exits == 0:
|
|
return -(trade.stake_amount / 2), 'take_half_1r'
|
|
return None
|
|
def custom_exit(self, pair: str, trade, current_time: datetime, current_rate: float,
|
|
current_profit: float, **kwargs):
|
|
risk_ratio = self.get_trade_risk_ratio(pair, trade)
|
|
if trade.nr_of_successful_exits > 0 and current_profit <= 0.001:
|
|
return 'breakeven_after_1r'
|
|
if current_profit >= risk_ratio * 2:
|
|
return 'take_profit_2r'
|
|
return None
|
|
def custom_stoploss(self, pair: str, trade, current_time: datetime, current_rate: float,
|
|
current_profit: float, after_fill: bool, **kwargs) -> float | None:
|
|
bsp_stop_price = trade.get_custom_data('bsp_stop_price')
|
|
if bsp_stop_price:
|
|
sl = stoploss_from_absolute(float(bsp_stop_price), current_rate, is_short=trade.is_short)
|
|
return min(sl, -0.05)
|
|
return -0.05
|
|
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]) |