CandlestickHatchReverseStrategy_v001.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  1. # 导入函数库
  2. from jqdata import *
  3. from jqdata import finance
  4. import pandas as pd
  5. import numpy as np
  6. from datetime import date, datetime, timedelta
  7. import re
  8. # 烛台影线形态反向交易策略 v001
  9. # 基于烛台形态检测,按照影线相反方向进行交易的策略
  10. # 设置以便完整打印 DataFrame
  11. pd.set_option('display.max_rows', None)
  12. pd.set_option('display.max_columns', None)
  13. pd.set_option('display.width', None)
  14. pd.set_option('display.max_colwidth', 20)
  15. ## 初始化函数,设定基准等等
  16. def initialize(context):
  17. # 设定沪深300作为基准
  18. set_benchmark('000300.XSHG')
  19. # 开启动态复权模式(真实价格)
  20. set_option('use_real_price', True)
  21. # 输出内容到日志
  22. log.info('烛台影线形态反向交易策略初始化开始')
  23. ### 期货相关设定 ###
  24. # 设定账户为金融账户
  25. set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
  26. # 期货类每笔交易时的手续费是: 买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
  27. set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
  28. # 设置期货交易的滑点
  29. set_slippage(StepRelatedSlippage(2))
  30. # 初始化全局变量
  31. g.usage_percentage = 0.8 # 最大资金使用比例
  32. g.max_margin_per_position = 20000 # 单个标的最大持仓保证金(元)
  33. # 烛台形态检测参数(与研究文件保持一致)
  34. g.hatch_to_body_ratio = 1.2 # 影线与实体长度比率阈值
  35. g.opposite_hatch_ratio = 0.5 # 相反方向影线与实体长度比率阈值
  36. g.historical_days = 365 # 历史数据天数,用于计算平均实体长度阈值(与研究文件保持一致)
  37. # 全局阈值缓存(每月更新一次)
  38. g.monthly_body_threshold_cache = {} # 存储每月计算的实体长度阈值
  39. g.last_threshold_update_month = None # 记录上次更新阈值的月份
  40. # 止损止盈策略参数
  41. g.fixed_stop_loss_rate = 0.01 # 固定止损比率(1%)
  42. g.trailing_stop_thresholds = [0.05, 0.10] # 动态追踪止损触发条件(5%, 10%)
  43. g.trailing_stop_rates = [0.02, 0.03, 0.04] # 动态追踪止损比率(2%, 3%, 4%)
  44. # 开仓方向配置参数
  45. g.reverse_direction_symbols = ['JD'] # 使用反向逻辑的品种列表(上影线做空,下影线做多)
  46. # 不在此列表中的品种使用正向逻辑(上影线做多,下影线做空)
  47. # 期货品种完整配置字典
  48. g.futures_config = {
  49. # 贵金属
  50. 'AU': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 1000},
  51. 'AG': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 15},
  52. # 有色金属
  53. 'CU': {'has_night_session': True, 'margin_rate': {'long': 0.09, 'short': 0.09}, 'multiplier': 5},
  54. 'AL': {'has_night_session': True, 'margin_rate': {'long': 0.09, 'short': 0.09}, 'multiplier': 5},
  55. 'ZN': {'has_night_session': True, 'margin_rate': {'long': 0.09, 'short': 0.09}, 'multiplier': 5},
  56. 'PB': {'has_night_session': True, 'margin_rate': {'long': 0.09, 'short': 0.09}, 'multiplier': 5},
  57. 'NI': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1},
  58. 'SN': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1},
  59. 'SS': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  60. # 黑色系
  61. 'RB': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  62. 'HC': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  63. 'I': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 100},
  64. 'JM': {'has_night_session': True, 'margin_rate': {'long': 0.22, 'short': 0.22}, 'multiplier': 100},
  65. 'J': {'has_night_session': True, 'margin_rate': {'long': 0.22, 'short': 0.22}, 'multiplier': 60},
  66. # 能源化工
  67. 'SP': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 10},
  68. 'FU': {'has_night_session': True, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 10},
  69. 'BU': {'has_night_session': True, 'margin_rate': {'long': 0.04, 'short': 0.04}, 'multiplier': 10},
  70. 'RU': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  71. 'BR': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  72. 'SC': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1000},
  73. 'NR': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10},
  74. 'LU': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10},
  75. 'LC': {'has_night_session': False, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 1},
  76. # 化工
  77. 'FG': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  78. 'TA': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  79. 'MA': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  80. 'SA': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  81. 'L': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  82. 'V': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  83. 'EG': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  84. 'PP': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  85. 'EB': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5},
  86. 'PG': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  87. # 农产品
  88. 'RM': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  89. 'OI': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  90. 'CF': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  91. 'SR': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  92. 'PF': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 5},
  93. 'C': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  94. 'CS': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  95. 'CY': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5},
  96. 'A': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  97. 'B': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  98. 'M': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  99. 'Y': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  100. 'P': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  101. # 无夜盘品种
  102. 'IF': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 300},
  103. 'IH': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 300},
  104. 'IC': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 200},
  105. 'IM': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 200},
  106. 'AP': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 10},
  107. 'CJ': {'has_night_session': False, 'margin_rate': {'long': 0.09, 'short': 0.09}, 'multiplier': 5},
  108. 'PK': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  109. 'JD': {'has_night_session': False, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  110. 'LH': {'has_night_session': False, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 16}
  111. }
  112. # 策略品种选择策略配置
  113. # 方案1:全品种策略 - 考虑所有配置的期货品种
  114. # g.strategy_focus_symbols = [] # 空列表表示考虑所有品种
  115. # 方案2:精选品种策略 - 只交易流动性较好的特定品种(如需使用请取消下行注释)
  116. g.strategy_focus_symbols = ['RM', 'CJ', 'CY', 'JD', 'L', 'LC', 'SF', 'SI']
  117. log.info(f"品种选择策略: {'全品种策略(覆盖所有配置品种)' if not g.strategy_focus_symbols else '精选品种策略(' + str(len(g.strategy_focus_symbols)) + '个品种)'}")
  118. # 输出开仓方向配置信息
  119. log.info("=" * 50)
  120. log.info("开仓方向配置:")
  121. log.info(f"反向逻辑品种: {g.reverse_direction_symbols} (上影线做空,下影线做多)")
  122. log.info("正向逻辑品种: 所有其他品种 (上影线做多,下影线做空)")
  123. log.info("=" * 50)
  124. # 交易记录和数据存储
  125. g.trade_history = {}
  126. g.candlestick_signals = {} # 存储烛台形态信号
  127. g.daily_data_cache = {} # 存储历史日线数据缓存
  128. g.minute_data_cache = {} # 存储今日分钟数据缓存
  129. g.body_threshold_cache = {} # 存储实体长度阈值缓存
  130. # 保证金比例管理
  131. g.margin_rate_history = {} # 保证金比例变化历史记录
  132. g.today_trades = [] # 当日交易记录
  133. # 定时任务设置
  134. # 每月第1个交易日更新阈值
  135. run_monthly(monthly_update_thresholds, 1, 'before_open', reference_security='IF1808.CCFX')
  136. # 夜盘开始 - 仅止损止盈检查
  137. run_daily(main_trading_stop_only, time='21:05:00', reference_security='IF1808.CCFX')
  138. run_daily(main_trading_stop_only, time='21:35:00', reference_security='IF1808.CCFX')
  139. run_daily(main_trading_stop_only, time='22:05:00', reference_security='IF1808.CCFX')
  140. run_daily(main_trading_stop_only, time='22:35:00', reference_security='IF1808.CCFX')
  141. # 日盘开始 - 仅止损止盈检查
  142. run_daily(main_trading_stop_only, time='09:05:00', reference_security='IF1808.CCFX')
  143. run_daily(main_trading_stop_only, time='09:35:00', reference_security='IF1808.CCFX')
  144. run_daily(main_trading_stop_only, time='10:05:00', reference_security='IF1808.CCFX')
  145. run_daily(main_trading_stop_only, time='10:35:00', reference_security='IF1808.CCFX')
  146. run_daily(main_trading_stop_only, time='11:05:00', reference_security='IF1808.CCFX')
  147. run_daily(main_trading_stop_only, time='11:25:00', reference_security='IF1808.CCFX')
  148. run_daily(main_trading_stop_only, time='13:35:00', reference_security='IF1808.CCFX')
  149. run_daily(main_trading_stop_only, time='14:05:00', reference_security='IF1808.CCFX')
  150. # 收盘前 - 14:55进行完整交易检查,14:35仅止损止盈
  151. run_daily(main_trading_stop_only, time='14:35:00', reference_security='IF1808.CCFX')
  152. # 完整交易检查 - 仅在14:55执行(任务1, 2, 3, 4, 5, 6, 7)
  153. run_daily(main_trading_complete, time='14:55:00', reference_security='IF1808.CCFX')
  154. # 收盘后
  155. run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
  156. ############################ 主程序执行函数 ###################################
  157. def monthly_update_thresholds(context):
  158. """每月更新实体长度阈值"""
  159. log.info("=" * 60)
  160. log.info("每月阈值更新开始")
  161. log.info("=" * 60)
  162. current_month = context.current_dt.strftime('%Y-%m')
  163. # 检查是否需要更新
  164. if g.last_threshold_update_month == current_month:
  165. log.info(f"本月阈值已更新,跳过更新")
  166. return
  167. # 获取所有需要计算阈值的品种
  168. focus_symbols = g.strategy_focus_symbols if g.strategy_focus_symbols else list(g.futures_config.keys())
  169. updated_count = 0
  170. for symbol in focus_symbols:
  171. try:
  172. # 获取主力合约
  173. dominant_future = get_dominant_future(symbol)
  174. if not dominant_future:
  175. continue
  176. # 获取365天历史数据
  177. data = attribute_history(dominant_future, g.historical_days, '1d',
  178. ['open', 'close', 'high', 'low', 'volume'],
  179. df=True)
  180. if data is not None and len(data) > 30: # 确保有足够数据
  181. # 计算实体长度阈值
  182. data['body_length'] = abs(data['close'] - data['open'])
  183. body_threshold = data['body_length'].mean()
  184. # 存储到全局阈值缓存
  185. g.monthly_body_threshold_cache[dominant_future] = body_threshold
  186. updated_count += 1
  187. log.info(f"更新 {symbol}({dominant_future}) 实体长度阈值: {body_threshold:.4f}")
  188. except Exception as e:
  189. log.warning(f"更新{symbol}阈值时出错: {str(e)}")
  190. continue
  191. # 更新最后更新月份
  192. g.last_threshold_update_month = current_month
  193. log.info(f"阈值更新完成,共更新 {updated_count} 个品种")
  194. log.info("=" * 60)
  195. def main_trading_stop_only(context):
  196. """仅进行止损止盈检查的交易时段"""
  197. # 只进行止损止盈检查
  198. task_7_check_stop_loss_profit(context)
  199. def main_trading_complete(context):
  200. """14:55 完整交易检查 - 执行任务1, 2, 3, 4, 5, 6, 7"""
  201. log.info("=" * 60)
  202. log.info("14:55 烛台影线形态反向交易策略 - 完整交易检查")
  203. log.info("=" * 60)
  204. # 任务1: 获取所有可交易品种
  205. task_1_get_tradable_futures(context)
  206. # 任务2: 获取历史数据并处理阈值(包括单独计算缺失阈值)
  207. task_2_load_historical_data_and_thresholds(context)
  208. # 任务3: 获取今日分钟数据
  209. task_3_update_realtime_data(context)
  210. # 任务4: 检测烛台形态
  211. task_4_detect_candlestick_patterns(context)
  212. # 任务5: 检查开仓条件(简化版)
  213. filtered_signals = task_5_check_opening_conditions(context)
  214. # 任务6: 执行交易
  215. if filtered_signals:
  216. task_6_execute_trades(context, filtered_signals)
  217. # 任务7: 检查止损止盈
  218. task_7_check_stop_loss_profit(context)
  219. # 任务8: 检查换月移仓
  220. task_8_check_position_switch(context)
  221. ############################ 核心任务函数 ###################################
  222. def task_1_get_tradable_futures(context):
  223. """任务1: 获取所有可交易品种(分白天和晚上)"""
  224. log.info("执行任务1: 获取可交易品种")
  225. current_time = str(context.current_dt.time())[:2]
  226. # 从策略关注列表中筛选可交易品种
  227. focus_symbols = g.strategy_focus_symbols if g.strategy_focus_symbols else list(g.futures_config.keys())
  228. potential_icon_list = []
  229. night_session_symbols = []
  230. day_only_symbols = []
  231. # 预先分类所有品种
  232. for symbol in focus_symbols:
  233. if get_futures_config(symbol, 'has_night_session', False):
  234. night_session_symbols.append(symbol)
  235. else:
  236. day_only_symbols.append(symbol)
  237. if current_time in ('21', '22'):
  238. # 夜盘时间:只考虑有夜盘的品种
  239. potential_icon_list = night_session_symbols[:]
  240. log.info(f"夜盘时间,有夜盘交易的品种: {len(night_session_symbols)}个")
  241. log.info(f"夜盘可交易品种: {potential_icon_list[:10]}{'...' if len(potential_icon_list) > 10 else ''}") # 显示前10个,避免日志过长
  242. else:
  243. # 日盘时间:所有品种都可以交易(包括有夜盘的和只有日盘的)
  244. potential_icon_list = focus_symbols[:]
  245. log.info(f"日盘时间,全部品种: {len(focus_symbols)}个(含夜盘品种: {len(night_session_symbols)}个,日盘专属品种: {len(day_only_symbols)}个)")
  246. if day_only_symbols:
  247. log.info(f"日盘专属品种: {day_only_symbols}")
  248. log.info(f"日盘可交易品种: {potential_icon_list[:10]}{'...' if len(potential_icon_list) > 10 else ''}") # 显示前10个,避免日志过长
  249. potential_future_list = []
  250. for symbol in potential_icon_list:
  251. dominant_future = get_dominant_future(symbol)
  252. if dominant_future:
  253. potential_future_list.append(dominant_future)
  254. # 过滤掉已有持仓的品种
  255. existing_positions = set(g.trade_history.keys())
  256. potential_future_list = [f for f in potential_future_list if not check_symbol_prefix_match(f, existing_positions)]
  257. # 存储到全局变量
  258. g.tradable_futures = potential_future_list
  259. log.info(f"最终可交易期货品种数量: {len(potential_future_list)}")
  260. return potential_future_list
  261. def task_2_load_historical_data_and_thresholds(context):
  262. """任务2: 获取历史数据并处理阈值(包括单独计算缺失阈值)"""
  263. log.info("执行任务2: 加载历史数据并处理阈值")
  264. if not hasattr(g, 'tradable_futures'):
  265. return
  266. for future_code in g.tradable_futures:
  267. try:
  268. # 获取30天历史数据(用于分钟数据合并)
  269. data = attribute_history(future_code, 30, '1d',
  270. ['open', 'close', 'high', 'low', 'volume'],
  271. df=True)
  272. if data is not None and len(data) > 0:
  273. # 排除今天的数据
  274. today = context.current_dt.date()
  275. data = data[data.index.date < today]
  276. g.daily_data_cache[future_code] = data
  277. # 处理阈值:优先使用月度阈值,缺失时单独计算
  278. if future_code in g.monthly_body_threshold_cache:
  279. # 使用月度阈值缓存
  280. body_threshold = g.monthly_body_threshold_cache[future_code]
  281. g.body_threshold_cache[future_code] = body_threshold
  282. # log.info(f"已缓存 {future_code} 历史数据 {len(data)} 条,使用月度阈值: {body_threshold:.4f}")
  283. else:
  284. # 单独计算缺失的阈值
  285. log.info(f"{future_code} 未找到月度阈值,开始单独计算")
  286. body_threshold = calculate_individual_threshold(context, future_code)
  287. if body_threshold is not None:
  288. g.body_threshold_cache[future_code] = body_threshold
  289. log.info(f"已为 {future_code} 单独计算阈值: {body_threshold:.4f}")
  290. else:
  291. log.warning(f"{future_code} 无法计算阈值,跳过")
  292. except Exception as e:
  293. log.warning(f"加载{future_code}历史数据时出错: {str(e)}")
  294. continue
  295. log.info(f"历史数据缓存完成,共缓存 {len(g.daily_data_cache)} 个品种")
  296. def calculate_individual_threshold(context, future_code):
  297. """为单个工具计算实体长度阈值并自动缓存到月度阈值中"""
  298. try:
  299. log.info(f"为 {future_code} 单独计算365天历史阈值")
  300. # 获取365天历史数据
  301. data = attribute_history(future_code, g.historical_days, '1d',
  302. ['open', 'close', 'high', 'low', 'volume'],
  303. df=True)
  304. if data is not None and len(data) > 30: # 确保有足够数据
  305. # 排除今天的数据
  306. today = context.current_dt.date()
  307. data = data[data.index.date < today]
  308. # 计算实体长度阈值
  309. data['body_length'] = abs(data['close'] - data['open'])
  310. body_threshold = data['body_length'].mean()
  311. # 🚀 优化1:将计算结果自动添加到月度阈值缓存中
  312. g.monthly_body_threshold_cache[future_code] = body_threshold
  313. log.info(f"✅ {future_code} 单独计算完成,阈值: {body_threshold:.4f},已添加到月度缓存")
  314. log.info(f"当前月度缓存包含 {len(g.monthly_body_threshold_cache)} 个品种阈值")
  315. return body_threshold
  316. else:
  317. log.warning(f"{future_code} 历史数据不足,无法计算阈值")
  318. return None
  319. except Exception as e:
  320. log.warning(f"为 {future_code} 单独计算阈值时出错: {str(e)}")
  321. return None
  322. def task_3_update_realtime_data(context):
  323. """任务3: 获取今日分钟数据"""
  324. # log.info("执行任务3: 更新实时数据")
  325. # 收集需要更新数据的品种
  326. update_symbols = set()
  327. # 添加可交易品种
  328. if hasattr(g, 'tradable_futures') and g.tradable_futures:
  329. update_symbols.update(g.tradable_futures)
  330. # 添加持仓品种(用于止损止盈)
  331. if hasattr(g, 'trade_history') and g.trade_history:
  332. update_symbols.update(g.trade_history.keys())
  333. if not update_symbols:
  334. return
  335. for future_code in update_symbols:
  336. try:
  337. # 获取今日分钟数据
  338. minute_data = get_today_minute_data(context, future_code)
  339. if minute_data is None:
  340. continue
  341. # 获取历史数据
  342. historical_data = g.daily_data_cache.get(future_code)
  343. if historical_data is None:
  344. # 为持仓品种临时获取历史数据
  345. try:
  346. data = attribute_history(future_code, g.historical_days, '1d',
  347. ['open', 'close', 'high', 'low', 'volume'],
  348. df=True)
  349. if data is not None and len(data) > 0:
  350. today = context.current_dt.date()
  351. data = data[data.index.date < today]
  352. # 计算实体长度阈值
  353. data['body_length'] = abs(data['close'] - data['open'])
  354. body_threshold = data['body_length'].mean()
  355. g.daily_data_cache[future_code] = data
  356. g.body_threshold_cache[future_code] = body_threshold
  357. historical_data = data
  358. log.info(f"为持仓品种 {future_code} 临时获取历史数据 {len(data)} 条")
  359. except Exception as e:
  360. log.warning(f"获取{future_code}历史数据失败: {str(e)}")
  361. continue
  362. if historical_data is None:
  363. continue
  364. # 将今日数据合并为日线数据
  365. today_data = aggregate_minute_to_daily(minute_data)
  366. if today_data is not None:
  367. # 合并历史数据和今日数据
  368. combined_data = pd.concat([historical_data, today_data], sort=False)
  369. g.minute_data_cache[future_code] = combined_data
  370. except Exception as e:
  371. log.warning(f"更新{future_code}实时数据时出错: {str(e)}")
  372. continue
  373. def task_4_detect_candlestick_patterns(context):
  374. """任务4: 检测烛台形态"""
  375. # log.info("执行任务4: 检测烛台形态")
  376. candlestick_signals = []
  377. # 获取已持仓的品种列表
  378. existing_positions = set(g.trade_history.keys())
  379. for future_code, data in g.minute_data_cache.items():
  380. try:
  381. # 检查是否已有相似持仓,如果有则跳过分析
  382. if check_symbol_prefix_match(future_code, existing_positions):
  383. continue
  384. # 获取实体长度阈值
  385. body_threshold = g.body_threshold_cache.get(future_code)
  386. if body_threshold is None:
  387. continue
  388. # 检查最新的烛台形态
  389. latest_pattern = check_latest_candlestick_pattern(data, future_code, body_threshold)
  390. if latest_pattern:
  391. candlestick_signals.append(latest_pattern)
  392. log.info(f"{future_code} 发现烛台形态: {latest_pattern['hatch_direction']}影线")
  393. except Exception as e:
  394. log.warning(f"检测{future_code}烛台形态时出错: {str(e)}")
  395. continue
  396. # 存储到全局变量
  397. g.candlestick_signals = candlestick_signals
  398. if len(candlestick_signals) > 0:
  399. log.info(f"烛台形态检测完成,发现信号 {len(candlestick_signals)} 个")
  400. return candlestick_signals
  401. def task_5_check_opening_conditions(context):
  402. """任务5: 检查开仓条件(简化版)"""
  403. log.info("执行任务5: 检查开仓条件(简化版)")
  404. if not hasattr(g, 'candlestick_signals') or not g.candlestick_signals:
  405. log.info("没有检测到烛台信号")
  406. return []
  407. log.info(f"检测到 {len(g.candlestick_signals)} 个烛台信号,开始筛选")
  408. filtered_signals = []
  409. for i, signal in enumerate(g.candlestick_signals):
  410. log.info(f"处理信号 {i+1}: {signal['symbol']} {signal['hatch_direction']}影线")
  411. # 仅检查是否已有相似持仓(避免重复开仓同一品种)
  412. if check_symbol_prefix_match(signal['symbol'], set(g.trade_history.keys())):
  413. log.info(f"{signal['symbol']} 已有相似持仓,跳过")
  414. continue
  415. # 简化版:只要形态满足条件就接受,无额外验证
  416. filtered_signals.append(signal)
  417. log.info(f"{signal['symbol']} 烛台形态满足条件,接受交易信号")
  418. log.info(f"开仓条件检查完成,满足条件 {len(filtered_signals)} 个")
  419. return filtered_signals
  420. def task_6_execute_trades(context, filtered_signals):
  421. """任务6: 执行交易(简化版)"""
  422. log.info("执行任务6: 执行交易(简化版)")
  423. if not filtered_signals:
  424. log.info("没有满足条件的交易信号")
  425. return
  426. log.info(f"开始执行 {len(filtered_signals)} 个交易信号")
  427. for i, signal in enumerate(filtered_signals):
  428. symbol = signal['symbol']
  429. log.info(f"执行交易 {i+1}: {symbol} {signal['hatch_direction']}影线形态")
  430. # 使用可配置的开仓方向逻辑
  431. direction, logic_description = determine_trading_direction(symbol, signal['hatch_direction'])
  432. log.info(f"{symbol} 交易方向: {direction} ({logic_description})")
  433. try:
  434. # 计算目标手数(优化版:直接返回手数)
  435. target_hands = calculate_target_hands(context, symbol, direction)
  436. log.info(f"计算目标手数: {symbol} {direction} 目标手数: {target_hands}")
  437. if target_hands > 0:
  438. # 执行开仓
  439. log.info(f"开始下单: {symbol} {direction} 目标手数: {target_hands}")
  440. success = open_position(context, symbol, target_hands, direction, signal)
  441. if success:
  442. actual_margin = g.trade_history[symbol]['actual_margin']
  443. actual_price = g.trade_history[symbol]['entry_price']
  444. log.info(f"✅ 成功开仓 {symbol} {direction}, 成交价格: {actual_price:.2f}, 目标手数: {target_hands}, 实际保证金: {actual_margin:.0f}")
  445. else:
  446. log.warning(f"❌ 开仓失败 {symbol} {direction}")
  447. else:
  448. log.warning(f"{symbol} 计算目标手数为0,跳过")
  449. except Exception as e:
  450. log.warning(f"{symbol} 交易执行出错: {str(e)}")
  451. continue
  452. log.info("交易执行完成")
  453. def task_8_check_position_switch(context):
  454. """任务8: 检查换月移仓"""
  455. # log.info("执行任务8: 检查换月移仓")
  456. switch_result = position_auto_switch(context)
  457. if switch_result:
  458. log.info(f"执行了 {len(switch_result)} 次移仓换月")
  459. for result in switch_result:
  460. log.info(f"移仓: {result['before']} -> {result['after']}")
  461. def task_7_check_stop_loss_profit(context):
  462. """任务7: 检查止损止盈(带交易时间验证)"""
  463. # log.info("执行任务7: 检查止损止盈")
  464. # 获取当前时间
  465. current_time = context.current_dt.strftime('%H:%M')
  466. current_hour = int(current_time[:2])
  467. # 判断是否为夜盘时间(21:00-23:00 和 00:00-02:30)
  468. is_night_session = (current_hour >= 21) or (current_hour <= 2)
  469. # 遍历所有持仓进行止损止盈检查
  470. subportfolio = context.subportfolios[0]
  471. long_positions = list(subportfolio.long_positions.values())
  472. short_positions = list(subportfolio.short_positions.values())
  473. closed_count = 0
  474. skipped_count = 0
  475. for position in long_positions + short_positions:
  476. security = position.security
  477. underlying_symbol = security.split('.')[0][:-4]
  478. # 检查交易时间适配性
  479. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  480. # 如果是夜盘时间,但品种不支持夜盘交易,则跳过
  481. if is_night_session and not has_night_session:
  482. skipped_count += 1
  483. # log.info(f"跳过夜盘时间的日间品种: {underlying_symbol} ({current_time})")
  484. continue
  485. # 执行止损止盈检查
  486. if check_stop_loss_profit(context, position):
  487. closed_count += 1
  488. if closed_count > 0:
  489. log.info(f"执行了 {closed_count} 次止损止盈")
  490. if skipped_count > 0:
  491. log.info(f"夜盘时间跳过 {skipped_count} 个日间品种的止损止盈检查")
  492. ############################ 数据处理辅助函数 ###################################
  493. def check_has_night_session(underlying_symbol):
  494. """检查品种是否有夜盘"""
  495. return get_futures_config(underlying_symbol, 'has_night_session', False)
  496. def get_today_minute_data(context, future_code):
  497. """获取今日分钟数据"""
  498. try:
  499. # 判断该品种是否有夜盘
  500. underlying_symbol = future_code.split('.')[0][:-4]
  501. has_night_session = check_has_night_session(underlying_symbol)
  502. end_time = context.current_dt
  503. # 获取足够的历史分钟数据
  504. minute_data = attribute_history(future_code,
  505. count=800, # 获取足够多的数据
  506. unit='1m',
  507. fields=['open', 'close', 'high', 'low', 'volume'],
  508. df=True)
  509. if minute_data is None or len(minute_data) == 0:
  510. return None
  511. # 提取所有日期(年月日维度)
  512. minute_data['date'] = minute_data.index.date
  513. unique_dates = sorted(minute_data['date'].unique())
  514. if has_night_session:
  515. # 有夜盘的品种:需要找到前一交易日的21:00作为今日开盘起点
  516. today_date = end_time.date()
  517. # 找到今天之前的最后一个交易日
  518. previous_trading_dates = [d for d in unique_dates if d < today_date]
  519. if not previous_trading_dates:
  520. return minute_data
  521. previous_trading_date = max(previous_trading_dates)
  522. # 找到前一交易日21:00:00的数据作为开盘起点
  523. previous_day_data = minute_data[minute_data['date'] == previous_trading_date]
  524. night_21_data = previous_day_data[previous_day_data.index.hour == 21]
  525. if len(night_21_data) > 0:
  526. # 从前一交易日21:00开始的所有数据
  527. start_time = night_21_data.index[0] # 21:00:00的时间点
  528. filtered_data = minute_data[minute_data.index >= start_time]
  529. return filtered_data.drop(columns=['date'])
  530. else:
  531. # 备选方案:使用今天9:00开始的数据
  532. today_data = minute_data[minute_data['date'] == today_date]
  533. day_9_data = today_data[today_data.index.hour >= 9]
  534. if len(day_9_data) > 0:
  535. return day_9_data.drop(columns=['date'])
  536. else:
  537. return minute_data.drop(columns=['date'])
  538. else:
  539. # 没有夜盘的品种:从今天9:00:00开始
  540. today_date = end_time.date()
  541. today_data = minute_data[minute_data['date'] == today_date]
  542. # 找到今天9:00:00开始的数据
  543. day_9_data = today_data[today_data.index.hour >= 9]
  544. if len(day_9_data) > 0:
  545. return day_9_data.drop(columns=['date'])
  546. else:
  547. return today_data.drop(columns=['date']) if len(today_data) > 0 else minute_data.drop(columns=['date'])
  548. except Exception as e:
  549. log.warning(f"获取{future_code}今日分钟数据时出错: {str(e)}")
  550. return None
  551. def aggregate_minute_to_daily(minute_data):
  552. """将分钟数据聚合为日数据"""
  553. try:
  554. if minute_data is None or len(minute_data) == 0:
  555. return None
  556. # 获取今日日期(使用最后一条数据的日期作为今日日期)
  557. today_date = minute_data.index[-1].date()
  558. # 聚合为日数据
  559. daily_data = pd.DataFrame({
  560. 'open': [minute_data['open'].iloc[0]], # 今日交易开始时的开盘价
  561. 'close': [minute_data['close'].iloc[-1]], # 当前收盘价,实时更新
  562. 'high': [minute_data['high'].max()],
  563. 'low': [minute_data['low'].min()],
  564. 'volume': [minute_data['volume'].sum()]
  565. }, index=[pd.Timestamp(today_date)])
  566. return daily_data
  567. except Exception as e:
  568. log.warning(f"聚合分钟数据时出错: {str(e)}")
  569. return None
  570. def check_latest_candlestick_pattern(data, future_code, body_threshold):
  571. """检查最新的烛台形态"""
  572. if len(data) < 1:
  573. return None
  574. # 获取最新一天的数据
  575. today = data.iloc[-1]
  576. # 检查烛台形态
  577. pattern_result = check_candlestick_pattern_single_day(today, body_threshold)
  578. if not pattern_result:
  579. return None
  580. return {
  581. 'symbol': future_code,
  582. 'date': today.name,
  583. 'hatch_direction': pattern_result['hatch_direction'],
  584. 'open': today['open'],
  585. 'close': today['close'],
  586. 'high': today['high'],
  587. 'low': today['low'],
  588. 'body_length': pattern_result['body_length'],
  589. 'hatch_length': pattern_result['hatch_length']
  590. }
  591. def check_candlestick_pattern_single_day(row, body_threshold):
  592. """检查单日烛台形态是否符合影线条件"""
  593. open_price = row['open']
  594. close_price = row['close']
  595. high_price = row['high']
  596. low_price = row['low']
  597. # 计算实体长度
  598. body_length = abs(close_price - open_price)
  599. # 检查实体长度是否满足阈值
  600. if body_length < body_threshold:
  601. return None
  602. # 计算影线长度
  603. upper_hatch = high_price - max(open_price, close_price)
  604. lower_hatch = min(open_price, close_price) - low_price
  605. # 检查影线条件
  606. hatch_direction = None
  607. hatch_length = 0
  608. # 检查上影线条件:上影线长度符合要求 且 下影线长度小于实体长度的一半
  609. if (upper_hatch >= g.hatch_to_body_ratio * body_length and
  610. lower_hatch < g.opposite_hatch_ratio * body_length):
  611. hatch_direction = 'up'
  612. hatch_length = upper_hatch
  613. # 检查下影线条件:下影线长度符合要求 且 上影线长度小于实体长度的一半
  614. elif (lower_hatch >= g.hatch_to_body_ratio * body_length and
  615. upper_hatch < g.opposite_hatch_ratio * body_length):
  616. hatch_direction = 'down'
  617. hatch_length = lower_hatch
  618. # 如果满足影线条件,返回形态信息
  619. if hatch_direction is not None:
  620. return {
  621. 'hatch_direction': hatch_direction,
  622. 'body_length': body_length,
  623. 'hatch_length': hatch_length
  624. }
  625. return None
  626. ############################ 动态保证金率调整函数 ###################################
  627. def detect_and_update_margin_rates(context, symbol, actual_hands, cash_change, direction):
  628. """
  629. 检测并更新保证金率配置
  630. 参数:
  631. symbol: 期货合约代码
  632. actual_hands: 实际成交手数
  633. cash_change: 实际资金变化(保证金使用)
  634. direction: 交易方向
  635. """
  636. try:
  637. underlying_symbol = symbol.split('.')[0][:-4]
  638. if underlying_symbol not in g.futures_config:
  639. return
  640. current_price = get_current_data()[symbol].last_price
  641. multiplier = get_multiplier(underlying_symbol)
  642. # 计算实际保证金率
  643. contract_value = current_price * multiplier * actual_hands
  644. actual_margin_rate = cash_change / contract_value if contract_value > 0 else 0
  645. # 获取配置中的保证金率
  646. config_margin_rate = g.futures_config[underlying_symbol]['margin_rate'][direction]
  647. # 计算差异百分比
  648. rate_diff_percentage = abs(actual_margin_rate - config_margin_rate) / config_margin_rate * 100 if config_margin_rate > 0 else 100
  649. # 如果差异超过10%,更新配置
  650. if rate_diff_percentage > 10:
  651. log.info(f"🔍 检测到{underlying_symbol}保证金率差异: 配置={config_margin_rate:.3f}, 实际={actual_margin_rate:.3f}, 差异={rate_diff_percentage:.1f}%")
  652. # 更新配置
  653. g.futures_config[underlying_symbol]['margin_rate'][direction] = actual_margin_rate
  654. # 如果是双向更新(多空保证金率通常相同)
  655. if g.futures_config[underlying_symbol]['margin_rate']['long'] == g.futures_config[underlying_symbol]['margin_rate']['short']:
  656. g.futures_config[underlying_symbol]['margin_rate']['long'] = actual_margin_rate
  657. g.futures_config[underlying_symbol]['margin_rate']['short'] = actual_margin_rate
  658. log.info(f"✅ 已更新{underlying_symbol}保证金率为 {actual_margin_rate:.3f} (双向)")
  659. else:
  660. log.info(f"✅ 已更新{underlying_symbol} {direction}保证金率为 {actual_margin_rate:.3f}")
  661. except Exception as e:
  662. log.warning(f"检测保证金率时出错 {symbol}: {str(e)}")
  663. ############################ 机会性仓位调整函数 ###################################
  664. def opportunistic_position_increase(context, symbol, direction, signal):
  665. """
  666. 机会性仓位调整:在保证金使用量低于限制时自动增加仓位
  667. 参数:
  668. symbol: 期货合约代码
  669. direction: 交易方向
  670. signal: 交易信号
  671. """
  672. try:
  673. if symbol not in g.trade_history:
  674. return False
  675. underlying_symbol = symbol.split('.')[0][:-4]
  676. current_price = get_current_data()[symbol].last_price
  677. margin_rate = get_margin_rate(underlying_symbol, direction)
  678. multiplier = get_multiplier(underlying_symbol)
  679. # 获取当前持仓信息
  680. current_actual_margin = g.trade_history[symbol]['actual_margin']
  681. current_hands = g.trade_history[symbol]['actual_hands']
  682. # 计算剩余保证金容量
  683. max_margin = g.max_margin_per_position
  684. remaining_margin_capacity = max_margin - current_actual_margin
  685. # 检查是否有足够的剩余容量增加至少1手
  686. single_hand_margin = current_price * multiplier * margin_rate
  687. if remaining_margin_capacity >= single_hand_margin:
  688. # 计算可以增加的最大手数
  689. additional_hands = int(remaining_margin_capacity / single_hand_margin)
  690. # 同时考虑可用资金限制
  691. available_cash = context.portfolio.available_cash * g.usage_percentage
  692. max_hands_by_cash = int(available_cash / single_hand_margin)
  693. # 取较小值
  694. additional_hands = min(additional_hands, max_hands_by_cash)
  695. if additional_hands >= 1:
  696. log.info(f"🚀 机会性增仓机会: {symbol} 当前{current_hands}手(保证金:{current_actual_margin:.0f}), 可增加{additional_hands}手")
  697. # 计算新的目标手数
  698. new_target_hands = current_hands + additional_hands
  699. # 执行增仓
  700. order = order_target(symbol, new_target_hands, side=direction)
  701. if order and order.filled > 0:
  702. # 计算实际增仓使用的保证金
  703. cash_after = context.portfolio.available_cash
  704. additional_margin_used = order.filled * single_hand_margin # 估算使用的保证金
  705. # 更新交易记录
  706. new_total_hands = current_hands + order.filled
  707. new_total_margin = current_actual_margin + additional_margin_used
  708. g.trade_history[symbol]['actual_hands'] = new_total_hands
  709. g.trade_history[symbol]['target_hands'] = new_target_hands
  710. g.trade_history[symbol]['actual_margin'] = new_total_margin
  711. log.info(f"✅ 成功增仓 {symbol} {order.filled}手, 总手数: {new_total_hands}手, 总保证金: {new_total_margin:.0f}")
  712. # 记录增仓交易
  713. g.today_trades.append({
  714. 'security': symbol,
  715. 'underlying_symbol': underlying_symbol,
  716. 'direction': direction,
  717. 'order_amount': order.filled,
  718. 'order_price': order.avg_cost if order.avg_cost else order.price,
  719. 'cash_change': additional_margin_used,
  720. 'time': context.current_dt,
  721. 'trade_type': 'increase' # 标记为增仓
  722. })
  723. return True
  724. return False
  725. except Exception as e:
  726. log.warning(f"机会性增仓时出错 {symbol}: {str(e)}")
  727. return False
  728. ############################ 交易执行函数 ###################################
  729. def open_position(context, security, target_hands, direction, signal):
  730. """开仓(优化版:使用order_target按手数开仓)"""
  731. try:
  732. # 记录交易前的可用资金
  733. cash_before = context.portfolio.available_cash
  734. # 使用order_target按手数开仓,自动处理持仓差额
  735. order = order_target(security, target_hands, side=direction)
  736. if order is not None and order.filled > 0:
  737. # 记录交易后的可用资金
  738. cash_after = context.portfolio.available_cash
  739. # 计算实际资金变化
  740. cash_change = cash_before - cash_after
  741. # 获取订单价格和数量
  742. order_price = order.avg_cost if order.avg_cost else order.price
  743. order_amount = order.filled
  744. # 记录当日交易
  745. underlying_symbol = security.split('.')[0][:-4]
  746. g.today_trades.append({
  747. 'security': security,
  748. 'underlying_symbol': underlying_symbol,
  749. 'direction': direction,
  750. 'order_amount': order_amount,
  751. 'order_price': order_price,
  752. 'cash_change': cash_change,
  753. 'time': context.current_dt
  754. })
  755. # 记录交易信息,包含止损止盈相关信息
  756. g.trade_history[security] = {
  757. 'entry_price': order_price,
  758. 'target_hands': target_hands,
  759. 'actual_hands': order_amount,
  760. 'actual_margin': cash_change,
  761. 'direction': direction,
  762. 'entry_time': context.current_dt,
  763. 'signal_info': signal,
  764. 'max_profit': 0.0, # 初始化最大利润
  765. 'max_profit_price': order_price # 记录最大利润时的价格
  766. }
  767. # 🚀 优化2:动态保证金率调整
  768. detect_and_update_margin_rates(context, security, order_amount, cash_change, direction)
  769. # 🚀 优化3:机会性仓位调整
  770. opportunistic_position_increase(context, security, direction, signal)
  771. return True
  772. except Exception as e:
  773. log.warning(f"开仓失败 {security}: {str(e)}")
  774. return False
  775. def close_position(context, security, direction):
  776. """平仓(优化版:使用order_target平仓到0手)"""
  777. try:
  778. # 使用order_target平仓到0手,自动处理持仓清零
  779. order = order_target(security, 0, side=direction)
  780. if order is not None and order.filled > 0:
  781. underlying_symbol = security.split('.')[0][:-4]
  782. # 记录当日交易(平仓)
  783. g.today_trades.append({
  784. 'security': security,
  785. 'underlying_symbol': underlying_symbol,
  786. 'direction': direction,
  787. 'order_amount': -order.filled, # 负数表示平仓
  788. 'order_price': order.avg_cost if order.avg_cost else order.price,
  789. 'cash_change': 0, # 平仓不计算保证金变化
  790. 'time': context.current_dt
  791. })
  792. log.info(f"平仓成功 - 品种: {underlying_symbol}, 平仓手数: {order.filled}")
  793. # 从交易历史中移除
  794. if security in g.trade_history:
  795. del g.trade_history[security]
  796. return True
  797. except Exception as e:
  798. log.warning(f"平仓失败 {security}: {str(e)}")
  799. return False
  800. def check_stop_loss_profit(context, position):
  801. """检查止损止盈"""
  802. security = position.security
  803. if security not in g.trade_history:
  804. return False
  805. trade_info = g.trade_history[security]
  806. direction = trade_info['direction']
  807. entry_price = trade_info['entry_price']
  808. current_price = position.price
  809. # 计算当前盈亏比率
  810. if direction == 'long':
  811. profit_rate = (current_price - entry_price) / entry_price
  812. else:
  813. profit_rate = (entry_price - current_price) / entry_price
  814. # 更新最大利润记录
  815. if profit_rate > trade_info['max_profit']:
  816. trade_info['max_profit'] = profit_rate
  817. trade_info['max_profit_price'] = current_price
  818. g.trade_history[security] = trade_info
  819. # 检查固定止损
  820. if profit_rate <= -g.fixed_stop_loss_rate:
  821. log.info(f"触发固定止损 {security} {direction}, 当前亏损率: {profit_rate:.3%}, 成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  822. close_position(context, security, direction)
  823. return True
  824. # 检查动态追踪止盈
  825. max_profit = trade_info['max_profit']
  826. if max_profit > 0:
  827. # 确定追踪止损比率
  828. if max_profit <= g.trailing_stop_thresholds[0]: # ≤5%
  829. trailing_rate = g.trailing_stop_rates[0] # 1%
  830. elif max_profit <= g.trailing_stop_thresholds[1]: # 5%-10%
  831. trailing_rate = g.trailing_stop_rates[1] # 2%
  832. else: # >10%
  833. trailing_rate = g.trailing_stop_rates[2] # 3%
  834. # 检查是否触发追踪止损
  835. profit_drawdown = max_profit - profit_rate
  836. if profit_drawdown >= trailing_rate:
  837. log.info(f"触发动态追踪止损 {security} {direction}")
  838. log.info(f"最大利润: {max_profit:.3%}, 当前利润: {profit_rate:.3%}, 回撤: {profit_drawdown:.3%}, 触发阈值: {trailing_rate:.3%}")
  839. close_position(context, security, direction)
  840. return True
  841. return False
  842. ############################ 辅助函数 ###################################
  843. def determine_trading_direction(symbol, hatch_direction):
  844. """
  845. 确定开仓方向(支持可配置的正向/反向逻辑)
  846. 参数:
  847. symbol: 期货合约代码 (如 'JD2510.XDCE')
  848. hatch_direction: 影线方向 ('up' 或 'down')
  849. 返回:
  850. (direction, logic_description): 交易方向和逻辑说明的元组
  851. """
  852. # 提取基础品种代码
  853. underlying_symbol = symbol.split('.')[0][:-4] # 如 'JD2510.XDCE' -> 'JD'
  854. # 检查是否在反向逻辑列表中
  855. use_reverse_logic = underlying_symbol in g.reverse_direction_symbols
  856. if use_reverse_logic:
  857. # 反向逻辑:上影线做空,下影线做多(当前逻辑)
  858. if hatch_direction == 'up':
  859. direction = 'short'
  860. logic_description = f"反向逻辑:{underlying_symbol}上影线做空"
  861. else:
  862. direction = 'long'
  863. logic_description = f"反向逻辑:{underlying_symbol}下影线做多"
  864. else:
  865. # 正向逻辑:上影线做多,下影线做空(新逻辑)
  866. if hatch_direction == 'up':
  867. direction = 'long'
  868. logic_description = f"正向逻辑:{underlying_symbol}上影线做多"
  869. else:
  870. direction = 'short'
  871. logic_description = f"正向逻辑:{underlying_symbol}下影线做空"
  872. return direction, logic_description
  873. def get_futures_config(underlying_symbol, config_key=None, default_value=None):
  874. """获取期货品种配置信息的辅助函数"""
  875. if underlying_symbol not in g.futures_config:
  876. if config_key and default_value is not None:
  877. return default_value
  878. return {}
  879. if config_key is None:
  880. return g.futures_config[underlying_symbol]
  881. return g.futures_config[underlying_symbol].get(config_key, default_value)
  882. def get_margin_rate(underlying_symbol, direction, default_rate=0.10):
  883. """获取保证金比例的辅助函数"""
  884. return g.futures_config.get(underlying_symbol, {}).get('margin_rate', {}).get(direction, default_rate)
  885. def get_multiplier(underlying_symbol, default_multiplier=10):
  886. """获取合约乘数的辅助函数"""
  887. return g.futures_config.get(underlying_symbol, {}).get('multiplier', default_multiplier)
  888. def calculate_target_hands(context, security, direction):
  889. """计算目标开仓手数(优化版:直接返回手数用于order_target)"""
  890. current_price = get_current_data()[security].last_price
  891. underlying_symbol = security.split('.')[0][:-4]
  892. # 使用保证金比例
  893. margin_rate = get_margin_rate(underlying_symbol, direction)
  894. multiplier = get_multiplier(underlying_symbol)
  895. # 计算单手保证金
  896. single_hand_margin = current_price * multiplier * margin_rate
  897. # 还要考虑可用资金限制
  898. available_cash = context.portfolio.available_cash * g.usage_percentage
  899. # 根据单个标的最大持仓保证金限制计算开仓数量
  900. max_margin = g.max_margin_per_position
  901. if single_hand_margin <= max_margin:
  902. # 如果单手保证金不超过最大限制,计算最大可开仓手数
  903. max_hands = int(max_margin / single_hand_margin)
  904. max_hands_by_cash = int(available_cash / single_hand_margin)
  905. # 取两者较小值
  906. actual_hands = min(max_hands, max_hands_by_cash)
  907. # 确保至少开1手
  908. actual_hands = max(1, actual_hands)
  909. # 实际保证金
  910. actual_margin = single_hand_margin * actual_hands
  911. log.info(f"单手保证金: {single_hand_margin:.0f}, 目标开仓手数: {actual_hands}, 预计保证金: {actual_margin:.0f}")
  912. # 直接返回手数,用于order_target()
  913. return actual_hands
  914. else:
  915. # 如果单手保证金超过最大限制,默认开仓1手
  916. actual_hands = 1
  917. actual_margin = single_hand_margin * actual_hands
  918. log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手, 预计保证金: {actual_margin:.0f}")
  919. # 直接返回手数,用于order_target()
  920. return actual_hands
  921. def check_sufficient_capital(context, symbol):
  922. """检查资金是否充足"""
  923. try:
  924. current_price = get_current_data()[symbol].last_price
  925. underlying_symbol = symbol.split('.')[0][:-4]
  926. margin_rate = get_margin_rate(underlying_symbol, 'long')
  927. multiplier = get_multiplier(underlying_symbol)
  928. # 计算单手保证金
  929. single_hand_margin = current_price * multiplier * margin_rate
  930. # 使用实际可用资金(考虑资金使用比例)
  931. available_cash = context.portfolio.available_cash * g.usage_percentage
  932. # 检查是否有足够资金开仓至少1手
  933. return available_cash >= single_hand_margin
  934. except:
  935. return False
  936. def check_price_and_liquidity(signal):
  937. """检查价格合理性和流动性"""
  938. try:
  939. # 简单的合理性检查
  940. symbol = signal['symbol']
  941. current_data = get_current_data()[symbol]
  942. log.info(f"{symbol} 价格检查 - 当前价: {current_data.last_price:.2f}, 涨停: {current_data.high_limit:.2f}, 跌停: {current_data.low_limit:.2f}, 成交量: {current_data.volume}")
  943. # 检查是否处于涨跌停
  944. if current_data.last_price <= current_data.low_limit:
  945. log.warning(f"{symbol} 价格触及跌停板 ({current_data.last_price:.2f} <= {current_data.low_limit:.2f}),跳过")
  946. return False
  947. if current_data.last_price >= current_data.high_limit:
  948. log.warning(f"{symbol} 价格触及涨停板 ({current_data.last_price:.2f} >= {current_data.high_limit:.2f}),跳过")
  949. return False
  950. # 检查成交量是否充足
  951. if current_data.volume <= 0:
  952. log.warning(f"{symbol} 无成交量 ({current_data.volume}),跳过")
  953. return False
  954. log.info(f"{symbol} 价格和流动性检查通过")
  955. return True
  956. except Exception as e:
  957. log.warning(f"{signal['symbol']} 价格检查时出错: {str(e)}")
  958. return False
  959. def check_symbol_prefix_match(symbol, hold_symbols):
  960. """检查是否有相似的持仓品种"""
  961. symbol_prefix = symbol[:-9]
  962. for hold_symbol in hold_symbols:
  963. hold_symbol_prefix = hold_symbol[:-9]
  964. if symbol_prefix == hold_symbol_prefix:
  965. return True
  966. return False
  967. def after_market_close(context):
  968. """收盘后运行函数"""
  969. log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
  970. # 只有当天有交易时才打印统计信息
  971. if g.today_trades:
  972. print_daily_trading_summary(context)
  973. # 清空当日交易记录
  974. g.today_trades = []
  975. log.info('##############################################################')
  976. def print_daily_trading_summary(context):
  977. """打印当日交易汇总"""
  978. if not g.today_trades:
  979. return
  980. log.info("\n=== 当日交易汇总 ===")
  981. total_margin = 0
  982. for trade in g.today_trades:
  983. if trade['order_amount'] > 0: # 开仓
  984. log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
  985. f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f}")
  986. total_margin += trade['cash_change']
  987. else: # 平仓
  988. log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
  989. f"价格:{trade['order_price']:.2f}")
  990. log.info(f"当日保证金占用: {total_margin:.0f}")
  991. log.info("==================\n")
  992. ########################## 自动移仓换月函数 #################################
  993. def position_auto_switch(context, pindex=0, switch_func=None, callback=None):
  994. """
  995. 期货自动移仓换月。默认使用市价单进行开平仓。
  996. """
  997. import re
  998. subportfolio = context.subportfolios[pindex]
  999. symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  1000. switch_result = []
  1001. for symbol in symbols:
  1002. match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
  1003. if not match:
  1004. raise ValueError("未知期货标的: {}".format(symbol))
  1005. else:
  1006. dominant = get_dominant_future(match.groupdict()["underlying_symbol"])
  1007. cur = get_current_data()
  1008. symbol_last_price = cur[symbol].last_price
  1009. dominant_last_price = cur[dominant].last_price
  1010. log.info(f'当前持仓合约: {symbol}, 当前主力合约: {dominant}')
  1011. if dominant > symbol:
  1012. for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
  1013. if symbol not in positions_.keys():
  1014. continue
  1015. else :
  1016. p = positions_[symbol]
  1017. if switch_func is not None:
  1018. switch_func(context, pindex, p, dominant)
  1019. else:
  1020. amount = p.total_amount
  1021. # 跌停不能开空和平多,涨停不能开多和平空。
  1022. if p.side == "long":
  1023. symbol_low_limit = cur[symbol].low_limit
  1024. dominant_high_limit = cur[dominant].high_limit
  1025. if symbol_last_price <= symbol_low_limit:
  1026. log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
  1027. continue
  1028. elif dominant_last_price >= dominant_high_limit:
  1029. log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(dominant))
  1030. continue
  1031. else:
  1032. log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
  1033. order_old = order_target(symbol, 0, side='long')
  1034. if order_old != None and order_old.filled > 0:
  1035. order_new = order_target(dominant, amount, side='long')
  1036. if order_new != None and order_new.filled > 0:
  1037. switch_result.append({"before": symbol, "after": dominant, "side": "long"})
  1038. # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
  1039. g.trade_history[dominant] = g.trade_history[symbol]
  1040. del g.trade_history[symbol]
  1041. else:
  1042. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1043. if p.side == "short":
  1044. symbol_high_limit = cur[symbol].high_limit
  1045. dominant_low_limit = cur[dominant].low_limit
  1046. if symbol_last_price >= symbol_high_limit:
  1047. log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
  1048. continue
  1049. elif dominant_last_price <= dominant_low_limit:
  1050. log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(dominant))
  1051. continue
  1052. else:
  1053. log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
  1054. order_old = order_target(symbol, 0, side='short')
  1055. if order_old != None and order_old.filled > 0:
  1056. order_new = order_target(dominant, amount, side='short')
  1057. if order_new != None and order_new.filled > 0:
  1058. switch_result.append({"before": symbol, "after": dominant, "side": "short"})
  1059. # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
  1060. g.trade_history[dominant] = g.trade_history[symbol]
  1061. del g.trade_history[symbol]
  1062. else:
  1063. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1064. if callback:
  1065. callback(context, pindex, p, dominant)
  1066. return switch_result