Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
close a position with a defined amount of money

Hello,

I'm new in Quantopian. Before I do a little code in another platform, the problem in there was it was not based as a portfolio like quantopian.
My question is regarding to this fact. Because the strategy will buy and sell different tickets at the same day probably, I want to have a fixed amount of stop loss and take profit. For example if the position in the ticker "XXXX" is winning more than $200 or losing more than $200 then close "this" position only.

This is the code but it doesn't work. It doesn't give any errors, is just not closing the positions. The trades are open in another part of the code, and are schedule for one time a day, in market open. I use the handle_data method because it supposed to work every minute, and I need this to work this way to check when to close positions.

def handle_data(context,data):

    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))  

Thank you!