Back to Community
Stops

Is there anyway to code a program that would take the other side of a trade once stops have been set-off?

1 response

Adam, here is an algorithm that trades four stocks. It initially takes a long position and then always reverses the position when a stop is hit.

Clone Algorithm
21
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
def initialize(context):

    # stocks to trade
    context.stocks = [sid(24), sid(2), sid(2673), sid(5061)] # AAPL, AA, F, MSFT
    
    # stop-loss percent
    context.stop_pct = .75
    
    # stops dictionary
    context.stop = {}

    return
 
def handle_data(context, data):

    # total capital
    total_capital = context.portfolio.starting_cash + context.portfolio.pnl

    # order size for each stock (with one portion left in cash)
    order_size = total_capital / ( len(context.stocks) + 1 )
    
    # loop over all stocks
    for stock in data.keys():

        # current position for this stock
        qty = context.portfolio.positions[stock].amount
        
        # if no existing position (only done once per stock)
        if qty == 0 or not( stock in context.stop ):

            # create a long position
            order(stock, order_size / data[stock].price - qty)

            # set trailing stop-loss
            context.stop[stock] = data[stock].price * context.stop_pct
            
        # check stop-loss for existing long position
        elif qty > 0 and stock in context.stop:
            
            # if price has dropped below stop-loss
            if data[stock].price < context.stop[stock]:
                
                # reverse position (negative amount for short minus existing position)
                order(stock, -order_size/data[stock].price - qty)
                
                # set trailing stop-loss (*above* current price for new short)
                context.stop[stock] = data[stock].price / context.stop_pct
                
            # otherwise price is still above stop-loss
            else:
                # update trailing stop-loss (*below* current price for existing long)
                context.stop[stock] = max(data[stock].price * context.stop_pct, context.stop[stock])
                
        # check stop-loss for existing short position
        elif qty < 0 and stock in context.stop:
            
            # if price has risen above stop-loss
            if data[stock].price > context.stop[stock]:
                
                # reverse position (positive amount for long minus existing position)
                order(stock, +order_size/data[stock].price - qty)
                
                # set trailing stop-loss (*below* current price for new long)
                context.stop[stock] = data[stock].price * context.stop_pct
                
            # otherwise price is still below stop-loss
            else:
                # update trailing stop-loss (*above* current price for existing short)
                context.stop[stock] = min(data[stock].price / context.stop_pct, context.stop[stock])
        
    return
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.