MAPatternStrategy_v002.py 73 KB

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