script to backtest buy today, sell tomorrow

dankercookie

New member
I've been trying to code a strategy that buys at the end of the day then sells at the open of the next day, but the script I use only wants to buy and sell the same day. any recommendations. I've tried setting some time and position parameters, but they don't seem to work. here is the code I had. Does anyone know how to do this??

def qty = GetQuantity();

# Define the input parameters
input buyTime = 1400;
input sellTime = 0930;

# Check if it is time to buy
def buyCond = GetTime() == buyTime;

# Check if it is time to sell
def sellCond =GetTime() == sellTime;

# Check if a position is open
def posnotOpen = if (qty > 1) then 1 else 0;
def posopen = if(qty <1) then 1 else 0;

input malength = 200;
def sma = simplemovingavg(length = malength);

# Check if we should buy
def buy = buyCond and posnotopen;


# Check if we should sell
def sell = sellCond and posopen;



AddOrder(OrderType.BUY_TO_OPEN, buy,close, name = "Buy", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);

AddOrder(OrderType.SELL_TO_CLOSE, sell,open, name = "Sell", tickcolor = Color.RED, arrowcolor = Color.RED);
 
Solution
I've been trying to code a strategy that buys at the end of the day then sells at the open of the next day, but the script I use only wants to buy and sell the same day. any recommendations. I've tried setting some time and position parameters, but they don't seem to work. here is the code I had. Does anyone know how to do this??

def qty = GetQuantity();

# Define the input parameters
input buyTime = 1400;
input sellTime = 0930;

# Check if it is time to buy
def buyCond = GetTime() == buyTime;

# Check if it is time to sell
def sellCond =GetTime() == sellTime;

# Check if a position is open
def posnotOpen = if (qty > 1) then 1 else 0;
def posopen = if(qty <1) then 1 else 0;

input malength = 200;
def sma = simplemovingavg(length =...
mod note for future viewers of this thread:
AddOrder() function provides backtesting data only.
It is not possible to use this script in actual live trading
 
@dankercookie
Ruby:
# Check if it is time to buy
def buyCond = SecondsTillTime(buyTime) == 0;

# Check if it is time to sell
def sellCond = SecondsTillTime(sellTime) == 0;

and you don't need the following code since your addorder lines specify TO_OPEN and TO_CLOSE, a TO_CLOSE will not plot unless a TO_OPEN is the last plot prior.
Ruby:
# Check if a position is open
def posnotOpen = if (qty > 1) then 1 else 0;
def posopen = if(qty <1) then 1 else 0;
 
Thanks! It still only seems to want to buy and sell on the same day instead of, for example, buying the close of the 15th and then selling the open of the 16th. Also, in the backtest it is actually shorting the open first for some reason instead of waiting until the end of the first day for the initial buy order. That was why I was trying to use the position quantity to keep it from selling (shorting) if there weren't any positions...but come to think of it, maybe it is looking at my actual account position size with that function so that wouldn't work anyway. Ugh!
 
I've been trying to code a strategy that buys at the end of the day then sells at the open of the next day, but the script I use only wants to buy and sell the same day. any recommendations. I've tried setting some time and position parameters, but they don't seem to work. here is the code I had. Does anyone know how to do this??

def qty = GetQuantity();

# Define the input parameters
input buyTime = 1400;
input sellTime = 0930;

# Check if it is time to buy
def buyCond = GetTime() == buyTime;

# Check if it is time to sell
def sellCond =GetTime() == sellTime;

# Check if a position is open
def posnotOpen = if (qty > 1) then 1 else 0;
def posopen = if(qty <1) then 1 else 0;

input malength = 200;
def sma = simplemovingavg(length = malength);

# Check if we should buy
def buy = buyCond and posnotopen;


# Check if we should sell
def sell = sellCond and posopen;



AddOrder(OrderType.BUY_TO_OPEN, buy,close, name = "Buy", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);

AddOrder(OrderType.SELL_TO_CLOSE, sell,open, name = "Sell", tickcolor = Color.RED, arrowcolor = Color.RED);


this is a strategy.
this will buy on the last bar of the day, on normal trading hours.
then sell on the first bar of the next day. (actually on the 2nd , see below)


the default setting of addorder is buy on open[-1], which means, to wait until the signal bar is closed, then buy on the next bar.
because of this, this code needs to shift the buy signal back 1 bar earlier.

if you try to use the default addorder to buy on the last bar of the day, it will buy on the next bar, which could be the first bar of the next day (if after hours are off). if after hours are on, then it would try to buy on the first bar in after hours.)

