# 导入函数库
from jqdata import *
from jqlib.technical_analysis import *
from datetime import *
import time
from decimal import Decimal
from MyTT import *
import requests
import json
import talib # 引入TA-Lib库,用于技术分析
## 初始化函数,设定基准等等
def initialize(context):
#参数
get_canshu(context)
# 设定上证指数作为基准
#'000300.XSHG'
set_benchmark("000852.XSHG" )
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
set_option("avoid_future_data", True)
log.info('初始函数开始运行且全局只运行一次')
log.set_level('order', 'error')
### 期货相关设定 ###
# 设定账户为金融账户
set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
# 期货类每笔交易时的手续费是:买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023,close_today_commission=0.000023), type='index_futures')
# 设定保证金比例
set_option('futures_margin_rate', 0.15)
# 设置期货交易的滑点
set_slippage(StepRelatedSlippage(2))
# 开盘运行
run_daily( before_market_open, time='09:30', reference_security=g.reference)
# 盘中每分钟运行一次
run_daily(market_open, time='every_bar', reference_security=g.reference)
def get_canshu(context):
g.unit='1m' #数据运行周期
g.flag = True #开平仓标记
# g.reference = "IM9999.CCFX" #分析参考标的
g.reference = "000852.XSHG" #分析参考标的
g.zft1 = False
g.long_short = 'long'
g.counts = 0
g.loss_s = 6000
g.gaokai = True
## 开盘前运行函数
def before_market_open(context):
g.IM_current_month = get_future_contracts('IM')[0]
# 获取下月沪深300指数期货合约
g.IM_next_month = get_future_contracts('IM')[1]
g.counts = 0
current_time2 = context.current_dt
# 获取当月合约交割日期
end_data = get_CCFX_end_date(g.IM_current_month)
#如果当日是交割日,并且没有平仓,那么先平仓,后开次月仓
if context.current_dt.date() == end_data:
g.IM_current_month = g.IM_next_month
df2 = get_price(g.IM_current_month,count=241,end_date=current_time2, frequency=g.unit, fields=['close','high','low','open'], skip_paused=False, fq='pre')
#df2.close.values[-1]
g.highest_high = 0
log.info('最高级价格:')
log.info(g.highest_high)
## 开盘时运行函数
def market_open(context):
#当前运行时间
current_time = context.current_dt
IM_current_month = g.IM_current_month
#下月合约
IM_next_month = g.IM_next_month
#log.info(IM_current_month)
# 分析- 沪深300指数
reference = g.reference
if '0930' < current_time.strftime("%H%M") < '1454':
#datas = get_bars(g.reference, count=120, unit='1m', fields=['close', 'high', 'low'], include_now=False, df=True)
df = get_price(g.IM_current_month,count=241,end_date=current_time, frequency=g.unit, fields=['close','high','low','open'], skip_paused=False, fq='pre')
close = df.close.values
high = df.high.values
low = df.low.values
open = df.open.values
ma45 = MA(close,45)
ema9 = EMA(close,9)
ema21 = EMA(close,21)
sma5 = SMA(close,5)
sma20 = SMA(close,20)
#rsi1 = RSI(close,6)
rsi1 = talib.RSI(close, 7) # 计算RSI指标,周期为10
MTR = MAX(MAX((high-low),ABS(REF(close,1)-high)),ABS(REF(close,1)-low))
ATR14 = MA(MTR,14)
ATR10 = MA(MTR,10)
# ATR14 = talib.ATR(high, low, close, timeperiod=14)
# ATR10 = talib.ATR(high, low, close, timeperiod=10)
# RSV = (close-LLV(low,9))/(HHV(high,9)-LLV(low,9))*100;
# kdj_k,kdl_d,kdj_j = KDJ(close, high, low, N=9,M1=3,M2=3)
# dif,dea,macd = MACD(close, 12,26,9)
log.info('目前价格:'+str(close[-1]))
current_price = close[-1]
# log.info("k线")
# log.info(open[-1], high[-1], low[-1], close[-1])
if np.isnan(rsi1[-1]): # 处理NaN值
rsi1[-1] = 50 # 横盘时设为中性值
log.info("rsi是空")
if g.counts<=5 and g.flag and rsi1[-1]>65 and ATR14[-1] > ATR10[-1]:
orders = order(IM_current_month, 1, side=g.long_short)
g.counts += 1
g.flag = False
g.highest_high = close[-1] # 开仓时初始化最高点为当前价格
log.info('买入价格:'+str(close[-1]))
#g.stop_loss_price = close[-1] - 2 * ATR14[-1] # 2倍ATR作为止损幅度
if not g.flag:
if current_price > g.highest_high:
g.highest_high = close[-1]
#计算回落
drop_ratio = (g.highest_high - current_price )/ g.highest_high
# 判断是否达到止损条件
#if drop_ratio >= 0.004:
if rsi1[-1]<25 and (ATR14[-1] >3 and ATR10[-1]>3):
#if rsi1[-1]>65:
log.info(ATR14[-1],ATR10[-1])
# 卖平
orders = order_target(IM_current_month, 0, side=g.long_short)
log.info('最高级价格:'+str(g.highest_high))
log.info('卖出价格:'+str(close[-1]))
log.info(current_price)
g.flag = True
if current_time.strftime("%H%M") == '1454' and g.counts == 0 and g.flag:
current_data = get_current_data()
high_limit = current_data[IM_current_month].high_limit
last_price = current_data[IM_current_month].last_price
low_limit = current_data[IM_current_month].low_limit
if last_price != high_limit and last_price != low_limit:
orders = order(IM_current_month, 1, side=g.long_short)
# results = interface(current_time,IM_current_month,g.name,"开多",orders.price,g.strategy_id)
# results_print(results)
g.flag = False
print('今日开仓次数不足1需下单')
if current_time.strftime("%H%M") >= '1455':
if not g.flag:
current_data = get_current_data()
high_limit = current_data[IM_current_month].high_limit
last_price = current_data[IM_current_month].last_price
low_limit = current_data[IM_current_month].low_limit
if last_price != high_limit and last_price != low_limit:
orders = order_target(IM_current_month, 0, side=g.long_short)
g.flag = True
log.info("===1455日内平仓===")
########################## 获取期货合约信息,请保留 #################################
# 获取金融期货合约到期日
def get_CCFX_end_date(future_code):
# 获取金融期货合约到期日
return get_security_info(future_code).end_date这是我的交易代码在这上面优化