MAPatternStrategy_v002.py 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. # 导入函数库
  2. from jqdata import *
  3. from jqdata import finance
  4. import pandas as pd
  5. import numpy as np
  6. import math
  7. from datetime import date, datetime, timedelta, time
  8. import re
  9. MA_ADDITIONAL_HISTORY_DAYS = 30 # 计算均线时额外获取的交易日数量,用于支持更长周期
  10. # 顺势交易策略 v001
  11. # 基于均线走势(前提条件)+ K线形态(开盘价差、当天价差)的期货交易策略
  12. #
  13. # 核心逻辑:
  14. # 1. 开盘时检查均线走势(MA30<=MA20<=MA10<=MA5为多头,反之为空头)
  15. # 2. 检查开盘价差是否符合方向要求(多头>=0.5%,空头<=-0.5%)
  16. # 3. 14:35和14:55检查当天价差(多头>0,空头<0),满足条件则开仓
  17. # 4. 应用固定止损和动态追踪止盈
  18. # 5. 自动换月移仓
  19. # 设置以便完整打印 DataFrame
  20. pd.set_option('display.max_rows', None)
  21. pd.set_option('display.max_columns', None)
  22. pd.set_option('display.width', None)
  23. pd.set_option('display.max_colwidth', 20)
  24. ## 初始化函数,设定基准等等
  25. def initialize(context):
  26. # 设定沪深300作为基准
  27. set_benchmark('000300.XSHG')
  28. # 开启动态复权模式(真实价格)
  29. set_option('use_real_price', True)
  30. # 输出内容到日志
  31. log.info('=' * 60)
  32. log.info('均线形态交易策略 v001 初始化开始')
  33. log.info('策略类型: 均线走势 + K线形态')
  34. log.info('=' * 60)
  35. ### 期货相关设定 ###
  36. # 设定账户为金融账户
  37. set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
  38. # 期货类每笔交易时的手续费是: 买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
  39. set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
  40. # 设置期货交易的滑点
  41. set_slippage(StepRelatedSlippage(2))
  42. # 初始化全局变量
  43. g.usage_percentage = 0.8 # 最大资金使用比例
  44. g.max_margin_per_position = 30000 # 单个标的最大持仓保证金(元)
  45. # 均线策略参数
  46. g.ma_periods = [5, 10, 20, 30, 60] # 均线周期(新增MA60)
  47. g.ma_cross_periods = [5, 10, 20, 30] # 参与均线穿越判断的均线周期
  48. g.ma_historical_days = 60 + MA_ADDITIONAL_HISTORY_DAYS # 额外增加30天,确保MA60计算稳定
  49. g.ma_open_gap_threshold = 0.001 # 方案1开盘价差阈值(0.2%)
  50. g.ma_pattern_lookback_days = 10 # 历史均线模式一致性检查的天数
  51. g.ma_pattern_consistency_threshold = 0.8 # 历史均线模式一致性阈值(80%)
  52. g.check_intraday_spread = False # 是否检查日内价差(True: 检查, False: 跳过)
  53. g.ma_proximity_min_threshold = 8 # MA5与MA10贴近计数和的最低阈值
  54. g.ma_pattern_extreme_days_threshold = 4 # 极端趋势天数阈值
  55. g.ma_distribution_lookback_days = 5 # MA5分布过滤回溯天数
  56. g.ma_distribution_min_ratio = 0.4 # MA5分布满足比例阈值
  57. g.enable_ma_distribution_filter = True # 是否启用MA5分布过滤
  58. g.ma_cross_threshold = 1 # 均线穿越数量阈值
  59. g.enable_open_gap_filter = True # 是否启用开盘价差过滤
  60. # 均线价差策略方案选择
  61. g.ma_gap_strategy_mode = 3 # 策略模式选择(1: 原方案, 2: 新方案, 3: 方案3)
  62. g.ma_open_gap_threshold2 = 0.001 # 方案2开盘价差阈值(0.2%)
  63. g.ma_intraday_threshold_scheme2 = 0.005 # 方案2日内变化阈值(0.5%)
  64. # 止损止盈策略参数
  65. g.fixed_stop_loss_rate = 0.01 # 固定止损比率(1%)
  66. g.ma_offset_ratio_normal = 0.003 # 均线跟踪止盈常规偏移量(0.3%)
  67. g.ma_offset_ratio_close = 0.01 # 均线跟踪止盈收盘前偏移量(1%)
  68. g.days_for_adjustment = 4 # 持仓天数调整阈值
  69. # 输出策略参数
  70. log.info("均线形态策略参数:")
  71. log.info(f" 均线周期: {g.ma_periods}")
  72. log.info(f" 均线穿越判定周期: {g.ma_cross_periods}")
  73. log.info(f" 策略模式: 方案{g.ma_gap_strategy_mode}")
  74. log.info(f" 方案1开盘价差阈值: {g.ma_open_gap_threshold:.1%}")
  75. log.info(f" 方案2开盘价差阈值: {g.ma_open_gap_threshold2:.1%}")
  76. log.info(f" 方案2日内变化阈值: {g.ma_intraday_threshold_scheme2:.1%}")
  77. log.info(f" 历史均线模式检查天数: {g.ma_pattern_lookback_days}天")
  78. log.info(f" 历史均线模式一致性阈值: {g.ma_pattern_consistency_threshold:.1%}")
  79. log.info(f" 极端趋势天数阈值: {g.ma_pattern_extreme_days_threshold}")
  80. log.info(f" 均线贴近计数阈值: {g.ma_proximity_min_threshold}")
  81. log.info(f" MA5分布过滤天数: {g.ma_distribution_lookback_days}")
  82. log.info(f" MA5分布最低比例: {g.ma_distribution_min_ratio:.0%}")
  83. log.info(f" 启用MA5分布过滤: {g.enable_ma_distribution_filter}")
  84. log.info(f" 是否检查日内价差: {g.check_intraday_spread}")
  85. log.info(f" 均线穿越阈值: {g.ma_cross_threshold}")
  86. log.info(f" 是否启用开盘价差过滤: {g.enable_open_gap_filter}")
  87. log.info(f" 固定止损: {g.fixed_stop_loss_rate:.1%}")
  88. log.info(f" 均线跟踪止盈常规偏移: {g.ma_offset_ratio_normal:.1%}")
  89. log.info(f" 均线跟踪止盈收盘前偏移: {g.ma_offset_ratio_close:.1%}")
  90. log.info(f" 持仓天数调整阈值: {g.days_for_adjustment}天")
  91. # 期货品种完整配置字典
  92. g.futures_config = {
  93. # 贵金属
  94. 'AU': {'has_night_session': True, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 1000, 'trading_start_time': '21:00'},
  95. 'AG': {'has_night_session': True, 'margin_rate': {'long': 0.22, 'short': 0.22}, 'multiplier': 15, 'trading_start_time': '21:00'},
  96. # 有色金属
  97. 'CU': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  98. 'AL': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  99. 'ZN': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '21:00'},
  100. 'PB': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '21:00'},
  101. 'NI': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 1, 'trading_start_time': '21:00'},
  102. 'SN': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 1, 'trading_start_time': '21:00'},
  103. 'SS': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5, 'trading_start_time': '21:00'},
  104. # 黑色系
  105. 'RB': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  106. 'HC': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  107. 'I': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 100, 'trading_start_time': '21:00'},
  108. 'JM': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 100, 'trading_start_time': '21:00'},
  109. 'J': {'has_night_session': True, 'margin_rate': {'long': 0.25, 'short': 0.25}, 'multiplier': 60, 'trading_start_time': '21:00'},
  110. # 能源化工
  111. 'SP': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  112. 'FU': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 10, 'trading_start_time': '21:00'},
  113. 'BU': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 10, 'trading_start_time': '21:00'},
  114. 'RU': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10, 'trading_start_time': '21:00'},
  115. 'BR': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  116. 'SC': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 1000, 'trading_start_time': '21:00'},
  117. 'NR': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10, 'trading_start_time': '21:00'},
  118. 'LU': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 10, 'trading_start_time': '21:00'},
  119. 'LC': {'has_night_session': False, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 1, 'trading_start_time': '09:00'},
  120. # 化工
  121. 'FG': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 20, 'trading_start_time': '21:00'},
  122. 'TA': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  123. 'MA': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  124. 'SA': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 20, 'trading_start_time': '21:00'},
  125. 'L': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  126. 'V': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  127. 'EG': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  128. 'PP': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  129. 'EB': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  130. 'PG': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 20, 'trading_start_time': '21:00'},
  131. 'PX': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 5, 'trading_start_time': '21:00'},
  132. # 农产品
  133. 'RM': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  134. 'OI': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  135. 'CF': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  136. 'SR': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  137. 'PF': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  138. 'C': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  139. 'CS': {'has_night_session': True, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 10, 'trading_start_time': '21:00'},
  140. 'CY': {'has_night_session': True, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 5, 'trading_start_time': '21:00'},
  141. 'A': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  142. 'B': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  143. 'M': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  144. 'Y': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  145. 'P': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  146. # 无夜盘品种
  147. 'IF': {'has_night_session': False, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 300, 'trading_start_time': '09:30'},
  148. 'IH': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 300, 'trading_start_time': '09:30'},
  149. 'IC': {'has_night_session': False, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 200, 'trading_start_time': '09:30'},
  150. 'IM': {'has_night_session': False, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 200, 'trading_start_time': '09:30'},
  151. 'AP': {'has_night_session': False, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 10, 'trading_start_time': '09:00'},
  152. 'CJ': {'has_night_session': False, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '09:00'},
  153. 'PK': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '09:00'},
  154. 'JD': {'has_night_session': False, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 10, 'trading_start_time': '09:00'},
  155. 'LH': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 16, 'trading_start_time': '09:00'},
  156. 'T': {'has_night_session': False, 'margin_rate': {'long': 0.03, 'short': 0.03}, 'multiplier': 1000000, 'trading_start_time': '09:30'},
  157. 'PS': {'has_night_session': False, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 3, 'trading_start_time': '09:00'},
  158. 'UR': {'has_night_session': False, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 20, 'trading_start_time': '09:00'},
  159. 'MO': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 100, 'trading_start_time': '21:00'},
  160. # 'LF': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1, 'trading_start_time': '09:30'},
  161. 'HO': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 100, 'trading_start_time': '09:30'},
  162. # 'LR': {'has_night_session': True, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 20, 'trading_start_time': '21:00'},
  163. 'LG': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 90, 'trading_start_time': '21:00'},
  164. # 'FB': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 10, 'trading_start_time': '21:00'},
  165. # 'PM': {'has_night_session': True, 'margin_rate': {'long': 0.2, 'short': 0.2}, 'multiplier': 50, 'trading_start_time': '21:00'},
  166. 'EC': {'has_night_session': False, 'margin_rate': {'long': 0.23, 'short': 0.23}, 'multiplier': 50, 'trading_start_time': '09:00'},
  167. # 'RR': {'has_night_session': True, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 10, 'trading_start_time': '21:00'},
  168. 'OP': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 40, 'trading_start_time': '09:00'},
  169. # 'IO': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 1, 'trading_start_time': '21:00'},
  170. 'BC': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  171. # 'WH': {'has_night_session': False, 'margin_rate': {'long': 0.2, 'short': 0.2}, 'multiplier': 20, 'trading_start_time': '09:00'},
  172. 'SH': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 30, 'trading_start_time': '21:00'},
  173. # 'RI': {'has_night_session': False, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 20, 'trading_start_time': '09:00'},
  174. 'TS': {'has_night_session': False, 'margin_rate': {'long': 0.015, 'short': 0.015}, 'multiplier': 2000000, 'trading_start_time': '09:30'},
  175. # 'JR': {'has_night_session': False, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 20, 'trading_start_time': '09:00'},
  176. 'AD': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '09:00'},
  177. # 'BB': {'has_night_session': False, 'margin_rate': {'long': 0.19, 'short': 0.19}, 'multiplier': 500, 'trading_start_time': '09:00'},
  178. 'PL': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 20, 'trading_start_time': '09:00'},
  179. # 'RS': {'has_night_session': False, 'margin_rate': {'long': 0.26, 'short': 0.26}, 'multiplier': 10, 'trading_start_time': '09:00'},
  180. 'SI': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '09:00'},
  181. # 'ZC': {'has_night_session': True, 'margin_rate': {'long': 0.56, 'short': 0.56}, 'multiplier': 100, 'trading_start_time': '21:00'},
  182. 'SM': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '09:00'},
  183. 'AO': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 20, 'trading_start_time': '21:00'},
  184. 'TL': {'has_night_session': False, 'margin_rate': {'long': 0.045, 'short': 0.045}, 'multiplier': 1000000, 'trading_start_time': '09:00'},
  185. 'SF': {'has_night_session': False, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '09:00'},
  186. # 'WR': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10, 'trading_start_time': '09:00'},
  187. 'PR': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 15, 'trading_start_time': '21:00'},
  188. 'TF': {'has_night_session': False, 'margin_rate': {'long': 0.022, 'short': 0.022}, 'multiplier': 1000000, 'trading_start_time': '09:00'},
  189. # 'VF': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1, 'trading_start_time': '09:00'},
  190. 'BZ': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 30, 'trading_start_time': '09:00'},
  191. }
  192. # 策略品种选择策略配置
  193. # 方案1:全品种策略 - 考虑所有配置的期货品种
  194. g.strategy_focus_symbols = [] # 空列表表示考虑所有品种
  195. # 方案2:精选品种策略 - 只交易流动性较好的特定品种(如需使用请取消下行注释)
  196. # g.strategy_focus_symbols = ['RM', 'CJ', 'CY', 'JD', 'L', 'LC', 'SF', 'SI']
  197. log.info(f"品种选择策略: {'全品种策略(覆盖所有配置品种)' if not g.strategy_focus_symbols else '精选品种策略(' + str(len(g.strategy_focus_symbols)) + '个品种)'}")
  198. # 交易记录和数据存储
  199. g.trade_history = {} # 持仓记录 {symbol: {'entry_price': xxx, 'direction': xxx, ...}}
  200. g.daily_ma_candidates = {} # 通过均线和开盘价差检查的候选品种 {symbol: {'direction': 'long'/'short', 'open_price': xxx, ...}}
  201. g.today_trades = [] # 当日交易记录
  202. g.excluded_contracts = {} # 每日排除的合约缓存 {dominant_future: {'reason': 'ma_trend'/'open_gap', 'trading_day': xxx}}
  203. g.ma_checked_underlyings = {} # 记录各品种在交易日的均线检查状态 {symbol: trading_day}
  204. g.last_ma_trading_day = None # 最近一次均线检查所属交易日
  205. # 夜盘禁止操作标志
  206. g.night_session_blocked = False # 标记是否禁止当晚操作
  207. g.night_session_blocked_trading_day = None # 记录被禁止的交易日
  208. # 定时任务设置
  209. # 夜盘开始(21:05) - 均线和开盘价差检查
  210. run_daily(check_ma_trend_and_open_gap, time='21:05:00', reference_security='IF1808.CCFX')
  211. # 日盘开始 - 均线和开盘价差检查
  212. run_daily(check_ma_trend_and_open_gap, time='09:05:00', reference_security='IF1808.CCFX')
  213. run_daily(check_ma_trend_and_open_gap, time='09:35:00', reference_security='IF1808.CCFX')
  214. # 夜盘开仓和止损止盈检查
  215. run_daily(check_open_and_stop, time='21:05:00', reference_security='IF1808.CCFX')
  216. run_daily(check_open_and_stop, time='21:35:00', reference_security='IF1808.CCFX')
  217. run_daily(check_open_and_stop, time='22:05:00', reference_security='IF1808.CCFX')
  218. run_daily(check_open_and_stop, time='22:35:00', reference_security='IF1808.CCFX')
  219. # 日盘开仓和止损止盈检查
  220. run_daily(check_open_and_stop, time='09:05:00', reference_security='IF1808.CCFX')
  221. run_daily(check_open_and_stop, time='09:35:00', reference_security='IF1808.CCFX')
  222. run_daily(check_open_and_stop, time='10:05:00', reference_security='IF1808.CCFX')
  223. run_daily(check_open_and_stop, time='10:35:00', reference_security='IF1808.CCFX')
  224. run_daily(check_open_and_stop, time='11:05:00', reference_security='IF1808.CCFX')
  225. run_daily(check_open_and_stop, time='11:25:00', reference_security='IF1808.CCFX')
  226. run_daily(check_open_and_stop, time='13:35:00', reference_security='IF1808.CCFX')
  227. run_daily(check_open_and_stop, time='14:05:00', reference_security='IF1808.CCFX')
  228. run_daily(check_open_and_stop, time='14:35:00', reference_security='IF1808.CCFX')
  229. run_daily(check_open_and_stop, time='14:55:00', reference_security='IF1808.CCFX')
  230. run_daily(check_ma_trailing_reactivation, time='14:55:00', reference_security='IF1808.CCFX')
  231. # 收盘后
  232. run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
  233. log.info('=' * 60)
  234. ############################ 主程序执行函数 ###################################
  235. def get_current_trading_day(current_dt):
  236. """根据当前时间推断对应的期货交易日"""
  237. current_date = current_dt.date()
  238. current_time = current_dt.time()
  239. trade_days = get_trade_days(end_date=current_date, count=1)
  240. if trade_days and trade_days[0] == current_date:
  241. trading_day = current_date
  242. else:
  243. next_days = get_trade_days(start_date=current_date, count=1)
  244. trading_day = next_days[0] if next_days else current_date
  245. if current_time >= time(20, 59):
  246. next_trade_days = get_trade_days(start_date=trading_day, count=2)
  247. if len(next_trade_days) >= 2:
  248. return next_trade_days[1]
  249. if len(next_trade_days) == 1:
  250. return next_trade_days[0]
  251. return trading_day
  252. def normalize_trade_day_value(value):
  253. """将交易日对象统一转换为 datetime.date"""
  254. if isinstance(value, date) and not isinstance(value, datetime):
  255. return value
  256. if isinstance(value, datetime):
  257. return value.date()
  258. if hasattr(value, 'to_pydatetime'):
  259. return value.to_pydatetime().date()
  260. try:
  261. return pd.Timestamp(value).date()
  262. except Exception:
  263. return value
  264. def check_ma_trend_and_open_gap(context):
  265. """阶段一:开盘时均线走势和开盘价差检查(一天一次)"""
  266. log.info("=" * 60)
  267. current_trading_day = get_current_trading_day(context.current_dt)
  268. log.info(f"执行均线走势和开盘价差检查 - 时间: {context.current_dt}, 交易日: {current_trading_day}")
  269. log.info("=" * 60)
  270. # 换月移仓检查(在所有部分之前)
  271. position_auto_switch(context)
  272. # ==================== 第一部分:基础数据获取 ====================
  273. # 步骤1:交易日检查和缓存清理
  274. if g.last_ma_trading_day != current_trading_day:
  275. if g.excluded_contracts:
  276. log.info(f"交易日切换至 {current_trading_day},清空上一交易日的排除缓存")
  277. g.excluded_contracts = {}
  278. g.ma_checked_underlyings = {}
  279. g.last_ma_trading_day = current_trading_day
  280. # 步骤2:获取当前时间和筛选可交易品种
  281. current_time = str(context.current_dt.time())[:5] # HH:MM格式
  282. focus_symbols = g.strategy_focus_symbols if g.strategy_focus_symbols else list(g.futures_config.keys())
  283. tradable_symbols = []
  284. # 根据当前时间确定可交易的时段
  285. # 21:05 -> 仅接受21:00开盘的合约
  286. # 09:05 -> 接受09:00或21:00开盘的合约
  287. # 09:35 -> 接受所有时段(21:00, 09:00, 09:30)的合约
  288. for symbol in focus_symbols:
  289. trading_start_time = get_futures_config(symbol, 'trading_start_time', '09:05')
  290. should_trade = False
  291. if current_time == '21:05':
  292. should_trade = trading_start_time.startswith('21:00')
  293. elif current_time == '09:05':
  294. should_trade = trading_start_time.startswith('21:00') or trading_start_time.startswith('09:00')
  295. elif current_time == '09:35':
  296. should_trade = True
  297. if should_trade:
  298. tradable_symbols.append(symbol)
  299. if not tradable_symbols:
  300. log.info(f"当前时间 {current_time} 无品种开盘,跳过检查")
  301. return
  302. log.info(f"当前时间 {current_time} 开盘品种: {tradable_symbols}")
  303. # 步骤3:对每个品种循环处理
  304. for symbol in tradable_symbols:
  305. # 步骤3.1:检查是否已处理过
  306. if g.ma_checked_underlyings.get(symbol) == current_trading_day:
  307. log.info(f"{symbol} 已在交易日 {current_trading_day} 完成均线检查,跳过本次执行")
  308. continue
  309. try:
  310. g.ma_checked_underlyings[symbol] = current_trading_day
  311. # 步骤3.2:获取主力合约
  312. dominant_future = get_dominant_future(symbol)
  313. if not dominant_future:
  314. log.info(f"{symbol} 未找到主力合约,跳过")
  315. continue
  316. # 步骤3.3:检查排除缓存
  317. if dominant_future in g.excluded_contracts:
  318. excluded_info = g.excluded_contracts[dominant_future]
  319. if excluded_info['trading_day'] == current_trading_day:
  320. continue
  321. else:
  322. # 新的一天,从缓存中移除(会在after_market_close统一清理,这里也做兜底)
  323. del g.excluded_contracts[dominant_future]
  324. # 步骤3.4:检查是否已有持仓
  325. if check_symbol_prefix_match(dominant_future, context, set(g.trade_history.keys())):
  326. log.info(f"{symbol} 已有持仓,跳过")
  327. continue
  328. # 步骤3.5:获取历史数据和前一交易日数据(合并优化)
  329. # 获取历史数据(需要足够计算MA30)
  330. historical_data = get_price(dominant_future, end_date=context.current_dt,
  331. frequency='1d', fields=['open', 'close', 'high', 'low'],
  332. count=g.ma_historical_days)
  333. if historical_data is None or len(historical_data) < max(g.ma_periods):
  334. log.info(f"{symbol} 历史数据不足,跳过")
  335. continue
  336. # 获取前一交易日并在历史数据中匹配
  337. previous_trade_days = get_trade_days(end_date=current_trading_day, count=2)
  338. previous_trade_days = [normalize_trade_day_value(d) for d in previous_trade_days]
  339. previous_trading_day = None
  340. if len(previous_trade_days) >= 2:
  341. previous_trading_day = previous_trade_days[-2]
  342. elif len(previous_trade_days) == 1 and previous_trade_days[0] < current_trading_day:
  343. previous_trading_day = previous_trade_days[0]
  344. if previous_trading_day is None:
  345. log.info(f"{symbol} 无法确定前一交易日,跳过")
  346. continue
  347. # 在历史数据中匹配前一交易日
  348. historical_dates = historical_data.index.date
  349. match_indices = np.where(historical_dates == previous_trading_day)[0]
  350. if len(match_indices) == 0:
  351. earlier_indices = np.where(historical_dates < previous_trading_day)[0]
  352. if len(earlier_indices) == 0:
  353. log.info(f"{symbol} 历史数据缺少 {previous_trading_day} 之前的记录,跳过")
  354. continue
  355. match_indices = [earlier_indices[-1]]
  356. # 提取截至前一交易日的数据,并一次性提取所有需要的字段
  357. data_upto_yesterday = historical_data.iloc[:match_indices[-1] + 1]
  358. yesterday_data = data_upto_yesterday.iloc[-1]
  359. yesterday_close = yesterday_data['close']
  360. yesterday_open = yesterday_data['open']
  361. # 步骤3.6:获取当前价格数据
  362. current_data = get_current_data()[dominant_future]
  363. today_open = current_data.day_open
  364. # ==================== 第二部分:核心指标计算 ====================
  365. # 步骤4:计算均线相关指标(合并优化)
  366. ma_values = calculate_ma_values(data_upto_yesterday, g.ma_periods)
  367. ma_proximity_counts = calculate_ma_proximity_counts(data_upto_yesterday, g.ma_periods, g.ma_pattern_lookback_days)
  368. log.info(f"{symbol}({dominant_future}) 均线检查:")
  369. log.info(f" 均线贴近统计: {ma_proximity_counts}")
  370. # 检查均线贴近计数
  371. proximity_sum = ma_proximity_counts.get('MA5', 0) + ma_proximity_counts.get('MA10', 0)
  372. if proximity_sum < g.ma_proximity_min_threshold:
  373. log.info(f" {symbol}({dominant_future}) ✗ 均线贴近计数不足,MA5+MA10={proximity_sum} < {g.ma_proximity_min_threshold},跳过")
  374. add_to_excluded_contracts(dominant_future, 'ma_proximity', current_trading_day)
  375. continue
  376. # 步骤5:计算极端趋势天数
  377. extreme_above_count, extreme_below_count = calculate_extreme_trend_days(
  378. data_upto_yesterday,
  379. g.ma_periods,
  380. g.ma_pattern_lookback_days
  381. )
  382. extreme_total = extreme_above_count + extreme_below_count
  383. min_extreme = min(extreme_above_count, extreme_below_count)
  384. filter_threshold = max(2, g.ma_pattern_extreme_days_threshold)
  385. log.info(
  386. f" 极端趋势天数统计: 收盘在所有均线上方 {extreme_above_count} 天, 收盘在所有均线下方 {extreme_below_count} 天, "
  387. f"合计 {extreme_total} 天, min(A,B)={min_extreme} (过滤阈值: {filter_threshold})"
  388. )
  389. if extreme_above_count > 0 and extreme_below_count > 0 and min_extreme >= filter_threshold:
  390. log.info(
  391. f" {symbol}({dominant_future}) ✗ 极端趋势多空同时出现且 min(A,B)={min_extreme} ≥ {filter_threshold},跳过"
  392. )
  393. add_to_excluded_contracts(dominant_future, 'ma_extreme_trend', current_trading_day)
  394. continue
  395. # 步骤6:判断均线走势
  396. direction = None
  397. if check_ma_pattern(ma_values, 'long'):
  398. direction = 'long'
  399. elif check_ma_pattern(ma_values, 'short'):
  400. direction = 'short'
  401. else:
  402. add_to_excluded_contracts(dominant_future, 'ma_trend', current_trading_day)
  403. continue
  404. # 步骤7:检查MA5分布过滤
  405. if g.enable_ma_distribution_filter:
  406. distribution_passed, distribution_stats = check_ma5_distribution_filter(
  407. data_upto_yesterday,
  408. g.ma_distribution_lookback_days,
  409. direction,
  410. g.ma_distribution_min_ratio
  411. )
  412. log.info(
  413. f" MA5分布过滤: 方向 {direction}, 有效天数 "
  414. f"{distribution_stats['valid_days']}/{distribution_stats['lookback_days']},"
  415. f"满足天数 {distribution_stats['qualified_days']}/{distribution_stats['required_days']}"
  416. )
  417. if not distribution_passed:
  418. insufficiency = distribution_stats['valid_days'] < distribution_stats['lookback_days']
  419. reason = "有效数据不足" if insufficiency else "满足天数不足"
  420. log.info(
  421. f" {symbol}({dominant_future}) ✗ MA5分布过滤未通过({reason})"
  422. )
  423. add_to_excluded_contracts(dominant_future, 'ma5_distribution', current_trading_day)
  424. continue
  425. # 步骤8:检查历史均线模式一致性
  426. consistency_passed, consistency_ratio = check_historical_ma_pattern_consistency(
  427. historical_data, direction, g.ma_pattern_lookback_days, g.ma_pattern_consistency_threshold
  428. )
  429. if not consistency_passed:
  430. log.info(f" {symbol}({dominant_future}) ✗ 历史均线模式一致性不足 "
  431. f"({consistency_ratio:.1%} < {g.ma_pattern_consistency_threshold:.1%}),跳过")
  432. add_to_excluded_contracts(dominant_future, 'ma_consistency', current_trading_day)
  433. continue
  434. else:
  435. log.info(f" {symbol}({dominant_future}) ✓ 历史均线模式一致性检查通过 "
  436. f"({consistency_ratio:.1%} >= {g.ma_pattern_consistency_threshold:.1%})")
  437. # 步骤9:检查开盘价差(可配置开关)
  438. if g.enable_open_gap_filter:
  439. gap_check_passed = check_open_gap_filter(
  440. symbol=symbol,
  441. dominant_future=dominant_future,
  442. direction=direction,
  443. yesterday_close=yesterday_close,
  444. today_open=today_open,
  445. current_trading_day=current_trading_day
  446. )
  447. if not gap_check_passed:
  448. continue
  449. else:
  450. log.info(" 已关闭开盘价差过滤(enable_open_gap_filter=False),跳过该检查")
  451. # 步骤10:将通过检查的品种加入候选列表
  452. g.daily_ma_candidates[dominant_future] = {
  453. 'symbol': symbol,
  454. 'direction': direction,
  455. 'open_price': today_open,
  456. 'yesterday_close': yesterday_close,
  457. 'yesterday_open': yesterday_open,
  458. 'ma_values': ma_values
  459. }
  460. log.info(f" ✓✓ {symbol} 通过均线和开盘价差检查,加入候选列表")
  461. except Exception as e:
  462. g.ma_checked_underlyings.pop(symbol, None)
  463. log.warning(f"{symbol} 检查时出错: {str(e)}")
  464. continue
  465. log.info(f"候选列表更新完成,当前候选品种: {list(g.daily_ma_candidates.keys())}")
  466. log.info("=" * 60)
  467. def check_open_and_stop(context):
  468. """统一的开仓和止损止盈检查函数"""
  469. # 先检查换月移仓
  470. log.info("=" * 60)
  471. current_trading_day = get_current_trading_day(context.current_dt)
  472. log.info(f"执行开仓和止损止盈检查 - 时间: {context.current_dt}, 交易日: {current_trading_day}")
  473. log.info("=" * 60)
  474. log.info(f"先检查换月:")
  475. position_auto_switch(context)
  476. # 获取当前时间
  477. current_time = str(context.current_dt.time())[:2]
  478. # 判断是否为夜盘时间
  479. is_night_session = (current_time in ['21', '22', '23', '00', '01', '02'])
  480. # 检查是否禁止当晚操作
  481. if is_night_session and g.night_session_blocked:
  482. blocked_trading_day = normalize_trade_day_value(g.night_session_blocked_trading_day) if g.night_session_blocked_trading_day else None
  483. current_trading_day_normalized = normalize_trade_day_value(current_trading_day)
  484. if blocked_trading_day == current_trading_day_normalized:
  485. log.info(f"当晚操作已被禁止(订单状态为'new',无夜盘),跳过所有操作")
  486. return
  487. # 得到当前未完成订单
  488. orders = get_open_orders()
  489. # 循环,撤销订单
  490. if len(orders) == 0:
  491. log.debug(f"无未完成订单")
  492. else:
  493. for _order in orders.values():
  494. log.debug(f"order: {_order}")
  495. cancel_order(_order)
  496. # 第一步:检查开仓条件
  497. log.info(f"检查开仓条件:")
  498. if g.daily_ma_candidates:
  499. log.info("=" * 60)
  500. log.info(f"执行开仓检查 - 时间: {context.current_dt}, 候选品种数量: {len(g.daily_ma_candidates)}")
  501. # 遍历候选品种
  502. candidates_to_remove = []
  503. for dominant_future, candidate_info in g.daily_ma_candidates.items():
  504. try:
  505. symbol = candidate_info['symbol']
  506. direction = candidate_info['direction']
  507. open_price = candidate_info['open_price']
  508. yesterday_close = candidate_info.get('yesterday_close')
  509. yesterday_open = candidate_info.get('yesterday_open')
  510. # 检查是否已有持仓
  511. if check_symbol_prefix_match(dominant_future, context, set(g.trade_history.keys())):
  512. log.info(f"{symbol} 已有持仓,从候选列表移除")
  513. candidates_to_remove.append(dominant_future)
  514. continue
  515. # 获取当前价格
  516. current_data = get_current_data()[dominant_future]
  517. current_price = current_data.last_price
  518. # 计算当天价差
  519. intraday_diff = current_price - open_price
  520. intraday_diff_ratio = intraday_diff / open_price
  521. log.info(f"{symbol}({dominant_future}) 开仓条件检查:")
  522. log.info(f" 方向: {direction}, 开盘价: {open_price:.2f}, 当前价: {current_price:.2f}, "
  523. f"当天价差: {intraday_diff:.2f}, 变化比例: {intraday_diff_ratio:.2%}")
  524. # 判断是否满足开仓条件 - 仅检查均线穿越得分
  525. should_open = True
  526. log.info(f" 开仓条件简化:仅检查均线穿越得分,跳过策略1,2,3的判断")
  527. if should_open:
  528. ma_values = candidate_info.get('ma_values') or {}
  529. avg_5day_change = calculate_recent_average_change(dominant_future, days=5)
  530. entry_snapshot = {
  531. 'yesterday_close': yesterday_close,
  532. 'today_open': open_price,
  533. 'ma_values': ma_values.copy() if ma_values else {},
  534. 'avg_5day_change': avg_5day_change
  535. }
  536. cross_score, score_details = calculate_ma_cross_score(open_price, current_price, ma_values, direction)
  537. # 根据当前时间调整所需的均线穿越得分阈值
  538. current_time_str = str(context.current_dt.time())[:5] # HH:MM格式
  539. required_cross_score = g.ma_cross_threshold
  540. if current_time_str != '14:55':
  541. # 在14:55以外的时间,需要更高的得分阈值
  542. required_cross_score = g.ma_cross_threshold + 1
  543. log.info(f" 均线穿越得分: {cross_score}, 得分详情: {score_details}, 当前时间: {current_time_str}, 所需阈值: {required_cross_score}")
  544. # 检查得分是否满足条件
  545. score_passed = False
  546. if cross_score >= required_cross_score:
  547. # 如果得分达到阈值,检查特殊情况:只有1分且来自MA5
  548. if cross_score == 1 and required_cross_score == 1:
  549. # 检查这一分是否来自MA5
  550. from_ma5_only = len(score_details) == 1 and score_details[0]['period'] == 5
  551. if not from_ma5_only:
  552. score_passed = True
  553. log.info(f" ✓ 均线穿越得分检查通过:1分且非来自MA5")
  554. else:
  555. log.info(f" ✗ 均线穿越得分检查未通过:1分且仅来自MA5")
  556. else:
  557. score_passed = True
  558. log.info(f" ✓ 均线穿越得分检查通过")
  559. if not score_passed:
  560. log.info(f" ✗ 均线穿越得分不足或不符合条件({cross_score} < {required_cross_score} 或 1分来自MA5),跳过开仓")
  561. continue
  562. if current_time_str == '14:55':
  563. positive_cross_periods = {detail['period'] for detail in score_details if detail.get('delta', 0) > 0}
  564. if positive_cross_periods == {30}:
  565. log.info(" ✗ 尾盘仅穿越MA30,跳过开仓")
  566. continue
  567. # 执行开仓
  568. log.info(f" 准备开仓: {symbol} {direction}")
  569. target_hands, single_hand_margin = calculate_target_hands(context, dominant_future, direction)
  570. if target_hands > 0:
  571. success = open_position(context, dominant_future, target_hands, direction, single_hand_margin,
  572. f'均线形态开仓', crossed_ma_details=score_details, entry_snapshot=entry_snapshot)
  573. if success:
  574. log.info(f" ✓✓ {symbol} 开仓成功,从候选列表移除")
  575. candidates_to_remove.append(dominant_future)
  576. else:
  577. log.warning(f" ✗ {symbol} 开仓失败")
  578. else:
  579. log.warning(f" ✗ {symbol} 计算目标手数为0,跳过开仓")
  580. except Exception as e:
  581. log.warning(f"{dominant_future} 处理时出错: {str(e)}")
  582. continue
  583. # 从候选列表中移除已开仓的品种
  584. for future in candidates_to_remove:
  585. if future in g.daily_ma_candidates:
  586. del g.daily_ma_candidates[future]
  587. log.info(f"剩余候选品种: {list(g.daily_ma_candidates.keys())}")
  588. log.info("=" * 60)
  589. # 第二步:检查止损止盈
  590. log.info(f"检查止损止盈条件:")
  591. subportfolio = context.subportfolios[0]
  592. long_positions = list(subportfolio.long_positions.values())
  593. short_positions = list(subportfolio.short_positions.values())
  594. closed_count = 0
  595. skipped_count = 0
  596. for position in long_positions + short_positions:
  597. security = position.security
  598. underlying_symbol = security.split('.')[0][:-4]
  599. # 检查交易时间适配性
  600. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  601. # 如果是夜盘时间,但品种不支持夜盘交易,则跳过
  602. if is_night_session and not has_night_session:
  603. skipped_count += 1
  604. continue
  605. # 执行止损止盈检查
  606. if check_position_stop_loss_profit(context, position):
  607. closed_count += 1
  608. if closed_count > 0:
  609. log.info(f"执行了 {closed_count} 次止损止盈")
  610. if skipped_count > 0:
  611. log.info(f"夜盘时间跳过 {skipped_count} 个日间品种的止损止盈检查")
  612. def check_ma_trailing_reactivation(context):
  613. """检查是否需要恢复均线跟踪止盈"""
  614. subportfolio = context.subportfolios[0]
  615. positions = list(subportfolio.long_positions.values()) + list(subportfolio.short_positions.values())
  616. if not positions:
  617. return
  618. reenabled_count = 0
  619. current_data = get_current_data()
  620. for position in positions:
  621. security = position.security
  622. trade_info = g.trade_history.get(security)
  623. if not trade_info or trade_info.get('ma_trailing_enabled', True):
  624. continue
  625. direction = trade_info['direction']
  626. ma_values = calculate_realtime_ma_values(security, [5])
  627. ma5_value = ma_values.get('ma5')
  628. if ma5_value is None or security not in current_data:
  629. continue
  630. today_price = current_data[security].last_price
  631. if direction == 'long' and today_price > ma5_value:
  632. trade_info['ma_trailing_enabled'] = True
  633. reenabled_count += 1
  634. log.info(f"恢复均线跟踪止盈: {security} {direction}, 当前价 {today_price:.2f} > MA5 {ma5_value:.2f}")
  635. elif direction == 'short' and today_price < ma5_value:
  636. trade_info['ma_trailing_enabled'] = True
  637. reenabled_count += 1
  638. log.info(f"恢复均线跟踪止盈: {security} {direction}, 当前价 {today_price:.2f} < MA5 {ma5_value:.2f}")
  639. if reenabled_count > 0:
  640. log.info(f"恢复均线跟踪止盈持仓数量: {reenabled_count}")
  641. def check_position_stop_loss_profit(context, position):
  642. """检查单个持仓的止损止盈"""
  643. log.info(f"检查持仓: {position.security}")
  644. security = position.security
  645. if security not in g.trade_history:
  646. return False
  647. trade_info = g.trade_history[security]
  648. direction = trade_info['direction']
  649. entry_price = trade_info['entry_price']
  650. entry_time = trade_info['entry_time']
  651. entry_trading_day = trade_info.get('entry_trading_day')
  652. if entry_trading_day is None:
  653. entry_trading_day = get_current_trading_day(entry_time)
  654. trade_info['entry_trading_day'] = entry_trading_day
  655. if entry_trading_day is not None:
  656. entry_trading_day = normalize_trade_day_value(entry_trading_day)
  657. current_trading_day = normalize_trade_day_value(get_current_trading_day(context.current_dt))
  658. current_price = position.price
  659. # 计算当前盈亏比率
  660. if direction == 'long':
  661. profit_rate = (current_price - entry_price) / entry_price
  662. else:
  663. profit_rate = (entry_price - current_price) / entry_price
  664. # 检查固定止损
  665. log.info("=" * 60)
  666. log.info(f"检查固定止损:")
  667. log.info("=" * 60)
  668. if profit_rate <= -g.fixed_stop_loss_rate:
  669. log.info(f"{security} {direction} 触发固定止损 {g.fixed_stop_loss_rate:.3%}, 当前亏损率: {profit_rate:.3%}, "
  670. f"成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  671. close_position(context, security, direction)
  672. return True
  673. else:
  674. log.debug(f"{security} {direction} 未触发固定止损 {g.fixed_stop_loss_rate:.3%}, 当前亏损率: {profit_rate:.3%}, "
  675. f"成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  676. if entry_trading_day is not None and entry_trading_day == current_trading_day:
  677. log.info(f"{security} 建仓交易日内跳过动态止盈检查")
  678. return False
  679. # 检查是否启用均线跟踪止盈
  680. log.info("=" * 60)
  681. log.info(f"检查是否启用均线跟踪止盈:")
  682. log.info("=" * 60)
  683. if not trade_info.get('ma_trailing_enabled', True):
  684. log.debug(f"{security} {direction} 未启用均线跟踪止盈")
  685. return False
  686. # 检查均线跟踪止盈
  687. # 获取持仓天数
  688. entry_date = entry_time.date()
  689. current_date = context.current_dt.date()
  690. all_trade_days = get_all_trade_days()
  691. holding_days = sum((entry_date <= d <= current_date) for d in all_trade_days)
  692. # 计算变化率
  693. today_price = get_current_data()[security].last_price
  694. avg_daily_change_rate = calculate_average_daily_change_rate(security)
  695. historical_data = attribute_history(security, 1, '1d', ['close'])
  696. yesterday_close = historical_data['close'].iloc[-1]
  697. today_change_rate = abs((today_price - yesterday_close) / yesterday_close)
  698. # 根据时间判断使用的偏移量
  699. current_time = context.current_dt.time()
  700. target_time = datetime.strptime('14:55:00', '%H:%M:%S').time()
  701. if current_time > target_time:
  702. offset_ratio = g.ma_offset_ratio_close
  703. log.debug(f"当前时间是:{current_time},使用偏移量: {offset_ratio:.3%}")
  704. else:
  705. offset_ratio = g.ma_offset_ratio_normal
  706. log.debug(f"当前时间是:{current_time},使用偏移量: {offset_ratio:.3%}")
  707. # 选择止损均线
  708. close_line = None
  709. if today_change_rate >= 1.5 * avg_daily_change_rate:
  710. close_line = 'ma5' # 波动剧烈时用短周期
  711. elif holding_days <= g.days_for_adjustment:
  712. close_line = 'ma5' # 持仓初期用短周期
  713. else:
  714. close_line = 'ma5' if today_change_rate >= 1.2 * avg_daily_change_rate else 'ma10'
  715. # 计算实时均线值
  716. ma_values = calculate_realtime_ma_values(security, [5, 10])
  717. ma_value = ma_values[close_line]
  718. # 应用偏移量
  719. if direction == 'long':
  720. adjusted_ma_value = ma_value * (1 - offset_ratio)
  721. else:
  722. adjusted_ma_value = ma_value * (1 + offset_ratio)
  723. # 判断是否触发均线止损
  724. if (direction == 'long' and today_price < adjusted_ma_value) or \
  725. (direction == 'short' and today_price > adjusted_ma_value):
  726. log.info(f"触发均线跟踪止盈 {security} {direction}, 止损均线: {close_line}, "
  727. f"均线值: {ma_value:.2f}, 调整后: {adjusted_ma_value:.2f}, "
  728. f"当前价: {today_price:.2f}, 持仓天数: {holding_days}")
  729. close_position(context, security, direction)
  730. return True
  731. else:
  732. log.debug(f"未触发均线跟踪止盈 {security} {direction}, 止损均线: {close_line}, "
  733. f"均线值: {ma_value:.2f}, 调整后: {adjusted_ma_value:.2f}, "
  734. f"当前价: {today_price:.2f}, 持仓天数: {holding_days}")
  735. return False
  736. ############################ 核心辅助函数 ###################################
  737. def calculate_ma_values(data, periods):
  738. """计算均线值
  739. Args:
  740. data: DataFrame,包含'close'列的历史数据(最后一行是最新的数据)
  741. periods: list,均线周期列表,如[5, 10, 20, 30]
  742. Returns:
  743. dict: {'MA5': value, 'MA10': value, 'MA20': value, 'MA30': value}
  744. 返回最后一行(最新日期)的各周期均线值
  745. """
  746. ma_values = {}
  747. for period in periods:
  748. if len(data) >= period:
  749. # 计算最后period天的均线值
  750. ma_values[f'MA{period}'] = data['close'].iloc[-period:].mean()
  751. else:
  752. ma_values[f'MA{period}'] = None
  753. return ma_values
  754. def calculate_ma_cross_score(open_price, current_price, ma_values, direction):
  755. """根据开盘价与当前价统计多周期均线穿越得分
  756. 返回: (总得分, 得分详情列表)
  757. 得分详情: [{'period': 5, 'delta': 1}, {'period': 10, 'delta': 1}, ...]
  758. """
  759. if not ma_values:
  760. return 0, []
  761. assert direction in ('long', 'short')
  762. score = 0
  763. score_details = []
  764. periods = getattr(g, 'ma_cross_periods', g.ma_periods)
  765. for period in periods:
  766. key = f'MA{period}'
  767. ma_value = ma_values.get(key)
  768. if ma_value is None:
  769. continue
  770. cross_up = open_price < ma_value and current_price > ma_value
  771. cross_down = open_price > ma_value and current_price < ma_value
  772. if not (cross_up or cross_down):
  773. continue
  774. if direction == 'long':
  775. delta = 1 if cross_up else -1
  776. else:
  777. delta = -1 if cross_up else 1
  778. score += delta
  779. score_details.append({'period': period, 'delta': delta})
  780. log.debug(
  781. f" 均线穿越[{key}] - 开盘 {open_price:.2f}, 当前 {current_price:.2f}, "
  782. f"均线 {ma_value:.2f}, 方向 {direction}, 增量 {delta}, 当前得分 {score}"
  783. )
  784. return score, score_details
  785. def calculate_ma_proximity_counts(data, periods, lookback_days):
  786. """统计近 lookback_days 天收盘价贴近各均线的次数"""
  787. proximity_counts = {f'MA{period}': 0 for period in periods}
  788. if len(data) < lookback_days:
  789. return proximity_counts
  790. closes = data['close'].iloc[-lookback_days:]
  791. ma_series = {
  792. period: data['close'].rolling(window=period).mean().iloc[-lookback_days:]
  793. for period in periods
  794. }
  795. for idx, close_price in enumerate(closes):
  796. min_diff = None
  797. closest_period = None
  798. for period in periods:
  799. ma_value = ma_series[period].iloc[idx]
  800. if pd.isna(ma_value):
  801. continue
  802. diff = abs(close_price - ma_value)
  803. if min_diff is None or diff < min_diff:
  804. min_diff = diff
  805. closest_period = period
  806. if closest_period is not None:
  807. proximity_counts[f'MA{closest_period}'] += 1
  808. return proximity_counts
  809. def calculate_extreme_trend_days(data, periods, lookback_days):
  810. """统计过去 lookback_days 天收盘价相对所有均线的极端趋势天数"""
  811. if len(data) < lookback_days:
  812. return 0, 0
  813. recent_closes = data['close'].iloc[-lookback_days:]
  814. ma_series = {
  815. period: data['close'].rolling(window=period).mean().iloc[-lookback_days:]
  816. for period in periods
  817. }
  818. above_count = 0
  819. below_count = 0
  820. for idx, close_price in enumerate(recent_closes):
  821. ma_values = []
  822. valid = True
  823. for period in periods:
  824. ma_value = ma_series[period].iloc[idx]
  825. if pd.isna(ma_value):
  826. valid = False
  827. break
  828. ma_values.append(ma_value)
  829. if not valid or not ma_values:
  830. continue
  831. if all(close_price > ma_value for ma_value in ma_values):
  832. above_count += 1
  833. elif all(close_price < ma_value for ma_value in ma_values):
  834. below_count += 1
  835. return above_count, below_count
  836. def check_ma5_distribution_filter(data, lookback_days, direction, min_ratio):
  837. """检查近 lookback_days 天收盘价相对于MA5的分布情况"""
  838. stats = {
  839. 'lookback_days': lookback_days,
  840. 'valid_days': 0,
  841. 'qualified_days': 0,
  842. 'required_days': max(0, math.ceil(lookback_days * min_ratio))
  843. }
  844. if lookback_days <= 0:
  845. return True, stats
  846. if len(data) < max(lookback_days, 5):
  847. return False, stats
  848. recent_closes = data['close'].iloc[-lookback_days:]
  849. ma5_series = data['close'].rolling(window=5).mean().iloc[-lookback_days:]
  850. for close_price, ma5_value in zip(recent_closes, ma5_series):
  851. log.debug(f"close_price: {close_price}, ma5_value: {ma5_value}")
  852. if pd.isna(ma5_value):
  853. continue
  854. stats['valid_days'] += 1
  855. if direction == 'long' and close_price < ma5_value:
  856. stats['qualified_days'] += 1
  857. elif direction == 'short' and close_price > ma5_value:
  858. stats['qualified_days'] += 1
  859. if stats['valid_days'] < lookback_days:
  860. return False, stats
  861. return stats['qualified_days'] >= stats['required_days'], stats
  862. def check_open_gap_filter(symbol, dominant_future, direction, yesterday_close, today_open, current_trading_day):
  863. """开盘价差过滤辅助函数
  864. 根据当前策略模式(`g.ma_gap_strategy_mode`)和对应阈值检查开盘价差是否符合方向要求。
  865. Args:
  866. symbol: 品种代码(如 'AO')
  867. dominant_future: 主力合约代码(如 'AO2502.XSGE')
  868. direction: 方向,'long' 或 'short'
  869. yesterday_close: 前一交易日收盘价
  870. today_open: 当日开盘价
  871. current_trading_day: 当前期货交易日
  872. Returns:
  873. bool: True 表示通过开盘价差过滤,False 表示未通过(并已加入排除缓存)
  874. """
  875. open_gap_ratio = (today_open - yesterday_close) / yesterday_close
  876. log.info(
  877. f" 开盘价差检查: 昨收 {yesterday_close:.2f}, 今开 {today_open:.2f}, "
  878. f"价差比例 {open_gap_ratio:.2%}"
  879. )
  880. gap_check_passed = False
  881. if g.ma_gap_strategy_mode == 1:
  882. # 方案1:多头检查上跳,空头检查下跳
  883. if direction == 'long' and open_gap_ratio >= g.ma_open_gap_threshold:
  884. log.info(
  885. f" {symbol}({dominant_future}) ✓ 方案1多头开盘价差检查通过 "
  886. f"({open_gap_ratio:.2%} >= {g.ma_open_gap_threshold:.2%})"
  887. )
  888. gap_check_passed = True
  889. elif direction == 'short' and open_gap_ratio <= -g.ma_open_gap_threshold:
  890. log.info(
  891. f" {symbol}({dominant_future}) ✓ 方案1空头开盘价差检查通过 "
  892. f"({open_gap_ratio:.2%} <= {-g.ma_open_gap_threshold:.2%})"
  893. )
  894. gap_check_passed = True
  895. elif g.ma_gap_strategy_mode == 2 or g.ma_gap_strategy_mode == 3:
  896. # 方案2和方案3:多头检查下跳,空头检查上跳
  897. if direction == 'long' and open_gap_ratio <= -g.ma_open_gap_threshold2:
  898. log.info(
  899. f" {symbol}({dominant_future}) ✓ 方案{g.ma_gap_strategy_mode}多头开盘价差检查通过 "
  900. f"({open_gap_ratio:.2%} <= {-g.ma_open_gap_threshold2:.2%})"
  901. )
  902. gap_check_passed = True
  903. elif direction == 'short' and open_gap_ratio >= g.ma_open_gap_threshold2:
  904. log.info(
  905. f" {symbol}({dominant_future}) ✓ 方案{g.ma_gap_strategy_mode}空头开盘价差检查通过 "
  906. f"({open_gap_ratio:.2%} >= {g.ma_open_gap_threshold2:.2%})"
  907. )
  908. gap_check_passed = True
  909. if not gap_check_passed:
  910. add_to_excluded_contracts(dominant_future, 'open_gap', current_trading_day)
  911. return False
  912. return True
  913. def check_ma_pattern(ma_values, direction):
  914. """检查均线排列模式是否符合方向要求
  915. Args:
  916. ma_values: dict,包含MA5, MA10, MA20, MA30的均线值
  917. direction: str,'long'或'short'
  918. Returns:
  919. bool: 是否符合均线排列要求
  920. """
  921. ma5 = ma_values['MA5']
  922. ma10 = ma_values['MA10']
  923. ma20 = ma_values['MA20']
  924. ma30 = ma_values['MA30']
  925. if direction == 'long':
  926. # 多头模式:MA30 <= MA20 <= MA10 <= MA5 或 MA30 <= MA20 <= MA5 <= MA10
  927. # 或者:MA20 <= MA30 <= MA10 <= MA5 或 MA20 <= MA30 <= MA5 <= MA10
  928. pattern1 = (ma30 <= ma20 <= ma10 <= ma5)
  929. pattern2 = (ma30 <= ma20 <= ma5 <= ma10)
  930. pattern3 = (ma20 <= ma30 <= ma10 <= ma5)
  931. pattern4 = (ma20 <= ma30 <= ma5 <= ma10)
  932. return pattern1 or pattern2 or pattern3 or pattern4
  933. elif direction == 'short':
  934. # 空头模式:MA10 <= MA5 <= MA20 <= MA30 或 MA5 <= MA10 <= MA20 <= MA30
  935. # 或者:MA10 <= MA5 <= MA30 <= MA20 或 MA5 <= MA10 <= MA30 <= MA20
  936. pattern1 = (ma10 <= ma5 <= ma20 <= ma30)
  937. pattern2 = (ma5 <= ma10 <= ma20 <= ma30)
  938. pattern3 = (ma10 <= ma5 <= ma30 <= ma20)
  939. pattern4 = (ma5 <= ma10 <= ma30 <= ma20)
  940. return pattern1 or pattern2 or pattern3 or pattern4
  941. else:
  942. return False
  943. def check_historical_ma_pattern_consistency(historical_data, direction, lookback_days, consistency_threshold):
  944. """检查历史均线模式的一致性
  945. Args:
  946. historical_data: DataFrame,包含足够天数的历史数据
  947. direction: str,'long'或'short'
  948. lookback_days: int,检查过去多少天
  949. consistency_threshold: float,一致性阈值(0-1之间)
  950. Returns:
  951. tuple: (bool, float) - (是否通过一致性检查, 实际一致性比例)
  952. """
  953. if len(historical_data) < max(g.ma_periods) + lookback_days:
  954. # 历史数据不足
  955. return False, 0.0
  956. match_count = 0
  957. total_count = lookback_days
  958. # log.debug(f"历史均线模式一致性检查: {direction}, 检查过去{lookback_days}天的数据")
  959. # log.debug(f"历史数据: {historical_data}")
  960. # 检查过去lookback_days天的均线模式
  961. for i in range(lookback_days):
  962. # 获取倒数第(i+1)天的数据(i=0时是昨天,i=1时是前天,依此类推)
  963. end_idx = -(i + 1)
  964. # 获取这一天的具体日期
  965. date = historical_data.index[end_idx].date()
  966. # 获取到该天(包括该天)为止的所有数据
  967. if i == 0:
  968. data_slice = historical_data
  969. else:
  970. data_slice = historical_data.iloc[:-i]
  971. # 计算该天的均线值
  972. # log.debug(f"对于倒数第{i+1}天,end_idx: {end_idx},日期: {date},计算均线值: {data_slice}")
  973. ma_values = calculate_ma_values(data_slice, g.ma_periods)
  974. # log.debug(f"end_idx: {end_idx},日期: {date},倒数第{i+1}天的均线值: {ma_values}")
  975. # 检查是否符合模式
  976. if check_ma_pattern(ma_values, direction):
  977. match_count += 1
  978. # log.debug(f"日期: {date},对于倒数第{i+1}天,历史均线模式一致性检查: {direction} 符合模式")
  979. # else:
  980. # log.debug(f"日期: {date},对于倒数第{i+1}天,历史均线模式一致性检查: {direction} 不符合模式")
  981. consistency_ratio = match_count / total_count
  982. passed = consistency_ratio >= consistency_threshold
  983. return passed, consistency_ratio
  984. ############################ 交易执行函数 ###################################
  985. def open_position(context, security, target_hands, direction, single_hand_margin, reason='', crossed_ma_details=None, entry_snapshot=None):
  986. """开仓"""
  987. try:
  988. # 记录交易前的可用资金
  989. cash_before = context.portfolio.available_cash
  990. # 使用order_target按手数开仓
  991. order = order_target(security, target_hands, side=direction)
  992. log.debug(f"order: {order}")
  993. # 检查订单状态,如果为'new'说明当晚没有夜盘
  994. if order is not None:
  995. order_status = str(order.status).lower()
  996. if order_status == 'new':
  997. # 取消订单
  998. cancel_order(order)
  999. current_trading_day = get_current_trading_day(context.current_dt)
  1000. g.night_session_blocked = True
  1001. g.night_session_blocked_trading_day = current_trading_day
  1002. log.warning(f"订单状态为'new',说明{current_trading_day}当晚没有夜盘,已取消订单: {security} {direction} {target_hands}手,并禁止当晚所有操作")
  1003. return False
  1004. if order is not None and order.filled > 0:
  1005. # 记录交易后的可用资金
  1006. cash_after = context.portfolio.available_cash
  1007. # 计算实际资金变化
  1008. cash_change = cash_before - cash_after
  1009. # 计算保证金变化
  1010. margin_change = single_hand_margin * target_hands
  1011. # 获取订单价格和数量
  1012. order_price = order.avg_cost if order.avg_cost else order.price
  1013. order_amount = order.filled
  1014. # 记录当日交易
  1015. underlying_symbol = security.split('.')[0][:-4]
  1016. g.today_trades.append({
  1017. 'security': security, # 合约代码
  1018. 'underlying_symbol': underlying_symbol, # 标的代码
  1019. 'direction': direction, # 方向
  1020. 'order_amount': order_amount, # 订单数量
  1021. 'order_price': order_price, # 订单价格
  1022. 'cash_change': cash_change, # 资金变化
  1023. 'margin_change': margin_change, # 保证金
  1024. 'time': context.current_dt # 时间
  1025. })
  1026. # 记录交易信息
  1027. entry_trading_day = get_current_trading_day(context.current_dt)
  1028. # 处理穿越均线信息
  1029. crossed_ma_lines = []
  1030. if crossed_ma_details:
  1031. crossed_ma_lines = [f"MA{detail['period']}" for detail in crossed_ma_details if detail.get('delta', 0) > 0]
  1032. snapshot_copy = None
  1033. if entry_snapshot:
  1034. snapshot_copy = {
  1035. 'yesterday_close': entry_snapshot.get('yesterday_close'),
  1036. 'today_open': entry_snapshot.get('today_open'),
  1037. 'ma_values': (entry_snapshot.get('ma_values') or {}).copy(),
  1038. 'avg_5day_change': entry_snapshot.get('avg_5day_change')
  1039. }
  1040. g.trade_history[security] = {
  1041. 'entry_price': order_price,
  1042. 'target_hands': target_hands,
  1043. 'actual_hands': order_amount,
  1044. 'actual_margin': margin_change,
  1045. 'direction': direction,
  1046. 'entry_time': context.current_dt,
  1047. 'entry_trading_day': entry_trading_day,
  1048. 'crossed_ma_lines': crossed_ma_lines, # 记录穿越的均线
  1049. 'entry_snapshot': snapshot_copy
  1050. }
  1051. ma_trailing_enabled = True
  1052. ma_values_at_entry = calculate_realtime_ma_values(security, [5])
  1053. ma5_value = ma_values_at_entry.get('ma5')
  1054. if ma5_value is not None:
  1055. if direction == 'long' and order_price < ma5_value:
  1056. ma_trailing_enabled = False
  1057. log.info(f"禁用均线跟踪止盈: {security} {direction}, 开仓价 {order_price:.2f} < MA5 {ma5_value:.2f}")
  1058. elif direction == 'short' and order_price > ma5_value:
  1059. ma_trailing_enabled = False
  1060. log.info(f"禁用均线跟踪止盈: {security} {direction}, 开仓价 {order_price:.2f} > MA5 {ma5_value:.2f}")
  1061. g.trade_history[security]['ma_trailing_enabled'] = ma_trailing_enabled
  1062. crossed_ma_str = ', '.join(crossed_ma_lines) if crossed_ma_lines else '无'
  1063. log.info(f"开仓成功: {security} {direction} {order_amount}手 @{order_price:.2f}, "
  1064. f"保证金: {margin_change:.0f}, 资金变化: {cash_change:.0f}, 原因: {reason}, "
  1065. f"穿越均线: {crossed_ma_str}")
  1066. return True
  1067. except Exception as e:
  1068. log.warning(f"开仓失败 {security}: {str(e)}")
  1069. return False
  1070. def close_position(context, security, direction):
  1071. """平仓"""
  1072. try:
  1073. # 使用order_target平仓到0手
  1074. order = order_target(security, 0, side=direction)
  1075. if order is not None and order.filled > 0:
  1076. underlying_symbol = security.split('.')[0][:-4]
  1077. # 记录当日交易(平仓)
  1078. g.today_trades.append({
  1079. 'security': security,
  1080. 'underlying_symbol': underlying_symbol,
  1081. 'direction': direction,
  1082. 'order_amount': -order.filled,
  1083. 'order_price': order.avg_cost if order.avg_cost else order.price,
  1084. 'cash_change': 0,
  1085. 'time': context.current_dt
  1086. })
  1087. log.info(f"平仓成功: {underlying_symbol} {direction} {order.filled}手")
  1088. # 从交易历史中移除
  1089. if security in g.trade_history:
  1090. del g.trade_history[security]
  1091. log.debug(f"从交易历史中移除: {security}")
  1092. else:
  1093. log.info(f"平仓失败: {security} {direction} {order.filled}手")
  1094. return True
  1095. except Exception as e:
  1096. log.warning(f"平仓失败 {security}: {str(e)}")
  1097. return False
  1098. ############################ 辅助函数 ###################################
  1099. def get_futures_config(underlying_symbol, config_key=None, default_value=None):
  1100. """获取期货品种配置信息的辅助函数"""
  1101. if underlying_symbol not in g.futures_config:
  1102. if config_key and default_value is not None:
  1103. return default_value
  1104. return {}
  1105. if config_key is None:
  1106. return g.futures_config[underlying_symbol]
  1107. return g.futures_config[underlying_symbol].get(config_key, default_value)
  1108. def get_margin_rate(underlying_symbol, direction, default_rate=0.10):
  1109. """获取保证金比例的辅助函数"""
  1110. return g.futures_config.get(underlying_symbol, {}).get('margin_rate', {}).get(direction, default_rate)
  1111. def get_multiplier(underlying_symbol, default_multiplier=10):
  1112. """获取合约乘数的辅助函数"""
  1113. return g.futures_config.get(underlying_symbol, {}).get('multiplier', default_multiplier)
  1114. def add_to_excluded_contracts(dominant_future, reason, current_trading_day):
  1115. """将合约添加到排除缓存"""
  1116. g.excluded_contracts[dominant_future] = {
  1117. 'reason': reason,
  1118. 'trading_day': current_trading_day
  1119. }
  1120. def has_reached_trading_start(current_dt, trading_start_time_str, has_night_session=False):
  1121. """判断当前是否已到达合约允许交易的起始时间"""
  1122. if not trading_start_time_str:
  1123. return True
  1124. try:
  1125. hour, minute = [int(part) for part in trading_start_time_str.split(':')[:2]]
  1126. except Exception:
  1127. return True
  1128. start_time = time(hour, minute)
  1129. current_time = current_dt.time()
  1130. if has_night_session:
  1131. if current_time >= start_time:
  1132. return True
  1133. if current_time < time(12, 0):
  1134. return True
  1135. if time(8, 30) <= current_time <= time(15, 30):
  1136. return True
  1137. return False
  1138. if current_time < start_time:
  1139. return False
  1140. if current_time >= time(20, 0):
  1141. return False
  1142. return True
  1143. def calculate_target_hands(context, security, direction):
  1144. """计算目标开仓手数"""
  1145. current_price = get_current_data()[security].last_price
  1146. underlying_symbol = security.split('.')[0][:-4]
  1147. # 使用保证金比例
  1148. margin_rate = get_margin_rate(underlying_symbol, direction)
  1149. multiplier = get_multiplier(underlying_symbol)
  1150. # 计算单手保证金
  1151. single_hand_margin = current_price * multiplier * margin_rate
  1152. log.debug(f"计算单手保证金: {current_price:.2f} * {multiplier:.2f} * {margin_rate:.2f} = {single_hand_margin:.2f}")
  1153. # 还要考虑可用资金限制
  1154. available_cash = context.portfolio.available_cash * g.usage_percentage
  1155. # 根据单个标的最大持仓保证金限制计算开仓数量
  1156. max_margin = g.max_margin_per_position
  1157. if single_hand_margin <= max_margin:
  1158. # 如果单手保证金不超过最大限制,计算最大可开仓手数
  1159. max_hands = int(max_margin / single_hand_margin)
  1160. max_hands_by_cash = int(available_cash / single_hand_margin)
  1161. # 取两者较小值
  1162. actual_hands = min(max_hands, max_hands_by_cash)
  1163. # 确保至少开1手
  1164. actual_hands = max(1, actual_hands)
  1165. log.info(f"单手保证金: {single_hand_margin:.0f}, 目标开仓手数: {actual_hands}")
  1166. return actual_hands, single_hand_margin
  1167. else:
  1168. # 如果单手保证金超过最大限制,默认开仓1手
  1169. actual_hands = 1
  1170. log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手")
  1171. return actual_hands, single_hand_margin
  1172. def check_symbol_prefix_match(symbol, context, hold_symbols):
  1173. """检查是否有相似的持仓品种"""
  1174. log.debug(f"检查持仓")
  1175. symbol_prefix = symbol[:-9]
  1176. long_positions = context.subportfolios[0].long_positions
  1177. short_positions = context.subportfolios[0].short_positions
  1178. log.debug(f"long_positions: {long_positions}, short_positions: {short_positions}")
  1179. for hold_symbol in hold_symbols:
  1180. hold_symbol_prefix = hold_symbol[:-9] if len(hold_symbol) > 9 else hold_symbol
  1181. if symbol_prefix == hold_symbol_prefix:
  1182. return True
  1183. return False
  1184. def calculate_average_daily_change_rate(security, days=30):
  1185. """计算日均变化率"""
  1186. historical_data = attribute_history(security, days + 1, '1d', ['close'])
  1187. daily_change_rates = abs(historical_data['close'].pct_change()).iloc[1:]
  1188. return daily_change_rates.mean()
  1189. def calculate_realtime_ma_values(security, ma_periods):
  1190. """计算包含当前价格的实时均线值"""
  1191. if not ma_periods:
  1192. return {}
  1193. max_period = max(ma_periods)
  1194. history_days = max_period + MA_ADDITIONAL_HISTORY_DAYS
  1195. historical_data = attribute_history(security, history_days, '1d', ['close'])
  1196. today_price = get_current_data()[security].last_price
  1197. close_prices = historical_data['close'].tolist() + [today_price]
  1198. ma_values = {}
  1199. for period in ma_periods:
  1200. if len(close_prices) >= period:
  1201. ma_values[f'ma{period}'] = sum(close_prices[-period:]) / period
  1202. else:
  1203. ma_values[f'ma{period}'] = None
  1204. return ma_values
  1205. def calculate_recent_average_change(security, days=5):
  1206. """计算最近days天日间收盘涨幅的平均值"""
  1207. if days <= 0:
  1208. return None
  1209. try:
  1210. history = attribute_history(security, days + 1, '1d', ['close'])
  1211. except Exception as e:
  1212. log.warning(f"{security} 获取历史数据失败(均值涨幅计算): {str(e)}")
  1213. return None
  1214. closes = history['close']
  1215. if len(closes) < days + 1:
  1216. return None
  1217. pct_changes = closes.pct_change().dropna().abs() # 取绝对值,更关心涨跌幅度而不是方向
  1218. if len(pct_changes) < days:
  1219. return None
  1220. return pct_changes.iloc[-days:].mean()
  1221. def format_entry_details(entry_snapshot):
  1222. """格式化记录到CSV的价格、均线及扩展信息"""
  1223. if not entry_snapshot:
  1224. return ''
  1225. def fmt(value):
  1226. return f"{value:.2f}" if value is not None else "NA"
  1227. ma_values = entry_snapshot.get('ma_values') or {}
  1228. snapshot_parts = [
  1229. f"prev_close:{fmt(entry_snapshot.get('yesterday_close'))}",
  1230. f"open:{fmt(entry_snapshot.get('today_open'))}"
  1231. ]
  1232. for period in [5, 10, 20, 30, 60]:
  1233. key_upper = f"MA{period}"
  1234. key_lower = key_upper.lower()
  1235. value = ma_values.get(key_upper)
  1236. if value is None:
  1237. value = ma_values.get(key_lower)
  1238. snapshot_parts.append(f"{key_upper}:{fmt(value)}")
  1239. avg_change = entry_snapshot.get('avg_5day_change')
  1240. if avg_change is not None:
  1241. snapshot_parts.append(f"AVG5:{avg_change:.4%}")
  1242. else:
  1243. snapshot_parts.append("AVG5:NA")
  1244. return '|'.join(snapshot_parts)
  1245. def save_today_new_positions_to_csv(context):
  1246. """将当天新增的持仓记录追加保存到CSV文件"""
  1247. log.info(f"保存当天新增的持仓记录到CSV文件")
  1248. if not g.trade_history:
  1249. return
  1250. current_trading_day = normalize_trade_day_value(get_current_trading_day(context.current_dt))
  1251. # 筛选当天新开仓的记录
  1252. today_new_positions = []
  1253. for security, trade_info in g.trade_history.items():
  1254. entry_trading_day = normalize_trade_day_value(trade_info.get('entry_trading_day'))
  1255. if entry_trading_day == current_trading_day:
  1256. underlying_symbol = security.split('.')[0][:-4]
  1257. crossed_ma_lines = trade_info.get('crossed_ma_lines', [])
  1258. # 使用分号分隔多条均线,避免CSV格式问题
  1259. crossed_ma_str = ';'.join(crossed_ma_lines) if crossed_ma_lines else ''
  1260. details = format_entry_details(trade_info.get('entry_snapshot'))
  1261. today_new_positions.append({
  1262. 'security': security,
  1263. 'underlying_symbol': underlying_symbol,
  1264. 'direction': trade_info['direction'],
  1265. 'entry_price': trade_info['entry_price'],
  1266. 'actual_hands': trade_info['actual_hands'],
  1267. 'actual_margin': trade_info['actual_margin'],
  1268. 'entry_time': trade_info['entry_time'].strftime('%H:%M:%S'), # 只保留时间
  1269. 'entry_trading_day': str(entry_trading_day),
  1270. 'crossed_ma_lines': crossed_ma_str,
  1271. 'details': details
  1272. })
  1273. # 如果没有当天新增的记录,直接返回
  1274. if not today_new_positions:
  1275. log.debug("当天无新增持仓记录,跳过保存")
  1276. return
  1277. try:
  1278. filename = 'trade_history.csv'
  1279. # 尝试读取现有文件
  1280. existing_content = ''
  1281. file_exists = False
  1282. try:
  1283. existing_content_bytes = read_file(filename)
  1284. if existing_content_bytes:
  1285. existing_content = existing_content_bytes.decode('utf-8')
  1286. file_exists = True
  1287. except:
  1288. pass
  1289. # 准备CSV内容
  1290. csv_lines = []
  1291. # 如果文件不存在,添加表头
  1292. if not file_exists:
  1293. header = 'security,underlying_symbol,direction,entry_price,actual_hands,actual_margin,entry_time,entry_trading_day,crossed_ma_lines,details'
  1294. csv_lines.append(header)
  1295. # 添加新记录
  1296. for pos in today_new_positions:
  1297. line = f"{pos['security']},{pos['underlying_symbol']},{pos['direction']},{pos['entry_price']:.2f},{pos['actual_hands']},{pos['actual_margin']:.2f},{pos['entry_time']},{pos['entry_trading_day']},{pos['crossed_ma_lines']},{pos['details']}"
  1298. csv_lines.append(line)
  1299. # 合并内容:现有内容 + 新内容
  1300. new_content = '\n'.join(csv_lines)
  1301. if file_exists:
  1302. final_content = existing_content.rstrip('\n') + '\n' + new_content
  1303. else:
  1304. final_content = new_content
  1305. # 写入文件 - 将字符串编码为bytes以符合JoinQuant API要求
  1306. write_file(filename, final_content.encode('utf-8'))
  1307. log.info(f"已追加{len(today_new_positions)}条当天新增持仓记录到文件: {filename}")
  1308. except Exception as e:
  1309. log.warning(f"保存持仓记录到CSV文件时出错: {str(e)}")
  1310. def sync_trade_history_with_positions(context):
  1311. """同步g.trade_history与实际持仓,清理已平仓但记录未删除的持仓"""
  1312. if not g.trade_history:
  1313. return
  1314. subportfolio = context.subportfolios[0]
  1315. actual_positions = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  1316. # 找出g.trade_history中有记录但实际已平仓的合约
  1317. stale_records = []
  1318. for security in g.trade_history.keys():
  1319. if security not in actual_positions:
  1320. stale_records.append(security)
  1321. # 清理这些过期记录
  1322. if stale_records:
  1323. log.info("=" * 60)
  1324. log.info("发现持仓记录与实际持仓不同步,进行清理:")
  1325. for security in stale_records:
  1326. trade_info = g.trade_history[security]
  1327. underlying_symbol = security.split('.')[0][:-4]
  1328. log.info(f" 清理过期记录: {underlying_symbol}({security}) {trade_info['direction']}, "
  1329. f"成本价: {trade_info['entry_price']:.2f}, "
  1330. f"入场时间: {trade_info['entry_time']}")
  1331. del g.trade_history[security]
  1332. log.info(f"共清理 {len(stale_records)} 条过期持仓记录")
  1333. log.info("=" * 60)
  1334. def after_market_close(context):
  1335. """收盘后运行函数"""
  1336. log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
  1337. # 保存当天新增的持仓记录到CSV文件
  1338. save_today_new_positions_to_csv(context)
  1339. # 同步检查:清理g.trade_history中已平仓但记录未删除的持仓
  1340. sync_trade_history_with_positions(context)
  1341. # 清空候选列表(每天重新检查)
  1342. g.daily_ma_candidates = {}
  1343. # 清空排除缓存(每天重新检查)
  1344. excluded_count = len(g.excluded_contracts)
  1345. if excluded_count > 0:
  1346. log.info(f"清空排除缓存,共 {excluded_count} 个合约")
  1347. g.excluded_contracts = {}
  1348. # 重置夜盘禁止操作标志
  1349. if g.night_session_blocked:
  1350. log.info(f"重置夜盘禁止操作标志")
  1351. g.night_session_blocked = False
  1352. g.night_session_blocked_trading_day = None
  1353. # 只有当天有交易时才打印统计信息
  1354. if g.today_trades:
  1355. print_daily_trading_summary(context)
  1356. # 清空当日交易记录
  1357. g.today_trades = []
  1358. log.info('##############################################################')
  1359. def print_daily_trading_summary(context):
  1360. """打印当日交易汇总"""
  1361. if not g.today_trades:
  1362. return
  1363. log.info("\n=== 当日交易汇总 ===")
  1364. total_margin = 0
  1365. for trade in g.today_trades:
  1366. if trade['order_amount'] > 0: # 开仓
  1367. log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
  1368. f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f}")
  1369. total_margin += trade['cash_change']
  1370. else: # 平仓
  1371. log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
  1372. f"价格:{trade['order_price']:.2f}")
  1373. log.info(f"当日保证金占用: {total_margin:.0f}")
  1374. log.info("==================\n")
  1375. ########################## 自动移仓换月函数 #################################
  1376. def position_auto_switch(context, pindex=0, switch_func=None, callback=None):
  1377. """期货自动移仓换月"""
  1378. import re
  1379. subportfolio = context.subportfolios[pindex]
  1380. symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  1381. switch_result = []
  1382. for symbol in symbols:
  1383. match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
  1384. if not match:
  1385. raise ValueError("未知期货标的: {}".format(symbol))
  1386. else:
  1387. underlying_symbol = match.groupdict()["underlying_symbol"]
  1388. trading_start = get_futures_config(underlying_symbol, 'trading_start_time', None)
  1389. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  1390. # log.debug(f"移仓换月: {symbol}, 交易开始时间: {trading_start}, 夜盘: {has_night_session}")
  1391. if trading_start and not has_reached_trading_start(context.current_dt, trading_start, has_night_session):
  1392. # log.info("{} 当前时间 {} 未到达交易开始时间 {} (夜盘:{} ),跳过移仓".format(
  1393. # symbol,
  1394. # context.current_dt.strftime('%H:%M:%S'),
  1395. # trading_start,
  1396. # has_night_session
  1397. # ))
  1398. continue
  1399. dominant = get_dominant_future(underlying_symbol)
  1400. cur = get_current_data()
  1401. symbol_last_price = cur[symbol].last_price
  1402. dominant_last_price = cur[dominant].last_price
  1403. if dominant > symbol:
  1404. for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
  1405. if symbol not in positions_.keys():
  1406. continue
  1407. else :
  1408. p = positions_[symbol]
  1409. if switch_func is not None:
  1410. switch_func(context, pindex, p, dominant)
  1411. else:
  1412. amount = p.total_amount
  1413. # 跌停不能开空和平多,涨停不能开多和平空
  1414. if p.side == "long":
  1415. symbol_low_limit = cur[symbol].low_limit
  1416. dominant_high_limit = cur[dominant].high_limit
  1417. if symbol_last_price <= symbol_low_limit:
  1418. log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
  1419. continue
  1420. elif dominant_last_price >= dominant_high_limit:
  1421. log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(dominant))
  1422. continue
  1423. else:
  1424. log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
  1425. order_old = order_target(symbol, 0, side='long')
  1426. if order_old != None and order_old.filled > 0:
  1427. order_new = order_target(dominant, amount, side='long')
  1428. if order_new != None and order_new.filled > 0:
  1429. switch_result.append({"before": symbol, "after": dominant, "side": "long"})
  1430. # 换月成功,更新交易记录
  1431. if symbol in g.trade_history:
  1432. # 复制旧的交易记录作为基础
  1433. old_entry_price = g.trade_history[symbol]['entry_price']
  1434. g.trade_history[dominant] = g.trade_history[symbol].copy()
  1435. # 更新成本价为新合约的实际开仓价
  1436. new_entry_price = None
  1437. if order_new.avg_cost and order_new.avg_cost > 0:
  1438. new_entry_price = order_new.avg_cost
  1439. g.trade_history[dominant]['entry_price'] = order_new.avg_cost
  1440. elif order_new.price and order_new.price > 0:
  1441. new_entry_price = order_new.price
  1442. g.trade_history[dominant]['entry_price'] = order_new.price
  1443. else:
  1444. # 如果订单价格无效,使用当前价格作为成本价
  1445. new_entry_price = dominant_last_price
  1446. g.trade_history[dominant]['entry_price'] = dominant_last_price
  1447. # 更新入场时间
  1448. g.trade_history[dominant]['entry_time'] = context.current_dt
  1449. # 更新入场交易日
  1450. g.trade_history[dominant]['entry_trading_day'] = get_current_trading_day(context.current_dt)
  1451. # 删除旧合约的交易记录
  1452. del g.trade_history[symbol]
  1453. log.info(f"移仓换月成本价更新: {symbol} -> {dominant}, "
  1454. f"旧成本价: {old_entry_price:.2f}, 新成本价: {new_entry_price:.2f}")
  1455. else:
  1456. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1457. if p.side == "short":
  1458. symbol_high_limit = cur[symbol].high_limit
  1459. dominant_low_limit = cur[dominant].low_limit
  1460. if symbol_last_price >= symbol_high_limit:
  1461. log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
  1462. continue
  1463. elif dominant_last_price <= dominant_low_limit:
  1464. log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(dominant))
  1465. continue
  1466. else:
  1467. log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
  1468. order_old = order_target(symbol, 0, side='short')
  1469. if order_old != None and order_old.filled > 0:
  1470. order_new = order_target(dominant, amount, side='short')
  1471. if order_new != None and order_new.filled > 0:
  1472. switch_result.append({"before": symbol, "after": dominant, "side": "short"})
  1473. # 换月成功,更新交易记录
  1474. if symbol in g.trade_history:
  1475. # 复制旧的交易记录作为基础
  1476. old_entry_price = g.trade_history[symbol]['entry_price']
  1477. g.trade_history[dominant] = g.trade_history[symbol].copy()
  1478. # 更新成本价为新合约的实际开仓价
  1479. new_entry_price = None
  1480. if order_new.avg_cost and order_new.avg_cost > 0:
  1481. new_entry_price = order_new.avg_cost
  1482. g.trade_history[dominant]['entry_price'] = order_new.avg_cost
  1483. elif order_new.price and order_new.price > 0:
  1484. new_entry_price = order_new.price
  1485. g.trade_history[dominant]['entry_price'] = order_new.price
  1486. else:
  1487. # 如果订单价格无效,使用当前价格作为成本价
  1488. new_entry_price = dominant_last_price
  1489. g.trade_history[dominant]['entry_price'] = dominant_last_price
  1490. # 更新入场时间
  1491. g.trade_history[dominant]['entry_time'] = context.current_dt
  1492. # 更新入场交易日
  1493. g.trade_history[dominant]['entry_trading_day'] = get_current_trading_day(context.current_dt)
  1494. # 删除旧合约的交易记录
  1495. del g.trade_history[symbol]
  1496. log.info(f"移仓换月成本价更新: {symbol} -> {dominant}, "
  1497. f"旧成本价: {old_entry_price:.2f}, 新成本价: {new_entry_price:.2f}")
  1498. else:
  1499. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1500. if callback:
  1501. callback(context, pindex, p, dominant)
  1502. return switch_result