2

我需要为我在 Quantopian 进行的每笔交易设置止损并获利。这是我目前拥有的代码,但它没有按预期工作。订单逻辑(进入空头或多头交易)每天只安排一次,而止盈或止损应每分钟检查一次。

import talib as ta  
import pandas  
risk_per_trade = 500  
factor_tp = 2  
factor_sl = 2  
Bars_count = 60

def initialize(context):  
    context.stocks = [sid(4265), sid(5061)]  
    schedule_function(orderlogic,date_rules.every_day(),   time_rules.market_open(hours=0, minutes=10))  
def orderlogic(context, data):  
    hist = data.history(context.stocks,['price','high','low','close','open'],                                 bar_count=Bars_count, frequency='1d')  
    for stock in context.stocks:  
        atr = ta.ATR(hist['high'][stock],hist['low'][stock],hist['close'][stock],timeperiod=14)  
        sma_20 = ta.SMA(hist['close'][stock], timeperiod=20)  
        stop_size = factor_sl * atr[-1]  
        amount_shares = round(risk_per_trade / stop_size)  
        open_orders = get_open_orders()  
        LongCondition = hist['price'][stock][-1] < sma_20[-1]  
        SellCondition = hist['price'][stock][-1] > sma_20[-1]  
        if LongCondition and stock not in open_orders and context.portfolio.positions[stock].amount ==0:  
            order(stock, amount_shares)  
        elif SellCondition and stock not in open_orders and context.portfolio.positions[stock].amount ==0:  
            order(stock, -1 * amount_shares)  
def handle_data(context,data):  
#    record(leverage=context.account.leverage)  
    for axion in context.stocks:  
        current_price = data.current(axion, 'price')  
        position = context.portfolio.positions[axion].amount  
        price_position = context.portfolio.positions[axion].cost_basis  
        pnl = ( current_price - price_position ) * position  
        if position > 0 and current_price > price_position:  
            if pnl >= factor_tp * risk_per_trade:  
                order_target_percent(axion, 0)  
                log.info("Buy with Take Profit hit " + str(axion.symbol))  
        if position > 0 and current_price < price_position:  
            if pnl <= -risk_per_trade:  
                order_target_percent(axion, 0)  
                log.info("Buy with Stop Loss hit " + str(axion.symbol))  
        if position < 0 and current_price < price_position:  
            if -pnl >= factor_tp * risk_per_trade:  
                order_target_percent(axion, 0)  
                log.info("Sell with Take Profit hit " + str(axion.symbol))  
        if position < 0 and current_price > price_position:  
            if pnl >= risk_per_trade:  
                order_target_percent(axion, 0)  
                log.info("Sell with Stop Loss hit " + str(axion.symbol))
4

0 回答 0