Back to Community
Creating an algorithm to buy, sell-short stocks based on Interactive Broker 1- or 3-minute bars

Has any Quant member created a cloneable algorithm that executes long (or short-sell) trades based on trends inputted from 1- or (preferably) 3-minute bars?

My algorithm idea would compare two consecutive bars, one-by-one, throughout the trading day. When two consecutive bars of a selected stock were green (i.e., rising) the platform would execute a market "buy" order. When two consecutive bars were red indicating (I hope) a downward trend, the algo would execute a market short sell order.

If neither a double green or double red occurs in a single, two-bar comparison, the algo would delete the data from the first bar and input data from the next bar for comparison. And so on, all day long.

The algo would reverse the trade, (or merely sell or cover) when the opposite trend appears.

Obviously, there are a few more bells and whistles in this algorithm, but I'm a rank beginner (as you can tell) and need a bit of code just to get started.

9 responses

Hey Charles,

I went ahead and tried making a quick algo that implements your idea. Initially I tried running it on the minutely data as you suggested. Unfortunately if you are doing buy and sell orders every minute or few minutes, you tend to get killed on commissions.

With that in mind I changed it to just run daily. So every day it checks the 3 previous daily prices. Like you specified, if both day-to-day changes are positive or negative, the algorithm longs or shorts, respectively. If the two changes are in opposite directions, it holds its position.

I hope this is helpful, and if you need additional explanation for the code, please let me know.

Clone Algorithm
Total Returns
Max Drawdown
Benchmark Returns
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
import pandas as pd

def initialize(context):
    context.equities = [sid(24), sid(5061), sid(46631)]
    context.num_equities = len(context.equities)
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(hours=1))
    schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())
def before_trading_start(context, data):
    # Get prices of specified equities: the 3 last data points, 1 day apart.
    prices = data.history(context.equities, 'price', 3, '1d')
    # Construct a DataFrame containing the 2 daily changes in prices.
    deltas = pd.DataFrame({0 : prices.iloc[1] - prices.iloc[0],
                           1 : prices.iloc[2] - prices.iloc[1]})
    # Construct bool series saying whether we should long or short based on the deltas.
    should_long = (deltas[0] > 0) & (deltas[1] > 0)
    should_short = (deltas[0] < 0) & (deltas[1] < 0)
    # Construct sets of equities to trade by filtering the series based on the bools.
    context.longs = set(should_long[should_long].index)
    context.shorts = set(should_short[should_short].index)
    context.position_set = context.longs.union(context.shorts)

def rebalance(context, data):
    for equity in context.position_set:
        if data.can_trade(equity):
            if equity in context.longs:
                cancel_and_order(equity, 1. / context.num_equities)
            else: # i.e., equity is in context.shorts
                cancel_and_order(equity, -1. / context.num_equities)
def cancel_and_order(equity, percent):
    for order in get_open_orders(equity):
    order_target_percent(equity, percent)
def record_vars(context, data):
    Plot variables at the end of each day.
    shorts = longs = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount < 0:
            shorts += 1
        elif position.amount > 0:
            longs += 1
    record(leverage = context.account.leverage, short_count = shorts, long_count = longs)
There was a runtime error.

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thanks, Nathan. You're a prince for trying to help me solve this problem.
You indicated you tried running this algo with minute bars.

Question: can you use daily streaming data from 3-minute bars (even though a backtest might not be available on Quantopian for 3-minute bars). Additionally, skipping the long trades, supposing the platform merely shorted shares when two consecutive red bars appeared and covered that trade when two consecutive green bars appeared. Is that possible?If you can create that, I'd be glad to pay you for your time and creativity. (See:

As an employee of Quantopian, I can merely try to guide you through writing the algorithm yourself. A great place to start is the Getting Started Tutorial, if you haven't taken a look yet. This tutorial covers the basics of the Quantopian API. Between the tutorial and the example I provided, I hope you'll be able to write the algorithm on your own!

Sorry. I didn't know you are an employee. Have viewed the tutorials, and am trying hard to learn. But before I go chasing an impossible, can you tell me if Quantopian can handle an algorithm using 3-minute bars? Can it backtest using 3-minute bars?

Thanks for your help. I am grateful.


Currently Quantopian doesn't support directly doing 3-minute bars. As a workaround, you could just do 1-minute and, for instance, discard all but every 3rd point of pricing data.

When you get a pandas DataFrame or Series out of data.history(), you can go ahead and use .resample() to condense the data down to 3-minute bars. For example, if you have

prices = data.history([sid(24), sid(5061)], 'price', 9, '1m'),


prices.resample('3T', how='last')

to throw out all but every third one. Use how='mean' to take the mean of every three 1-minute bars, and use how='sum' to take the sum of every three bars. The documentation for .resample() is here.

Hello Nathan. How do I change the code so that the whole position for this code will be under $100,000 even though I have 1 M cash on IB. Thank you!

The order amount is controlled by the second argument of order_target_percent. For the algo I posted, if you only wanted 1/10 of your balance to be used, you would change order_target_percent(equity, percent) to order_target_percent(equity, percent / 10).

Hey all,

I was going through the forums and saw a post this post.

Im new to this so bare with me. Im looking to do something very similar, where if you have on a time frame (say daily), if you have two consecutive down bars, and the third bar is an up bar, to store the open of the up bars price for future reference?

Excited to be part of the community and learn more!