新的策略,先开单,明天继续添加条件
This commit is contained in:
@@ -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