Files
Chan/strategies/EMA26_EMA52_Cross.py
T

183 lines
7.7 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
# --------------------------------
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=20260101-
# freqtrade download-data -c ./user_data/Chan/config/Local_Test.json -t 1m 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 EMA26_EMA52_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.15,
"500": 0.2,
"1200": 0.1,
"1800": 0.08,
"2400": 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 = 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
time5 = 5
time15 = 15
time30 = 30
time60 = 60
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe_15m = resample_to_interval(dataframe, self.get_ticker_indicator() * self.time15)
dataframe_30m = resample_to_interval(dataframe, self.get_ticker_indicator() * self.time30)
dataframe_60m = resample_to_interval(dataframe, self.get_ticker_indicator() * self.time60)
dataframe_15m = self.add_indicators(dataframe_15m)
dataframe_30m = self.add_indicators(dataframe_30m)
dataframe_60m = self.add_indicators(dataframe_60m)
dataframe = self.add_indicators(dataframe)
dataframe = resampled_merge(dataframe, dataframe_15m)
dataframe = resampled_merge(dataframe, dataframe_30m)
dataframe = resampled_merge(dataframe, dataframe_60m)
return dataframe
def add_indicators(self, dataframe):
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))
)
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 - 10
else:
new_entryprice = proposed_rate + 10
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 + 10
else:
new_exitprice = proposed_rate - 10
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:
time = self.time30
cross_up = 'resample_{}_ema26_cross_up_52'.format(self.get_ticker_indicator() * time)
cross_down = 'resample_{}_ema26_cross_down_52'.format(self.get_ticker_indicator() * time)
#time = 1
#cross_up = 'ema26_cross_up_52'
#cross_down = 'ema26_cross_down_52'
dataframe.loc[
(dataframe[cross_up].shift(time) == True),
['enter_long', 'enter_tag']] = (1, 'long_signal')
dataframe.loc[
(dataframe[cross_down].shift(time) == True),
['enter_short', 'enter_tag']] = (1, 'short_signal')
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
time = self.time30
cross_up = 'resample_{}_ema26_cross_up_52'.format(self.get_ticker_indicator() * time)
cross_down = 'resample_{}_ema26_cross_down_52'.format(self.get_ticker_indicator() * time)
#time = 1
#cross_up = 'ema26_cross_up_52'
#cross_down = 'ema26_cross_down_52'
dataframe.loc[
(dataframe[cross_down].shift(time) == True),
['exit_long', 'exit_tag']] = (1, 'long_signal')
dataframe.loc[
(dataframe[cross_up].shift(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])