Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
My stop order is not working

My stop order doesn't work even I set it to 0.999
Is it because I have put it in the "handle_data" and it keeps changing?

STOP_LOSS = 0.999   

def handle_data(context,data):  
    MAX_LEVERAGE = calc_leverage(context.portfolio.cash)  
    context.pctx = diversify(context,data,context.security_listF,MAX_LEVERAGE)  
    if context.pctx == 0:  
        return  
    for s in context.security_listF:  
        cp = data.current(s,'price')  
        if s not in context.portfolio.positions and s not in get_open_orders():  
            #if context.portfolio.cash > 0:  
                if data.can_trade(s):  
                    order_target_percent(s,context.pctx,style=MarketOrder())  
                    context.sl[s] = cp * STOP_LOSS  
                    order_target(s,0,style=StopOrder(context.sl[s]))  
2 responses

It finally works in this way...

MAX_LEVERAGE = calc_leverage(context.portfolio.cash)  
    context.pctx = diversify(context,data,context.security_listF,MAX_LEVERAGE)  
    if context.pctx == 0:  
        return  
    for s in context.security_listF:  
        cp = data.current(s,'price')  
        if s not in context.portfolio.positions and s not in get_open_orders():  
            #if context.portfolio.cash > 0:  
                if data.can_trade(s):  
                    #shares = context.portfolio.portfolio_value * context.pctx / cp  
                    order_target_percent(s,context.pctx,style=MarketOrder())  
    for s in context.portfolio.positions:  
                    cb = context.portfolio.positions[s].cost_basis  
                    context.sl[s] = cb * STOP_LOSS  
                    order_target(s,0,style=StopOrder(context.sl[s]))  
MAX_LEVERAGE = calc_leverage(context.portfolio.cash)  
    context.pctx = diversify(context,data,context.security_listF,MAX_LEVERAGE)  
    if context.pctx == 0:  
        return  
    for s in context.security_listF:  
        cp = data.current(s,'price')  
        if s not in context.portfolio.positions and s not in get_open_orders():  
            #if context.portfolio.cash > 0:  
                if data.can_trade(s):  
                    #shares = context.portfolio.portfolio_value * context.pctx / cp  
                    order_target_percent(s,context.pctx,style=MarketOrder())  
        if s in context.portfolio.positions and s not in get_open_orders():  
                    cb = context.portfolio.positions[s].cost_basis  
                    context.sl[s] = cb * STOP_LOSS  
                    order_target(s,0,style=StopOrder(context.sl[s]))