Close position based on Stop Loss and Elapsed Time (or number of candles)

TMB70

New member
Hello,
I am trying to set up an order to close based on the EntryPrice, a stop loss value, and the amount of time that has passed since entering the position.

For example, suppose I added an order based on the following...


#### OPEN POSITION

#### LONG Bull
AddOrder(OrderType.BUY_TO_OPEN, Bull1 and Bull2 and Bull3, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long_Bull_Open");

#### SHORT Bear
AddOrder(OrderType.SELL_TO_OPEN, Bear1 and Bear2 and Bear3, tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "Short_Bear_Open");

The following works for using a Stop Loss Order, but doesn't include the criteria for the amount of time that has passed.

#### CLOSE POSITION DUE TO STOPLOSS

#### LONG CLOSE
input stoplossLONG = 1.50;
def stopLONG = EntryPrice() - stoplossLONG;
AddOrder(OrderType.SELL_TO_CLOSE, close < stopLONG, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Long_Close_Stop");

#### SHORT CLOSE
input stoplossSHORT = 1.50;
def stopSHORT = EntryPrice() + stoplossSHORT;
AddOrder(OrderType.BUY_TO_CLOSE, close > stopSHORT , tickcolor = Color.RED, arrowcolor = Color.RED, name = "Short_Close_Stop");

I am not sure how to count minutes or candlesticks after opening the position and add it to the code above. If I am using a "1 minute" chart and see that my stop loss has been exceeded AND ten minutes have passed, I would then exit the trade. Here is a hypothetical code below.

#### CLOSE POSITION DUE TO STOPLOSS AND TIME CONDITION IS MET

#### LONG CLOSE AFTER TBD MINUTES
input stoplossLONG = 1.00;
def stopLONG = EntryPrice() - stoplossLONG;
AddOrder(OrderType.SELL_TO_CLOSE, close < stoplong and TIME_CONDITION_MET, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Long_Close_Stop");

#### SHORT CLOSE AFTER TBD MINUTES
input stoplossSHORT = 1.00;
def stopSHORT = EntryPrice() + stoplossSHORT;
AddOrder(OrderType.BUY_TO_CLOSE, close > stopSHORT and TIME_CONDITION_MET, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Short_Close_Stop");

Any help on how to count the elapsed time (or the number of candles) after entering a position would be greatly appreciated. Also, the counter will need to be reset after exiting the trade.

I am thinking there may be some clues in this thread, but am not sure how to pick the starting candle when the position is opened in the strategy.
https://usethinkscript.com/threads/consecutive-bar-count-indicator-for-thinkorswim.324/

Thanks,
TMB_70

Pretty please? Thank you.
 
Last edited:
Solution
Hello,
I am trying to set up an order to close based on the EntryPrice, a stop loss value, and the amount of time that has passed since entering the position.

For example, suppose I added an order based on the following...


#### OPEN POSITION

#### LONG Bull
AddOrder(OrderType.BUY_TO_OPEN, Bull1 and Bull2 and Bull3, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long_Bull_Open");

#### SHORT Bear
AddOrder(OrderType.SELL_TO_OPEN, Bear1 and Bear2 and Bear3, tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "Short_Bear_Open");

The following works for using a Stop Loss Order, but doesn't include the criteria for the amount of time that has passed.

#### CLOSE POSITION DUE TO STOPLOSS

#### LONG CLOSE...
Hello,
I am trying to set up an order to close based on the EntryPrice, a stop loss value, and the amount of time that has passed since entering the position.

For example, suppose I added an order based on the following...


#### OPEN POSITION

#### LONG Bull
AddOrder(OrderType.BUY_TO_OPEN, Bull1 and Bull2 and Bull3, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "Long_Bull_Open");

#### SHORT Bear
AddOrder(OrderType.SELL_TO_OPEN, Bear1 and Bear2 and Bear3, tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "Short_Bear_Open");

The following works for using a Stop Loss Order, but doesn't include the criteria for the amount of time that has passed.

#### CLOSE POSITION DUE TO STOPLOSS

#### LONG CLOSE
input stoplossLONG = 1.50;
def stopLONG = EntryPrice() - stoplossLONG;
AddOrder(OrderType.SELL_TO_CLOSE, close < stopLONG, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Long_Close_Stop");

#### SHORT CLOSE
input stoplossSHORT = 1.50;
def stopSHORT = EntryPrice() + stoplossSHORT;
AddOrder(OrderType.BUY_TO_CLOSE, close > stopSHORT , tickcolor = Color.RED, arrowcolor = Color.RED, name = "Short_Close_Stop");

I am not sure how to count minutes or candlesticks after opening the position and add it to the code above. If I am using a "1 minute" chart and see that my stop loss has been exceeded AND ten minutes have passed, I would then exit the trade. Here is a hypothetical code below.

#### CLOSE POSITION DUE TO STOPLOSS AND TIME CONDITION IS MET

#### LONG CLOSE AFTER TBD MINUTES
input stoplossLONG = 1.00;
def stopLONG = EntryPrice() - stoplossLONG;
AddOrder(OrderType.SELL_TO_CLOSE, close < stoplong and TIME_CONDITION_MET, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Long_Close_Stop");

#### SHORT CLOSE AFTER TBD MINUTES
input stoplossSHORT = 1.00;
def stopSHORT = EntryPrice() + stoplossSHORT;
AddOrder(OrderType.BUY_TO_CLOSE, close > stopSHORT and TIME_CONDITION_MET, tickcolor = Color.RED, arrowcolor = Color.RED, name = "Short_Close_Stop");

Any help on how to count the elapsed time (or the number of candles) after entering a position would be greatly appreciated. Also, the counter will need to be reset after exiting the trade.

I am thinking there may be some clues in this thread, but am not sure how to pick the starting candle when the position is opened in the strategy.
https://usethinkscript.com/threads/consecutive-bar-count-indicator-for-thinkorswim.324/

Thanks,
TMB_70

Pretty please? Thank you.

here is a study to experiment with


Ruby:
# sell_xbars_afterbuy_00
#-------------------------------------
def bn = barnumber();
def na = double.nan;

input trade_max_duration_bars = 12;

#-------------------------------------
# test trigger , short avg crossing above long avg
input avg1_len = 10;
input avg1_type =  AverageType.simple;
def ma1 = MovingAverage(avg1_type, close, avg1_len);

input avg2_len = 80;
input avg2_type =  AverageType.simple;
def ma2 = MovingAverage(avg2_type, close, avg2_len);

def buy1 = if ma1 crosses above ma2 then 1 else 0;

plot buy1z = if buy1 then low else na;
buy1z.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
# x.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
buy1z.SetDefaultColor(Color.green);
buy1z.setlineweight(3);
buy1z.hidebubble();

def buy2 = 1;

#-------------------------------------
input show_lines = no;
plot z1 = if show_lines then ma1 else na;
z1.setdefaultcolor(color.cyan);
plot z2 = if show_lines then ma2 else na;
z2.setdefaultcolor(color.yellow);

#-------------------------------------
def buy = buy1 and buy2;
def buybn = if bn ==1 then na else if buy then bn else buybn[1];
def barsafterbuy = if isnan(buybn) then 0 else bn - buybn;
def sell_xbars_after_buy = if isnan(buybn) then 0 else if barsafterbuy == trade_max_duration_bars then 1 else 0;

#-------------------------------------
addchartbubble(1, ma2*0.998,
buy + " buy\n" +
barsafterbuy + " bars\n" +
trade_max_duration_bars + " max\n" +
sell_xbars_after_buy + " sell\n"
, ( if buy then color.green else if sell_xbars_after_buy then color.red else color.gray), no);

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

when buy is true, it draws a green arrow and a green bubble
max bars after a buy is set to 12. after 12 bars , a red bubble is drawn.
WQ0j6ef.jpg
 
Solution
here is a study to experiment with


Ruby:
# sell_xbars_afterbuy_00
#-------------------------------------
def bn = barnumber();
def na = double.nan;

input trade_max_duration_bars = 12;

#-------------------------------------
# test trigger , short avg crossing above long avg
input avg1_len = 10;
input avg1_type =  AverageType.simple;
def ma1 = MovingAverage(avg1_type, close, avg1_len);

input avg2_len = 80;
input avg2_type =  AverageType.simple;
def ma2 = MovingAverage(avg2_type, close, avg2_len);

def buy1 = if ma1 crosses above ma2 then 1 else 0;

plot buy1z = if buy1 then low else na;
buy1z.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
# x.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
buy1z.SetDefaultColor(Color.green);
buy1z.setlineweight(3);
buy1z.hidebubble();

def buy2 = 1;

#-------------------------------------
input show_lines = no;
plot z1 = if show_lines then ma1 else na;
z1.setdefaultcolor(color.cyan);
plot z2 = if show_lines then ma2 else na;
z2.setdefaultcolor(color.yellow);

#-------------------------------------
def buy = buy1 and buy2;
def buybn = if bn ==1 then na else if buy then bn else buybn[1];
def barsafterbuy = if isnan(buybn) then 0 else bn - buybn;
def sell_xbars_after_buy = if isnan(buybn) then 0 else if barsafterbuy == trade_max_duration_bars then 1 else 0;

#-------------------------------------
addchartbubble(1, ma2*0.998,
buy + " buy\n" +
barsafterbuy + " bars\n" +
trade_max_duration_bars + " max\n" +
sell_xbars_after_buy + " sell\n"
, ( if buy then color.green else if sell_xbars_after_buy then color.red else color.gray), no);

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

when buy is true, it draws a green arrow and a green bubble
max bars after a buy is set to 12. after 12 bars , a red bubble is drawn.
WQ0j6ef.jpg

Thank you! I will have a look and see it helps with my strategy.
 

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