这是我的止盈止损函数,借你用下
```
#检查持仓盈亏,根据盈亏点数自动买入卖出 卖出每天盘前都要执行
def checkamount(context):
#获取到当前的持仓数据
oldstocklist = context.portfolio.positions
for x in oldstocklist:
closeable_amount = context.portfolio.positions[x].closeable_amount#可以卖出 的仓位
if closeable_amount >0:#如果这个票可交易的是0,就不用执行后面的逻辑
cost=context.portfolio.positions[x].avg_cost#获取股票持仓成本
price=context.portfolio.positions[x].price#获取股票现价
amount=context.portfolio.positions[x].total_amount#总仓位
ret=price/cost-1#计算收益率
floatprofit = amount*(price-cost)#总的浮动盈亏
closefloatprofit = closeable_amount*(price-cost)#可交易的浮动盈亏
log.info('['+x+']成本:'+str(cost)+' 现价:'+str(price)+' 总仓位:'+str(amount) +' 可交易仓位:'+str(closeable_amount)+' 收益率:'+str(ret*100)+'%' +' 浮动盈亏:'+str(closefloatprofit))
#检查是否到达止损点
if ret< =g.maxlosst:
order(x,(-1)*closeable_amount)
log.info('['+x+']亏损已达止损点'+str(g.maxlosst*100)+'%触发止损,本次净亏损:'+str(closefloatprofit)+'元,亏损点数:'+str(ret*100)+'%')
#止盈清仓
if ret>=g.maxprofit:
order(x,(-1)*closeable_amount)
log.info('['+x+']盈利已达止止盈点'+str(g.maxprofit*100)+'%触发止赢,本次净盈利:'+str(closefloatprofit)+'元,盈利点数:'+str(ret*100)+'%')
#中期止盈
if (ret>=g.midprofit) and (ret< g.maxprofit):
if(closeable_amount/2 >= 100):
order_target(x,(-1)*closeable_amount/2)
log.info('['+x+']盈利已达中期止盈点'+str(g.midprofit*100)+'%触发中期减仓止赢,本次止盈减仓:'+str(closeable_amount/2)+'股,当前总盈利:'+ str(closefloatprofit)+'元,盈利点数:'+str(ret*100)+'%')
else:
log.info('['+x+']由于 T+1 制度当前仓位不可交易')
```
2021-07-27