i added an offset,
input last_bar_offset = 1;
, so the buy signal happens on the 2nd to last bar of the day. then the addorder buy is processed on the next bar, the last bar of the day. then sell is processed on the 2nd bar of the day.




Code:
# buy_day_end_sell_am_strat_00

#https://usethinkscript.com/threads/script-that-lets-me-buy-today-sell-tomorrow.13930/
# script that lets me buy today, sell tomorrow
# trying to code a strategy that buys at the end of the day then sells at the open of the next day


def bn = barnumber();
def na = double.nan;

#------------------------------
# ref
# https://usethinkscript.com/threads/time-anchored-line-showing-for-last-5-days.13887/#post-115603
def diffday = if getday() != getday()[1] then 1 else 0;

input buy_time = 1600;
input sell_time = 0930;

def chartagg = getaggregationperiod();
def chartmin = chartagg/(1000*60);
#addlabel(yes, chartmin + " min", color.yellow);


# since default addorder() buys/sells on the bar after the signal, find the 2nd to last bar of day as the buy signal.
# then the strategy buys on next bar, the last bar of day
#   nth last bar
# 1 = last bar , 2 = 2nd to last bar , 3 = 3rd to last bar
#  (last_bar_offset * chart minutes) has to be <= 60. otherwise  buy_timeadj  formula needs to be changed
input last_bar_offset = 1;

# adjust buy time, if 4pm, to be the last bar of day
def buy_timeadj = if buy_time == 1600 then 1560 - ((last_bar_offset+1) * chartmin) else buy_time;

def sell3 = if SecondsTillTime(sell_time) == 0 and SecondsFromTime(sell_time) == 0 then 1 else 0;
def buy3 = if SecondsTillTime(buy_timeadj) == 0 and SecondsFromTime(buy_timeadj) == 0 then 1 else 0;

#------------------------------------------


# ref
# https://usethinkscript.com/threads/how-to-code-logic-to-filter-out-duplicated-signals-closing-the-current-position-and-open-the-opposite-trend-position.13832/#post-115584

def buy = buy3;
def sell = sell3;

def long;
if bn == 1 then {
long = 0;
} else if sell and long[1] then {
long = 0;
} else if buy and !long[1]  then {
long = 1;
} else {
long = long[1];
}


def long_open = !long[1] and long;
def long_close = long[1] and !long;


#---------------------------


def Size = 1;

AddOrder(OrderType.BUY_TO_OPEN, long_open, price = open[-1], tradeSize = Size, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "buy");
AddOrder(OrderType.sell_to_close, long_close, price = open[-1], tradeSize = Size, tickcolor = Color.RED, arrowcolor = Color.RED, name = "sell");

#---------------------------

input show_daystart_end_arrows = yes;
plot zbuy = if show_daystart_end_arrows and buy3 then low else na;
zbuy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
#zbuy.SetDefaultColor(Color.green);
zbuy.SetDefaultColor(Color.cyan);
zbuy.setlineweight(2);
zbuy.hidebubble();
plot zsell = if show_daystart_end_arrows and sell3 then high else na;
zsell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
#zsell.SetDefaultColor(Color.red);
zsell.SetDefaultColor(Color.cyan);
zsell.setlineweight(2);
zsell.hidebubble();


input test_long_bubbles = no;
addchartbubble(test_long_bubbles , low,
buy3 + " b3\n" +
long_open + " opn\n" +
sell3 + " s3\n" +
long_close + " cls\n" +
long + " long"
, ( if long_open then color.green
else if long_close then color.red
else if long then color.lime
else color.gray), no);
#

light blue arrows are buy and sell signals
green and red arrows are when the strategy activates
after hours turned off
eyHCpZg.jpg


after hours turned on
EG2nr2v.jpg




reference

buy sell template
https://usethinkscript.com/threads/...he-opposite-trend-position.13832/#post-115584

find last bar of day
https://usethinkscript.com/threads/time-anchored-line-showing-for-last-5-days.13887/#post-115603
 
Solution

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
367 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top