MAPatternStrategy_v002.py 79 KB

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