| 
 等级: 免费版 
注册: 2021-7-6曾用名:  | 
 
 
 楼主|
发表于 2023-3-6 16:18
|
显示全部楼层 
| # 本Python代码主要用于策略交易 
 
 
 # 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。
 from PythonApi import *
 import numpy as np
 import talib
 import math
 
 
 #  在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。--(必须实现)
 def init(context):
 #入场周期
 context.X = 20
 #出场周期
 context.Y = 10
 #记录建仓的atr
 context.entry = 0
 #记录交易次数
 context.num = 0
 #交易标的
 context.s = context.run_info.base_book_id
 #记录上次开仓价
 context.enterprice = 0
 
 
 # 你选择的品种的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新。--(必须实现)
 def handle_bar(context):
 close = history_bars(context.s,context.X+2, '1d','close')
 high = history_bars(context.s,context.X+2, '1d','high')
 low = history_bars(context.s,context.X+2, '1d','low')
 if len(close) == context.X+2:
 #atr的计算参考这个帖子http://www.weistock.com/bbs/dispbbs.asp?boardid=10&Id=173300
 tr = talib.TRANGE(high,low,close)
 atr = talib.SMA(tr[1:],context.X)
 logger.info('波幅'+str(atr))
 unit = int((get_account(6)*0.01) / (atr[-2] * get_dynainf(context.s,209)))
 #X天的高低点(不包含当天)
 X周期高点 = high[:-1].max()
 X周期低点 = low[:-1].min()
 
 #建立头寸,根据唐奇安通道创新高入场,关键点就是利用波动atr计算仓位数量,portfolio用来进行仓位的控制
 
 portfolio=get_portfolio (context.s, 2)
 print('品种信息:'+str(portfolio)) #############################
 
 if high[-1]>=X周期高点 and portfolio.buy_quantity==0 and portfolio.sell_quantity==0:
 buy_open(context.s, "Market",0 ,unit,serial_id = 1)
 context.entry = atr[-2]
 context.num = 1
 context.enterprice = close[-1]
 if low[-1]<=X周期低点 and portfolio.sell_quantity==0 and portfolio.buy_quantity==0:
 sell_open(context.s, "Market",0 ,unit,serial_id = 2)
 context.entry = atr[-2]
 context.num = 1
 context.enterprice = close[-1]
 
 #加仓,最高价比上次开仓价多0.5个atr(盈利加仓)
 if portfolio.sell_quantity ==0 and portfolio.buy_quantity>0 and high[-1]>context.enterprice + 0.5*context.entry and context.num<4:
 buy_open(context.s, "Market",0 ,unit,serial_id = 3)
 context.num+=1
 context.enterprice = close[-1]
 if portfolio.buy_quantity==0 and portfolio.sell_quantity>0 and low[-1]<context.enterprice - 0.5*context.entry and context.num<4:
 sell_open(context.s, "Market",0 ,unit,serial_id = 4)
 context.num+=1
 context.enterprice = close[-1]
 
 #出场,跌破短周期低点平多
 Y周期高点 = high[-context.Y-1:-1].max()
 Y周期低点 = low[-context.Y-1:-1].min()
 if portfolio.buy_quantity>0 and low[-1] < Y周期低点:
 sell_close(context.s,"Market",0,portfolio.buy_quantity,serial_id = 5)
 if portfolio.sell_quantity>0 and high[-1] > Y周期高点:
 buy_close(context.s,"Market",0,portfolio.sell_quantity,serial_id = 6)
 
 #止损,亏损幅度超过开仓2个atr幅度止损
 if portfolio.buy_quantity>0 and low[-1] < context.enterprice - 2*context.entry:
 sell_close(context.s,"Market",0,portfolio.buy_quantity,serial_id = 7)
 if portfolio.sell_quantity>0 and high[-1] > context.enterprice + 2*context.entry:
 buy_close(context.s,"Market",0,portfolio.sell_quantity,serial_id = 8)
 | 
 |