CandlestickHatchReverseStrategy_v002.py 68 KB

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