MAPatternStrategy_v002.py 80 KB

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