MAPatternStrategy_v002.py 86 KB

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