MAPatternStrategy_v002.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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 = ['AU'] # 空列表表示考虑所有品种
  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 = False
  523. if g.ma_gap_strategy_mode == 1:
  524. # 方案1:根据参数决定是否检查日内价差
  525. if not g.check_intraday_spread:
  526. log.info(f" 方案1跳过日内价差检查(check_intraday_spread=False)")
  527. should_open = True
  528. elif direction == 'long' and intraday_diff > 0:
  529. log.info(f" ✓ 方案1多头当天价差检查通过 ({intraday_diff:.2f} > 0)")
  530. should_open = True
  531. elif direction == 'short' and intraday_diff < 0:
  532. log.info(f" ✓ 方案1空头当天价差检查通过 ({intraday_diff:.2f} < 0)")
  533. should_open = True
  534. else:
  535. log.info(f" ✗ 方案1当天价差不符合{direction}方向要求")
  536. elif g.ma_gap_strategy_mode == 2:
  537. # 方案2:强制检查日内变化,使用专用阈值
  538. if direction == 'long' and intraday_diff_ratio >= g.ma_intraday_threshold_scheme2:
  539. log.info(f" ✓ 方案2多头日内变化检查通过 ({intraday_diff_ratio:.2%} >= {g.ma_intraday_threshold_scheme2:.2%})")
  540. should_open = True
  541. elif direction == 'short' and intraday_diff_ratio <= -g.ma_intraday_threshold_scheme2:
  542. log.info(f" ✓ 方案2空头日内变化检查通过 ({intraday_diff_ratio:.2%} <= {-g.ma_intraday_threshold_scheme2:.2%})")
  543. should_open = True
  544. else:
  545. log.info(f" ✗ 方案2日内变化不符合{direction}方向要求(阈值: ±{g.ma_intraday_threshold_scheme2:.2%})")
  546. elif g.ma_gap_strategy_mode == 3:
  547. # 方案3:下跳后上涨(多头)或上跳后下跌(空头),并检查当前价格与前一日开盘收盘均值的关系
  548. if yesterday_open is not None and yesterday_close is not None:
  549. prev_day_avg = (yesterday_open + yesterday_close) / 2
  550. log.debug(f" 前一日开盘价: {yesterday_open:.2f}, 前一日收盘价: {yesterday_close:.2f}, 前一日开盘收盘均值: {prev_day_avg:.2f}")
  551. if direction == 'long':
  552. # 多头:当前价格 >= 前一日开盘收盘均值
  553. if current_price >= prev_day_avg:
  554. log.info(f" ✓ 方案3多头入场条件通过: 当前价 {current_price:.2f} >= 前日均值 {prev_day_avg:.2f}")
  555. should_open = True
  556. else:
  557. log.info(f" ✗ 方案3多头入场条件未通过: 当前价 {current_price:.2f} < 前日均值 {prev_day_avg:.2f}")
  558. elif direction == 'short':
  559. # 空头:当前价格 <= 前一日开盘收盘均值
  560. if current_price <= prev_day_avg:
  561. log.info(f" ✓ 方案3空头入场条件通过: 当前价 {current_price:.2f} <= 前日均值 {prev_day_avg:.2f}")
  562. should_open = True
  563. else:
  564. log.info(f" ✗ 方案3空头入场条件未通过: 当前价 {current_price:.2f} > 前日均值 {prev_day_avg:.2f}")
  565. else:
  566. log.info(f" ✗ 方案3缺少前一日开盘或收盘价数据")
  567. if should_open:
  568. ma_values = candidate_info.get('ma_values') or {}
  569. cross_score = calculate_ma_cross_score(open_price, current_price, ma_values, direction)
  570. # 根据当前时间调整所需的均线穿越得分阈值
  571. current_time_str = str(context.current_dt.time())[:5] # HH:MM格式
  572. required_cross_score = g.ma_cross_threshold
  573. if current_time_str != '14:55':
  574. # 在14:55以外的时间,需要更高的得分阈值
  575. required_cross_score = g.ma_cross_threshold + 1
  576. log.info(f" 均线穿越得分: {cross_score}, 当前时间: {current_time_str}, 所需阈值: {required_cross_score}")
  577. if cross_score < required_cross_score:
  578. log.info(f" ✗ 均线穿越得分不足({cross_score} < {required_cross_score}),跳过开仓")
  579. continue
  580. # 执行开仓
  581. log.info(f" 准备开仓: {symbol} {direction}")
  582. target_hands, single_hand_margin = calculate_target_hands(context, dominant_future, direction)
  583. if target_hands > 0:
  584. success = open_position(context, dominant_future, target_hands, direction, single_hand_margin,
  585. f'均线形态开仓')
  586. if success:
  587. log.info(f" ✓✓ {symbol} 开仓成功,从候选列表移除")
  588. candidates_to_remove.append(dominant_future)
  589. else:
  590. log.warning(f" ✗ {symbol} 开仓失败")
  591. else:
  592. log.warning(f" ✗ {symbol} 计算目标手数为0,跳过开仓")
  593. except Exception as e:
  594. log.warning(f"{dominant_future} 处理时出错: {str(e)}")
  595. continue
  596. # 从候选列表中移除已开仓的品种
  597. for future in candidates_to_remove:
  598. if future in g.daily_ma_candidates:
  599. del g.daily_ma_candidates[future]
  600. log.info(f"剩余候选品种: {list(g.daily_ma_candidates.keys())}")
  601. log.info("=" * 60)
  602. # 第二步:检查止损止盈
  603. log.info(f"检查止损止盈条件:")
  604. subportfolio = context.subportfolios[0]
  605. long_positions = list(subportfolio.long_positions.values())
  606. short_positions = list(subportfolio.short_positions.values())
  607. closed_count = 0
  608. skipped_count = 0
  609. for position in long_positions + short_positions:
  610. security = position.security
  611. underlying_symbol = security.split('.')[0][:-4]
  612. # 检查交易时间适配性
  613. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  614. # 如果是夜盘时间,但品种不支持夜盘交易,则跳过
  615. if is_night_session and not has_night_session:
  616. skipped_count += 1
  617. continue
  618. # 执行止损止盈检查
  619. if check_position_stop_loss_profit(context, position):
  620. closed_count += 1
  621. if closed_count > 0:
  622. log.info(f"执行了 {closed_count} 次止损止盈")
  623. if skipped_count > 0:
  624. log.info(f"夜盘时间跳过 {skipped_count} 个日间品种的止损止盈检查")
  625. def check_ma_trailing_reactivation(context):
  626. """检查是否需要恢复均线跟踪止盈"""
  627. subportfolio = context.subportfolios[0]
  628. positions = list(subportfolio.long_positions.values()) + list(subportfolio.short_positions.values())
  629. if not positions:
  630. return
  631. reenabled_count = 0
  632. current_data = get_current_data()
  633. for position in positions:
  634. security = position.security
  635. trade_info = g.trade_history.get(security)
  636. if not trade_info or trade_info.get('ma_trailing_enabled', True):
  637. continue
  638. direction = trade_info['direction']
  639. ma_values = calculate_realtime_ma_values(security, [5])
  640. ma5_value = ma_values.get('ma5')
  641. if ma5_value is None or security not in current_data:
  642. continue
  643. today_price = current_data[security].last_price
  644. if direction == 'long' and today_price > ma5_value:
  645. trade_info['ma_trailing_enabled'] = True
  646. reenabled_count += 1
  647. log.info(f"恢复均线跟踪止盈: {security} {direction}, 当前价 {today_price:.2f} > MA5 {ma5_value:.2f}")
  648. elif direction == 'short' and today_price < ma5_value:
  649. trade_info['ma_trailing_enabled'] = True
  650. reenabled_count += 1
  651. log.info(f"恢复均线跟踪止盈: {security} {direction}, 当前价 {today_price:.2f} < MA5 {ma5_value:.2f}")
  652. if reenabled_count > 0:
  653. log.info(f"恢复均线跟踪止盈持仓数量: {reenabled_count}")
  654. def check_position_stop_loss_profit(context, position):
  655. """检查单个持仓的止损止盈"""
  656. log.info(f"检查持仓: {position.security}")
  657. security = position.security
  658. if security not in g.trade_history:
  659. return False
  660. trade_info = g.trade_history[security]
  661. direction = trade_info['direction']
  662. entry_price = trade_info['entry_price']
  663. entry_time = trade_info['entry_time']
  664. entry_trading_day = trade_info.get('entry_trading_day')
  665. if entry_trading_day is None:
  666. entry_trading_day = get_current_trading_day(entry_time)
  667. trade_info['entry_trading_day'] = entry_trading_day
  668. if entry_trading_day is not None:
  669. entry_trading_day = normalize_trade_day_value(entry_trading_day)
  670. current_trading_day = normalize_trade_day_value(get_current_trading_day(context.current_dt))
  671. current_price = position.price
  672. # 计算当前盈亏比率
  673. if direction == 'long':
  674. profit_rate = (current_price - entry_price) / entry_price
  675. else:
  676. profit_rate = (entry_price - current_price) / entry_price
  677. # 检查固定止损
  678. log.info("=" * 60)
  679. log.info(f"检查固定止损:")
  680. log.info("=" * 60)
  681. if profit_rate <= -g.fixed_stop_loss_rate:
  682. log.info(f"{security} {direction} 触发固定止损 {g.fixed_stop_loss_rate:.3%}, 当前亏损率: {profit_rate:.3%}, "
  683. f"成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  684. close_position(context, security, direction)
  685. return True
  686. else:
  687. log.debug(f"{security} {direction} 未触发固定止损 {g.fixed_stop_loss_rate:.3%}, 当前亏损率: {profit_rate:.3%}, "
  688. f"成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  689. if entry_trading_day is not None and entry_trading_day == current_trading_day:
  690. log.info(f"{security} 建仓交易日内跳过动态止盈检查")
  691. return False
  692. # 检查是否启用均线跟踪止盈
  693. log.info("=" * 60)
  694. log.info(f"检查是否启用均线跟踪止盈:")
  695. log.info("=" * 60)
  696. if not trade_info.get('ma_trailing_enabled', True):
  697. log.debug(f"{security} {direction} 未启用均线跟踪止盈")
  698. return False
  699. # 检查均线跟踪止盈
  700. # 获取持仓天数
  701. entry_date = entry_time.date()
  702. current_date = context.current_dt.date()
  703. all_trade_days = get_all_trade_days()
  704. holding_days = sum((entry_date <= d <= current_date) for d in all_trade_days)
  705. # 计算变化率
  706. today_price = get_current_data()[security].last_price
  707. avg_daily_change_rate = calculate_average_daily_change_rate(security)
  708. historical_data = attribute_history(security, 1, '1d', ['close'])
  709. yesterday_close = historical_data['close'].iloc[-1]
  710. today_change_rate = abs((today_price - yesterday_close) / yesterday_close)
  711. # 根据时间判断使用的偏移量
  712. current_time = context.current_dt.time()
  713. target_time = datetime.strptime('14:55:00', '%H:%M:%S').time()
  714. if current_time > target_time:
  715. offset_ratio = g.ma_offset_ratio_close
  716. log.debug(f"当前时间是:{current_time},使用偏移量: {offset_ratio:.3%}")
  717. else:
  718. offset_ratio = g.ma_offset_ratio_normal
  719. log.debug(f"当前时间是:{current_time},使用偏移量: {offset_ratio:.3%}")
  720. # 选择止损均线
  721. close_line = None
  722. if today_change_rate >= 1.5 * avg_daily_change_rate:
  723. close_line = 'ma5' # 波动剧烈时用短周期
  724. elif holding_days <= g.days_for_adjustment:
  725. close_line = 'ma5' # 持仓初期用短周期
  726. else:
  727. close_line = 'ma5' if today_change_rate >= 1.2 * avg_daily_change_rate else 'ma10'
  728. # 计算实时均线值
  729. ma_values = calculate_realtime_ma_values(security, [5, 10])
  730. ma_value = ma_values[close_line]
  731. # 应用偏移量
  732. if direction == 'long':
  733. adjusted_ma_value = ma_value * (1 - offset_ratio)
  734. else:
  735. adjusted_ma_value = ma_value * (1 + offset_ratio)
  736. # 判断是否触发均线止损
  737. if (direction == 'long' and today_price < adjusted_ma_value) or \
  738. (direction == 'short' and today_price > adjusted_ma_value):
  739. log.info(f"触发均线跟踪止盈 {security} {direction}, 止损均线: {close_line}, "
  740. f"均线值: {ma_value:.2f}, 调整后: {adjusted_ma_value:.2f}, "
  741. f"当前价: {today_price:.2f}, 持仓天数: {holding_days}")
  742. close_position(context, security, direction)
  743. return True
  744. else:
  745. log.debug(f"未触发均线跟踪止盈 {security} {direction}, 止损均线: {close_line}, "
  746. f"均线值: {ma_value:.2f}, 调整后: {adjusted_ma_value:.2f}, "
  747. f"当前价: {today_price:.2f}, 持仓天数: {holding_days}")
  748. return False
  749. ############################ 核心辅助函数 ###################################
  750. def calculate_ma_values(data, periods):
  751. """计算均线值
  752. Args:
  753. data: DataFrame,包含'close'列的历史数据(最后一行是最新的数据)
  754. periods: list,均线周期列表,如[5, 10, 20, 30]
  755. Returns:
  756. dict: {'MA5': value, 'MA10': value, 'MA20': value, 'MA30': value}
  757. 返回最后一行(最新日期)的各周期均线值
  758. """
  759. ma_values = {}
  760. for period in periods:
  761. if len(data) >= period:
  762. # 计算最后period天的均线值
  763. ma_values[f'MA{period}'] = data['close'].iloc[-period:].mean()
  764. else:
  765. ma_values[f'MA{period}'] = None
  766. return ma_values
  767. def calculate_ma_cross_score(open_price, current_price, ma_values, direction):
  768. """根据开盘价与当前价统计多周期均线穿越得分"""
  769. if not ma_values:
  770. return 0
  771. assert direction in ('long', 'short')
  772. score = 0
  773. for period in g.ma_periods:
  774. key = f'MA{period}'
  775. ma_value = ma_values.get(key)
  776. if ma_value is None:
  777. continue
  778. cross_up = open_price < ma_value and current_price > ma_value
  779. cross_down = open_price > ma_value and current_price < ma_value
  780. if not (cross_up or cross_down):
  781. continue
  782. if direction == 'long':
  783. delta = 1 if cross_up else -1
  784. else:
  785. delta = -1 if cross_up else 1
  786. score += delta
  787. log.debug(
  788. f" 均线穿越[{key}] - 开盘 {open_price:.2f}, 当前 {current_price:.2f}, "
  789. f"均线 {ma_value:.2f}, 方向 {direction}, 增量 {delta}, 当前得分 {score}"
  790. )
  791. return score
  792. def calculate_ma_proximity_counts(data, periods, lookback_days):
  793. """统计近 lookback_days 天收盘价贴近各均线的次数"""
  794. proximity_counts = {f'MA{period}': 0 for period in periods}
  795. if len(data) < lookback_days:
  796. return proximity_counts
  797. 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. for idx, close_price in enumerate(closes):
  803. min_diff = None
  804. closest_period = None
  805. for period in periods:
  806. ma_value = ma_series[period].iloc[idx]
  807. if pd.isna(ma_value):
  808. continue
  809. diff = abs(close_price - ma_value)
  810. if min_diff is None or diff < min_diff:
  811. min_diff = diff
  812. closest_period = period
  813. if closest_period is not None:
  814. proximity_counts[f'MA{closest_period}'] += 1
  815. return proximity_counts
  816. def calculate_extreme_trend_days(data, periods, lookback_days):
  817. """统计过去 lookback_days 天收盘价相对所有均线的极端趋势天数"""
  818. if len(data) < lookback_days:
  819. return 0, 0
  820. recent_closes = data['close'].iloc[-lookback_days:]
  821. ma_series = {
  822. period: data['close'].rolling(window=period).mean().iloc[-lookback_days:]
  823. for period in periods
  824. }
  825. above_count = 0
  826. below_count = 0
  827. for idx, close_price in enumerate(recent_closes):
  828. ma_values = []
  829. valid = True
  830. for period in periods:
  831. ma_value = ma_series[period].iloc[idx]
  832. if pd.isna(ma_value):
  833. valid = False
  834. break
  835. ma_values.append(ma_value)
  836. if not valid or not ma_values:
  837. continue
  838. if all(close_price > ma_value for ma_value in ma_values):
  839. above_count += 1
  840. elif all(close_price < ma_value for ma_value in ma_values):
  841. below_count += 1
  842. return above_count, below_count
  843. def check_ma5_distribution_filter(data, lookback_days, direction, min_ratio):
  844. """检查近 lookback_days 天收盘价相对于MA5的分布情况"""
  845. stats = {
  846. 'lookback_days': lookback_days,
  847. 'valid_days': 0,
  848. 'qualified_days': 0,
  849. 'required_days': max(0, math.ceil(lookback_days * min_ratio))
  850. }
  851. if lookback_days <= 0:
  852. return True, stats
  853. if len(data) < max(lookback_days, 5):
  854. return False, stats
  855. recent_closes = data['close'].iloc[-lookback_days:]
  856. ma5_series = data['close'].rolling(window=5).mean().iloc[-lookback_days:]
  857. for close_price, ma5_value in zip(recent_closes, ma5_series):
  858. log.debug(f"close_price: {close_price}, ma5_value: {ma5_value}")
  859. if pd.isna(ma5_value):
  860. continue
  861. stats['valid_days'] += 1
  862. if direction == 'long' and close_price < ma5_value:
  863. stats['qualified_days'] += 1
  864. elif direction == 'short' and close_price > ma5_value:
  865. stats['qualified_days'] += 1
  866. if stats['valid_days'] < lookback_days:
  867. return False, stats
  868. return stats['qualified_days'] >= stats['required_days'], stats
  869. def check_ma_pattern(ma_values, direction):
  870. """检查均线排列模式是否符合方向要求
  871. Args:
  872. ma_values: dict,包含MA5, MA10, MA20, MA30的均线值
  873. direction: str,'long'或'short'
  874. Returns:
  875. bool: 是否符合均线排列要求
  876. """
  877. ma5 = ma_values['MA5']
  878. ma10 = ma_values['MA10']
  879. ma20 = ma_values['MA20']
  880. ma30 = ma_values['MA30']
  881. if direction == 'long':
  882. # 多头模式:MA30 <= MA20 <= MA10 <= MA5 或 MA30 <= MA20 <= MA5 <= MA10
  883. # 或者:MA20 <= MA30 <= MA10 <= MA5 或 MA20 <= MA30 <= MA5 <= MA10
  884. pattern1 = (ma30 <= ma20 <= ma10 <= ma5)
  885. pattern2 = (ma30 <= ma20 <= ma5 <= ma10)
  886. pattern3 = (ma20 <= ma30 <= ma10 <= ma5)
  887. pattern4 = (ma20 <= ma30 <= ma5 <= ma10)
  888. return pattern1 or pattern2 or pattern3 or pattern4
  889. elif direction == 'short':
  890. # 空头模式:MA10 <= MA5 <= MA20 <= MA30 或 MA5 <= MA10 <= MA20 <= MA30
  891. # 或者:MA10 <= MA5 <= MA30 <= MA20 或 MA5 <= MA10 <= MA30 <= MA20
  892. pattern1 = (ma10 <= ma5 <= ma20 <= ma30)
  893. pattern2 = (ma5 <= ma10 <= ma20 <= ma30)
  894. pattern3 = (ma10 <= ma5 <= ma30 <= ma20)
  895. pattern4 = (ma5 <= ma10 <= ma30 <= ma20)
  896. return pattern1 or pattern2 or pattern3 or pattern4
  897. else:
  898. return False
  899. def check_historical_ma_pattern_consistency(historical_data, direction, lookback_days, consistency_threshold):
  900. """检查历史均线模式的一致性
  901. Args:
  902. historical_data: DataFrame,包含足够天数的历史数据
  903. direction: str,'long'或'short'
  904. lookback_days: int,检查过去多少天
  905. consistency_threshold: float,一致性阈值(0-1之间)
  906. Returns:
  907. tuple: (bool, float) - (是否通过一致性检查, 实际一致性比例)
  908. """
  909. if len(historical_data) < max(g.ma_periods) + lookback_days:
  910. # 历史数据不足
  911. return False, 0.0
  912. match_count = 0
  913. total_count = lookback_days
  914. # log.debug(f"历史均线模式一致性检查: {direction}, 检查过去{lookback_days}天的数据")
  915. # log.debug(f"历史数据: {historical_data}")
  916. # 检查过去lookback_days天的均线模式
  917. for i in range(lookback_days):
  918. # 获取倒数第(i+1)天的数据(i=0时是昨天,i=1时是前天,依此类推)
  919. end_idx = -(i + 1)
  920. # 获取这一天的具体日期
  921. date = historical_data.index[end_idx].date()
  922. # 获取到该天(包括该天)为止的所有数据
  923. if i == 0:
  924. data_slice = historical_data
  925. else:
  926. data_slice = historical_data.iloc[:-i]
  927. # 计算该天的均线值
  928. # log.debug(f"对于倒数第{i+1}天,end_idx: {end_idx},日期: {date},计算均线值: {data_slice}")
  929. ma_values = calculate_ma_values(data_slice, g.ma_periods)
  930. # log.debug(f"end_idx: {end_idx},日期: {date},倒数第{i+1}天的均线值: {ma_values}")
  931. # 检查是否符合模式
  932. if check_ma_pattern(ma_values, direction):
  933. match_count += 1
  934. # log.debug(f"日期: {date},对于倒数第{i+1}天,历史均线模式一致性检查: {direction} 符合模式")
  935. # else:
  936. # log.debug(f"日期: {date},对于倒数第{i+1}天,历史均线模式一致性检查: {direction} 不符合模式")
  937. consistency_ratio = match_count / total_count
  938. passed = consistency_ratio >= consistency_threshold
  939. return passed, consistency_ratio
  940. ############################ 交易执行函数 ###################################
  941. def open_position(context, security, target_hands, direction, single_hand_margin, reason=''):
  942. """开仓"""
  943. try:
  944. # 记录交易前的可用资金
  945. cash_before = context.portfolio.available_cash
  946. # 使用order_target按手数开仓
  947. order = order_target(security, target_hands, side=direction)
  948. log.debug(f"order: {order}")
  949. # 检查订单状态,如果为'new'说明当晚没有夜盘
  950. if order is not None:
  951. order_status = str(order.status).lower()
  952. if order_status == 'new':
  953. # 取消订单
  954. cancel_order(order)
  955. current_trading_day = get_current_trading_day(context.current_dt)
  956. g.night_session_blocked = True
  957. g.night_session_blocked_trading_day = current_trading_day
  958. log.warning(f"订单状态为'new',说明{current_trading_day}当晚没有夜盘,已取消订单: {security} {direction} {target_hands}手,并禁止当晚所有操作")
  959. return False
  960. if order is not None and order.filled > 0:
  961. # 记录交易后的可用资金
  962. cash_after = context.portfolio.available_cash
  963. # 计算实际资金变化
  964. cash_change = cash_before - cash_after
  965. # 计算保证金变化
  966. margin_change = single_hand_margin * target_hands
  967. # 获取订单价格和数量
  968. order_price = order.avg_cost if order.avg_cost else order.price
  969. order_amount = order.filled
  970. # 记录当日交易
  971. underlying_symbol = security.split('.')[0][:-4]
  972. g.today_trades.append({
  973. 'security': security, # 合约代码
  974. 'underlying_symbol': underlying_symbol, # 标的代码
  975. 'direction': direction, # 方向
  976. 'order_amount': order_amount, # 订单数量
  977. 'order_price': order_price, # 订单价格
  978. 'cash_change': cash_change, # 资金变化
  979. 'margin_change': margin_change, # 保证金
  980. 'time': context.current_dt # 时间
  981. })
  982. # 记录交易信息
  983. entry_trading_day = get_current_trading_day(context.current_dt)
  984. g.trade_history[security] = {
  985. 'entry_price': order_price,
  986. 'target_hands': target_hands,
  987. 'actual_hands': order_amount,
  988. 'actual_margin': margin_change,
  989. 'direction': direction,
  990. 'entry_time': context.current_dt,
  991. 'entry_trading_day': entry_trading_day
  992. }
  993. ma_trailing_enabled = True
  994. ma_values_at_entry = calculate_realtime_ma_values(security, [5])
  995. ma5_value = ma_values_at_entry.get('ma5')
  996. if ma5_value is not None:
  997. if direction == 'long' and order_price < ma5_value:
  998. ma_trailing_enabled = False
  999. log.info(f"禁用均线跟踪止盈: {security} {direction}, 开仓价 {order_price:.2f} < MA5 {ma5_value:.2f}")
  1000. elif direction == 'short' and order_price > ma5_value:
  1001. ma_trailing_enabled = False
  1002. log.info(f"禁用均线跟踪止盈: {security} {direction}, 开仓价 {order_price:.2f} > MA5 {ma5_value:.2f}")
  1003. g.trade_history[security]['ma_trailing_enabled'] = ma_trailing_enabled
  1004. log.info(f"开仓成功: {security} {direction} {order_amount}手 @{order_price:.2f}, "
  1005. f"保证金: {margin_change:.0f}, 资金变化: {cash_change:.0f}, 原因: {reason}")
  1006. return True
  1007. except Exception as e:
  1008. log.warning(f"开仓失败 {security}: {str(e)}")
  1009. return False
  1010. def close_position(context, security, direction):
  1011. """平仓"""
  1012. try:
  1013. # 使用order_target平仓到0手
  1014. order = order_target(security, 0, side=direction)
  1015. if order is not None and order.filled > 0:
  1016. underlying_symbol = security.split('.')[0][:-4]
  1017. # 记录当日交易(平仓)
  1018. g.today_trades.append({
  1019. 'security': security,
  1020. 'underlying_symbol': underlying_symbol,
  1021. 'direction': direction,
  1022. 'order_amount': -order.filled,
  1023. 'order_price': order.avg_cost if order.avg_cost else order.price,
  1024. 'cash_change': 0,
  1025. 'time': context.current_dt
  1026. })
  1027. log.info(f"平仓成功: {underlying_symbol} {direction} {order.filled}手")
  1028. # 从交易历史中移除
  1029. if security in g.trade_history:
  1030. del g.trade_history[security]
  1031. return True
  1032. except Exception as e:
  1033. log.warning(f"平仓失败 {security}: {str(e)}")
  1034. return False
  1035. ############################ 辅助函数 ###################################
  1036. def get_futures_config(underlying_symbol, config_key=None, default_value=None):
  1037. """获取期货品种配置信息的辅助函数"""
  1038. if underlying_symbol not in g.futures_config:
  1039. if config_key and default_value is not None:
  1040. return default_value
  1041. return {}
  1042. if config_key is None:
  1043. return g.futures_config[underlying_symbol]
  1044. return g.futures_config[underlying_symbol].get(config_key, default_value)
  1045. def get_margin_rate(underlying_symbol, direction, default_rate=0.10):
  1046. """获取保证金比例的辅助函数"""
  1047. return g.futures_config.get(underlying_symbol, {}).get('margin_rate', {}).get(direction, default_rate)
  1048. def get_multiplier(underlying_symbol, default_multiplier=10):
  1049. """获取合约乘数的辅助函数"""
  1050. return g.futures_config.get(underlying_symbol, {}).get('multiplier', default_multiplier)
  1051. def add_to_excluded_contracts(dominant_future, reason, current_trading_day):
  1052. """将合约添加到排除缓存"""
  1053. g.excluded_contracts[dominant_future] = {
  1054. 'reason': reason,
  1055. 'trading_day': current_trading_day
  1056. }
  1057. def has_reached_trading_start(current_dt, trading_start_time_str, has_night_session=False):
  1058. """判断当前是否已到达合约允许交易的起始时间"""
  1059. if not trading_start_time_str:
  1060. return True
  1061. try:
  1062. hour, minute = [int(part) for part in trading_start_time_str.split(':')[:2]]
  1063. except Exception:
  1064. return True
  1065. start_time = time(hour, minute)
  1066. current_time = current_dt.time()
  1067. if has_night_session:
  1068. if current_time >= start_time:
  1069. return True
  1070. if current_time < time(12, 0):
  1071. return True
  1072. if time(8, 30) <= current_time <= time(15, 30):
  1073. return True
  1074. return False
  1075. if current_time < start_time:
  1076. return False
  1077. if current_time >= time(20, 0):
  1078. return False
  1079. return True
  1080. def calculate_target_hands(context, security, direction):
  1081. """计算目标开仓手数"""
  1082. current_price = get_current_data()[security].last_price
  1083. underlying_symbol = security.split('.')[0][:-4]
  1084. # 使用保证金比例
  1085. margin_rate = get_margin_rate(underlying_symbol, direction)
  1086. multiplier = get_multiplier(underlying_symbol)
  1087. # 计算单手保证金
  1088. single_hand_margin = current_price * multiplier * margin_rate
  1089. log.debug(f"计算单手保证金: {current_price:.2f} * {multiplier:.2f} * {margin_rate:.2f} = {single_hand_margin:.2f}")
  1090. # 还要考虑可用资金限制
  1091. available_cash = context.portfolio.available_cash * g.usage_percentage
  1092. # 根据单个标的最大持仓保证金限制计算开仓数量
  1093. max_margin = g.max_margin_per_position
  1094. if single_hand_margin <= max_margin:
  1095. # 如果单手保证金不超过最大限制,计算最大可开仓手数
  1096. max_hands = int(max_margin / single_hand_margin)
  1097. max_hands_by_cash = int(available_cash / single_hand_margin)
  1098. # 取两者较小值
  1099. actual_hands = min(max_hands, max_hands_by_cash)
  1100. # 确保至少开1手
  1101. actual_hands = max(1, actual_hands)
  1102. log.info(f"单手保证金: {single_hand_margin:.0f}, 目标开仓手数: {actual_hands}")
  1103. return actual_hands, single_hand_margin
  1104. else:
  1105. # 如果单手保证金超过最大限制,默认开仓1手
  1106. actual_hands = 1
  1107. log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手")
  1108. return actual_hands, single_hand_margin
  1109. def check_symbol_prefix_match(symbol, hold_symbols):
  1110. """检查是否有相似的持仓品种"""
  1111. symbol_prefix = symbol[:-9]
  1112. for hold_symbol in hold_symbols:
  1113. hold_symbol_prefix = hold_symbol[:-9] if len(hold_symbol) > 9 else hold_symbol
  1114. if symbol_prefix == hold_symbol_prefix:
  1115. return True
  1116. return False
  1117. def calculate_average_daily_change_rate(security, days=30):
  1118. """计算日均变化率"""
  1119. historical_data = attribute_history(security, days + 1, '1d', ['close'])
  1120. daily_change_rates = abs(historical_data['close'].pct_change()).iloc[1:]
  1121. return daily_change_rates.mean()
  1122. def calculate_realtime_ma_values(security, ma_periods):
  1123. """计算包含当前价格的实时均线值"""
  1124. historical_data = attribute_history(security, max(ma_periods), '1d', ['close'])
  1125. today_price = get_current_data()[security].last_price
  1126. close_prices = historical_data['close'].tolist() + [today_price]
  1127. ma_values = {f'ma{period}': sum(close_prices[-period:]) / period for period in ma_periods}
  1128. return ma_values
  1129. def after_market_close(context):
  1130. """收盘后运行函数"""
  1131. log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
  1132. # 清空候选列表(每天重新检查)
  1133. g.daily_ma_candidates = {}
  1134. # 清空排除缓存(每天重新检查)
  1135. excluded_count = len(g.excluded_contracts)
  1136. if excluded_count > 0:
  1137. log.info(f"清空排除缓存,共 {excluded_count} 个合约")
  1138. g.excluded_contracts = {}
  1139. # 重置夜盘禁止操作标志
  1140. if g.night_session_blocked:
  1141. log.info(f"重置夜盘禁止操作标志")
  1142. g.night_session_blocked = False
  1143. g.night_session_blocked_trading_day = None
  1144. # 只有当天有交易时才打印统计信息
  1145. if g.today_trades:
  1146. print_daily_trading_summary(context)
  1147. # 清空当日交易记录
  1148. g.today_trades = []
  1149. log.info('##############################################################')
  1150. def print_daily_trading_summary(context):
  1151. """打印当日交易汇总"""
  1152. if not g.today_trades:
  1153. return
  1154. log.info("\n=== 当日交易汇总 ===")
  1155. total_margin = 0
  1156. for trade in g.today_trades:
  1157. if trade['order_amount'] > 0: # 开仓
  1158. log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
  1159. f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f}")
  1160. total_margin += trade['cash_change']
  1161. else: # 平仓
  1162. log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
  1163. f"价格:{trade['order_price']:.2f}")
  1164. log.info(f"当日保证金占用: {total_margin:.0f}")
  1165. log.info("==================\n")
  1166. ########################## 自动移仓换月函数 #################################
  1167. def position_auto_switch(context, pindex=0, switch_func=None, callback=None):
  1168. """期货自动移仓换月"""
  1169. import re
  1170. subportfolio = context.subportfolios[pindex]
  1171. symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  1172. switch_result = []
  1173. for symbol in symbols:
  1174. match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
  1175. if not match:
  1176. raise ValueError("未知期货标的: {}".format(symbol))
  1177. else:
  1178. underlying_symbol = match.groupdict()["underlying_symbol"]
  1179. trading_start = get_futures_config(underlying_symbol, 'trading_start_time', None)
  1180. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  1181. # log.debug(f"移仓换月: {symbol}, 交易开始时间: {trading_start}, 夜盘: {has_night_session}")
  1182. if trading_start and not has_reached_trading_start(context.current_dt, trading_start, has_night_session):
  1183. # log.info("{} 当前时间 {} 未到达交易开始时间 {} (夜盘:{} ),跳过移仓".format(
  1184. # symbol,
  1185. # context.current_dt.strftime('%H:%M:%S'),
  1186. # trading_start,
  1187. # has_night_session
  1188. # ))
  1189. continue
  1190. dominant = get_dominant_future(underlying_symbol)
  1191. cur = get_current_data()
  1192. symbol_last_price = cur[symbol].last_price
  1193. dominant_last_price = cur[dominant].last_price
  1194. if dominant > symbol:
  1195. for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
  1196. if symbol not in positions_.keys():
  1197. continue
  1198. else :
  1199. p = positions_[symbol]
  1200. if switch_func is not None:
  1201. switch_func(context, pindex, p, dominant)
  1202. else:
  1203. amount = p.total_amount
  1204. # 跌停不能开空和平多,涨停不能开多和平空
  1205. if p.side == "long":
  1206. symbol_low_limit = cur[symbol].low_limit
  1207. dominant_high_limit = cur[dominant].high_limit
  1208. if symbol_last_price <= symbol_low_limit:
  1209. log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
  1210. continue
  1211. elif dominant_last_price >= dominant_high_limit:
  1212. log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(dominant))
  1213. continue
  1214. else:
  1215. log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
  1216. order_old = order_target(symbol, 0, side='long')
  1217. if order_old != None and order_old.filled > 0:
  1218. order_new = order_target(dominant, amount, side='long')
  1219. if order_new != None and order_new.filled > 0:
  1220. switch_result.append({"before": symbol, "after": dominant, "side": "long"})
  1221. # 换月成功,更新交易记录
  1222. if symbol in g.trade_history:
  1223. # 复制旧的交易记录作为基础
  1224. old_entry_price = g.trade_history[symbol]['entry_price']
  1225. g.trade_history[dominant] = g.trade_history[symbol].copy()
  1226. # 更新成本价为新合约的实际开仓价
  1227. new_entry_price = None
  1228. if order_new.avg_cost and order_new.avg_cost > 0:
  1229. new_entry_price = order_new.avg_cost
  1230. g.trade_history[dominant]['entry_price'] = order_new.avg_cost
  1231. elif order_new.price and order_new.price > 0:
  1232. new_entry_price = order_new.price
  1233. g.trade_history[dominant]['entry_price'] = order_new.price
  1234. else:
  1235. # 如果订单价格无效,使用当前价格作为成本价
  1236. new_entry_price = dominant_last_price
  1237. g.trade_history[dominant]['entry_price'] = dominant_last_price
  1238. # 更新入场时间
  1239. g.trade_history[dominant]['entry_time'] = context.current_dt
  1240. # 更新入场交易日
  1241. g.trade_history[dominant]['entry_trading_day'] = get_current_trading_day(context.current_dt)
  1242. # 删除旧合约的交易记录
  1243. del g.trade_history[symbol]
  1244. log.info(f"移仓换月成本价更新: {symbol} -> {dominant}, "
  1245. f"旧成本价: {old_entry_price:.2f}, 新成本价: {new_entry_price:.2f}")
  1246. else:
  1247. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1248. if p.side == "short":
  1249. symbol_high_limit = cur[symbol].high_limit
  1250. dominant_low_limit = cur[dominant].low_limit
  1251. if symbol_last_price >= symbol_high_limit:
  1252. log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
  1253. continue
  1254. elif dominant_last_price <= dominant_low_limit:
  1255. log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(dominant))
  1256. continue
  1257. else:
  1258. log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
  1259. order_old = order_target(symbol, 0, side='short')
  1260. if order_old != None and order_old.filled > 0:
  1261. order_new = order_target(dominant, amount, side='short')
  1262. if order_new != None and order_new.filled > 0:
  1263. switch_result.append({"before": symbol, "after": dominant, "side": "short"})
  1264. # 换月成功,更新交易记录
  1265. if symbol in g.trade_history:
  1266. # 复制旧的交易记录作为基础
  1267. old_entry_price = g.trade_history[symbol]['entry_price']
  1268. g.trade_history[dominant] = g.trade_history[symbol].copy()
  1269. # 更新成本价为新合约的实际开仓价
  1270. new_entry_price = None
  1271. if order_new.avg_cost and order_new.avg_cost > 0:
  1272. new_entry_price = order_new.avg_cost
  1273. g.trade_history[dominant]['entry_price'] = order_new.avg_cost
  1274. elif order_new.price and order_new.price > 0:
  1275. new_entry_price = order_new.price
  1276. g.trade_history[dominant]['entry_price'] = order_new.price
  1277. else:
  1278. # 如果订单价格无效,使用当前价格作为成本价
  1279. new_entry_price = dominant_last_price
  1280. g.trade_history[dominant]['entry_price'] = dominant_last_price
  1281. # 更新入场时间
  1282. g.trade_history[dominant]['entry_time'] = context.current_dt
  1283. # 更新入场交易日
  1284. g.trade_history[dominant]['entry_trading_day'] = get_current_trading_day(context.current_dt)
  1285. # 删除旧合约的交易记录
  1286. del g.trade_history[symbol]
  1287. log.info(f"移仓换月成本价更新: {symbol} -> {dominant}, "
  1288. f"旧成本价: {old_entry_price:.2f}, 新成本价: {new_entry_price:.2f}")
  1289. else:
  1290. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1291. if callback:
  1292. callback(context, pindex, p, dominant)
  1293. return switch_result