MAPatternStrategy_v002.py 70 KB

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