Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Intraday Trades

Hi,

I am new to Quantopian and to Python as well, so I need a little help to start.
I am trying to code the following strategy but I am sure how to do it in Quantopian.

I'd like to open a position (long or short) at the opening price of the day.
Then I will place a stop (maybe a trailing stop), a take profit and in any case the trade will be closed at the end of the day.

I do not know how to start as, at minute level, Quantopian run the code for each minute, so actually I don't know how to open the trades at opening of the day.

Thanks to anyone who will give a little hint.

Davide

11 responses

Hello Davide,

To get the opening price, you have to submit an order at the very end of the prior trading day. Then, the order will be filled upon market open. If you can tolerate the order being filled a minute late, you can submit the order when the market opens, and it will be filled a minute after the market opens.

There are a few details that can lead to partial or delayed fills, but I wouldn't worry about them at this point.

Grant

Hi Grant,

many thanks. I think that I can start by placing the order at the end of day.

How can I do that?

Thanks
Davide

Hi Davide,

You can use a simple check to see if it's currently at the end of day (e.g. 3:59 PM)

The following will show you how to do that

Feel free to ask any questions about the algorithm

Disclaimer

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.

Hi Seong,

sorry but I need to ask something. Sorry but I have only some experience with macro for excel and I am struggling with python. I am studying on codecademy as well but it is not easy for me.

I need to close all the open positions at the end of day (or at a fixed time) AND then to place the orders at the very last minute of the day, so the system will execute the orders at the opening of the following day.

In the code you provided I can see only one time. Is that right?

I think I can use 2 "def endofday_check(context, minutes_early)" setting 2 different "context.minutes_early = 5".
However I am not sure how to place the order at the very end of the day. Not sure if I have to send order at 15.59 or at 16.00.

Thanks very much for help.
Davide

Davide, you definitely could do two different functions. It would be slightly more elegant to use one function with two arguments, but I'm not one to be picky about code elegance.

The backtester takes orders in one call to handle_data(), and fills them in the next call to handle_data() (longer explanation in the FAQ). So if you send in an order at the dot of close, it gets filled the next day.

It's worth pointing out that while that will work in the backtester, it actually won't work in real money, as we've implemented it today. Right now all orders are cancelled overnight. It's something we need to enable for the future, but today it won't work with real money.

Disclaimer

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.

Hi Dan,

I tried to code it with a random strategy. But I get this error:
TypeError: 'int' object is not callable
USER ALGORITHM:59, in handle_data
order(context.aapl,-quantity)

Can you please help me?
Thanks
Davide

from pytz import timezone
from datetime import datetime, timedelta
from zipline.utils.tradingcalendar import get_early_closes
from random import randint

def initialize(context):
context.aapl = sid(24)

# Initializing your start and end dates to check for early closes  
start_date = context.aapl.security_start_date  
end_date = context.aapl.security_end_date  
context.early_closes = get_early_closes(start_date,end_date).date  
# Minutes before close that you want to execute your order, so this will execute at 3:55 PM only  
context.minutes_closeposition = 30  
context.minutes_openposition = 0

def handle_data(context, data):

loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
date = get_datetime().date()  

# Checks for an early close on special dates such as holidays and the day after thanksgiving  
# The market closes at 1:00PM EST on those days  
if date in context.early_closes:  
    # Returns true if it's 1:00PM - minutes so in this case 12:54PM  
    if loc_dt.hour == 12 and loc_dt.minute == (59-context.minutes_closeposition):  
        log.debug(get_datetime())  
        order = 1  
    elif loc_dt.hour == 12 and loc_dt.minute == (59-context.minutes_openposition):  
        log.debug(get_datetime())  
        order = 2  
    else:  
        order = 0  

# Returns true if it's 4:00PM EST - minutes so in this case at 3:54PM  
# Daylight savings time are accounted for, so it will automatically adjust to DST  
elif loc_dt.hour == 15 and loc_dt.minute == (59-context.minutes_closeposition):  
        log.debug(get_datetime())  
        order = 1  
elif loc_dt.hour == 15 and loc_dt.minute == (59-context.minutes_openposition):  
        log.debug(get_datetime())  
        order = 2  
else:  
    order = 0  

side = randint(0,1)  
price = data[context.aapl].price  
position = context.portfolio.positions[context.aapl].amount  
cost = context.portfolio.positions[context.aapl].cost_basis  
quantity = int(100000/price)  

if side == 0 and position == 0 and order == 2:  
  order(context.aapl,-quantity)  
elif side == 1 and position == 0 and order == 2:  
  order(context.aapl,quantity)    

# Take profits  

profit = 0.015  
if position  0 and price > cost * (1+profit):  
  order(context.aapl,-position)

# Stop loss

stop = 0.005  
if position  cost * (1+stop):  
  order(context.aapl,-position)  
elif position > 0 and price  0 and order == 1:  
  order(context.aapl,-quantity)  
elif position  

Eddie helped me figure this one out! By using a variable called "order" you were shooting yourself in the foot. I changed it to order2 and it runs now.

That's right. I see the problem.
Now it is working but, I don't why it is sending orders at 15.31 and not at the opening of next day.

Thanks for any feedback on this.

Davide

Hello Davide,

Is your location GMT+1? I'm in the UK and the trades are made at 14:31 which is the end of the first minute of the trading day.

(I think you're in Switzerland....)

P.

Hi Peter,

you are right, but I thought that the algos were running in US time...

Hello Davide,

I don't understand Python timezones, I'm afraid, but somehow EST is converted to GMT and GMT+1 in our respective cases.

P.