diff --git a/.DS_Store b/.DS_Store index 6b5a277..19da654 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/ChanLun.py b/ChanLun.py index 14ddabe..c383ff4 100644 --- a/ChanLun.py +++ b/ChanLun.py @@ -126,7 +126,8 @@ class ChanLun(): - + def get_bsp_state(self, dataframe): + return self.tf_df.get_bsp_state(dataframe) def get_structure_zones(self, current_price=None, config=None): if config is None: diff --git a/TF_DF.py b/TF_DF.py index e692bfb..2d1fe47 100644 --- a/TF_DF.py +++ b/TF_DF.py @@ -157,7 +157,40 @@ class TF_DF(): klu_state_list.append("00") print(klu_state_list[:20]) return klu_state_list - + def get_bsp_state(self, dataframe): + klu_list = self.get_klu_list(dataframe) + klc_list = self.get_klc_list(klu_list) + bi_list = self.cal_bi_list(klc_list) + seg_list = self.get_seg_list(bi_list) + bi_zs_list = self.cal_bi_zs(seg_list) + bsp_list = self.find_all_bsp(bi_list, bi_zs_list) + bsp_state_list = [0] * len(dataframe) + klc_index = 0 + for index in range(0, len(dataframe)): + if klc_index == len(klc_list): + klc_index = len(klc_list) - 1 + klc = klc_list[klc_index] + if klc.end_klu and klc.end_klu.idx == index: + if klc.klc_fx_type == Chan_KLC_FX.TOP2: + bi = klc.bi.pre + if bi and bi.is_sure and bi.end_klc.bsp_type == Chan_BSP_TYPE.B3: + # 第三类买点 + bsp_state_list[index] = -1 + #print(klc.end_time, "B3") + else: + bsp_state_list[index] = 0 + elif klc.klc_fx_type == Chan_KLC_FX.BOTTOM2: + bi = klc.bi.pre + if bi and bi.is_sure and bi.end_klc.bsp_type == Chan_BSP_TYPE.S3: + # 第三类卖点 + bsp_state_list[index] = 1 + #print(klc.end_time, "S3") + else: + bsp_state_list[index] = 0 + klc_index += 1 + else: + bsp_state_list[index] = 0 + return bsp_state_list def get_ema_state(self, dataframe): klu_list = self.get_klu_list(dataframe) klc_list = self.get_klc_list(klu_list) @@ -947,7 +980,7 @@ class TF_DF(): bi_list = [] last_top = None last_bottom = None - bi_klc_min = 3 + bi_klc_min = 4 last_fx_klc = None for klc in klc_list: if last_fx_klc: diff --git a/config/ChanLun_BTC_1m.json b/config/ChanLun_BTC_1m.json new file mode 100644 index 0000000..23f7ceb --- /dev/null +++ b/config/ChanLun_BTC_1m.json @@ -0,0 +1,89 @@ +{ + "$schema": "https://schema.freqtrade.io/schema.json", + "max_open_trades": 1, + "stake_currency": "USDT", + "stake_amount": "unlimited", + "tradable_balance_ratio": 0.99, + "fiat_display_currency": "USD", + "dry_run": true, + "db_url": "sqlite:///tradesv3.chanlun_btc_1m.sqlite", + "dry_run_wallet": 1000, + "cancel_open_orders_on_exit": true, + "trading_mode": "futures", + "margin_mode": "isolated", + "can_short" : true, + "timeframe" : "1m", + "process_only_new_candles" : false, + "unfilledtimeout": { + "entry": 1, + "exit": 1, + "exit_timeout_count": 5, + "unit": "minutes" + }, + "order_types": { + "entry": "limit", + "exit": "limit", + "stoploss": "limit", + "stoploss_on_exchange": false + }, + "entry_pricing": { + "price_side": "same", + "use_order_book": true + }, + "exit_pricing": { + "price_side": "same", + "use_order_book": true + }, + "exchange": { + "name": "binance", + "key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8", + "secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l", + "ccxt_config": { + "proxies": { + "http": "http://127.0.0.1:7897", + "https": "http://127.0.0.1:7897" + } + }, + "ccxt_async_config": { + "aiohttp_proxy": "http://127.0.0.1:7897" + }, + "pair_whitelist": [ + "BTC/USDT:USDT" + ], + "pair_blacklist": [ + "BNB/.*" + ] + }, + "pairlists": [ + { + "method": "StaticPairList", + "number_assets": 1, + "sort_key": "quoteVolume", + "min_value": 0, + "refresh_period": 1800 + } + ], + "telegram": { + "enabled": true, + "token": "8197349375:AAH208JghCq8raFYF-IpnobYknCr6iGDH_0", + "chat_id": "580807463" + }, + "api_server": { + "enabled": true, + "listen_ip_address": "0.0.0.0", + "listen_port": 8814, + "verbosity": "error", + "enable_openapi": false, + "jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d", + "ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg", + "CORS_origins": [], + "username": "freqtrader", + "password": "FreqTrade007" + }, + "bot_name": "freqtrade", + "initial_state": "running", + "force_entry_enable": false, + "internals": { + "process_throttle_secs": 1 + } +} \ No newline at end of file diff --git a/strategies/ChanLun_BTC_1m.py b/strategies/ChanLun_BTC_1m.py new file mode 100644 index 0000000..2848540 --- /dev/null +++ b/strategies/ChanLun_BTC_1m.py @@ -0,0 +1,133 @@ +# --- 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 + # 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, + "60": 0.03, + "120": 0.01, + "180": 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来控制 + + trailing_stop = False + trailing_stop_positive = 0.03 + trailing_stop_positive_offset = 0.06 + trailing_only_offset_is_reached = False + + # 关闭分批止盈/仓位调整 + 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) + dataframe['bsp_state'] = self.chan.get_bsp_state(dataframe) + return dataframe + def add_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) + return df + + def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + dataframe.loc[ + ( + (dataframe['bsp_state'].shift(1) == -1) + ), + ['enter_long', 'enter_tag']] = (1, 'long_signal_chan') + dataframe.loc[ + ( + (dataframe['bsp_state'].shift(1) == 1) + ), + ['enter_short', 'enter_tag']] = (1, 'short_signal_chan') + return dataframe + def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + # 出场和进场共用同一套“确认笔 + end_klc 买卖点”语义。 + dataframe.loc[ + ( + (dataframe['bsp_state'].shift(1) == 1) + ), + ['exit_long', 'exit_tag']] = (1, 'long_signal_chan') + dataframe.loc[ + ( + (dataframe['bsp_state'].shift(1) == -1) + ), + ['exit_short', 'exit_tag']] = (1, 'short_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 self.lev + def get_ticker_indicator(self): + return int(self.timeframe[:-1]) \ No newline at end of file diff --git a/web/app.py b/web/app.py index d5ce725..c2d409f 100644 --- a/web/app.py +++ b/web/app.py @@ -564,6 +564,7 @@ def analyze_chan(df, symbol=None, timeframe=None): bsp_list = [] if len(bi_zs_list) > 0: bsp_list = chan.find_all_bsp(bi_list, bi_zs_list) + #bsp_state_list = chan.get_bsp_state(df) #for bsp in bsp_list: #print(bsp.end_time, bsp.type, bsp.dir) # 添加买卖点识别