Стоп лосс и тейк профит в Quantopian - PullRequest
1 голос
/ 21 марта 2019

Мне нужно установить стоп-лосс и зафиксировать прибыль для каждой сделки, которую я совершаю в 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))
...