SELL_TO_CLOSE after a number of bars

krose

New member
I want to backtest a strategy that does a SELL_TO_CLOSE within a given number of bars if a target price hasn't been reached. Is there a function that tells the number of bars a trade has been opened? Or a method one can follow to keep a count that can be used in the SELL_TO_CLOSE test?

The following snippet describes what I've tried (that isn't working):

Code:
def longOpenRule = aboveBars > minLongBarsSinceMACross
  and rsiCrossBelow
  and price > trendDef;
def longTargetReached = price >= (EntryPrice() * (1 + (longExitPct  / 100)));

def barCount = if !EntryPrice() then 0 else barCount[1] + 1;

AddOrder(OrderType.BUY_TO_OPEN, longOpenRule, price, tradeSize);
AddOrder(OrderType.SELL_TO_CLOSE,longTargetReached or barCount > maxLongBars, price, tradeSize);
 
Solution
Posting back because I finally found a good way to do this simply. The days in the current position is simple if you leverage the EntryPrice() function:

Code:
def posCount = if isNaN(EntryPrice()) then 0 else posCount[1] + 1;

This value can be used to close a position after it has been open for a specified period of time. Here's a simple strategy to illustrate:

Code:
# ====================================
# MA Crosover Strategy
# ====================================

input price = open;

input fastMAbars = 3;
input slowMAbars = 20;
input maAverageType = AverageType.WILDERS;

input holdBars = 20;

# ------------------------------------
# Situation
# ------------------------------------
plot fastMA = MovingAverage(maAverageType, price...
I want to backtest a strategy that does a SELL_TO_CLOSE within a given number of bars if a target price hasn't been reached. Is there a function that tells the number of bars a trade has been opened? Or a method one can follow to keep a count that can be used in the SELL_TO_CLOSE test?

The following snippet describes what I've tried (that isn't working):

Code:
def longOpenRule = aboveBars > minLongBarsSinceMACross
  and rsiCrossBelow
  and price > trendDef;
def longTargetReached = price >= (EntryPrice() * (1 + (longExitPct  / 100)));

def barCount = if !EntryPrice() then 0 else barCount[1] + 1;

AddOrder(OrderType.BUY_TO_OPEN, longOpenRule, price, tradeSize);
AddOrder(OrderType.SELL_TO_CLOSE,longTargetReached or barCount > maxLongBars, price, tradeSize);

maybe try using the same variable as in your addorder, to drive the counter?

Code:
def barCount = if barnumber() == 1 then 0 
 else if longTargetReached then 0
 else if longOpenRule then 0
 else barCount[1] + 1;


a variation to try, reset to a negative number when trade closed, so the count will be negative.
then you can check if count > 0 to see if it is valid

Code:
# if barcount > 0 then a trade is open
def barCount = if barnumber() == 1 then 0 
 else if longTargetReached then -99999
 else if longOpenRule then 0
 else barCount[1] + 1;
 

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

Posting back because I finally found a good way to do this simply. The days in the current position is simple if you leverage the EntryPrice() function:

Code:
def posCount = if isNaN(EntryPrice()) then 0 else posCount[1] + 1;

This value can be used to close a position after it has been open for a specified period of time. Here's a simple strategy to illustrate:

Code:
# ====================================
# MA Crosover Strategy
# ====================================

input price = open;

input fastMAbars = 3;
input slowMAbars = 20;
input maAverageType = AverageType.WILDERS;

input holdBars = 20;

# ------------------------------------
# Situation
# ------------------------------------
plot fastMA = MovingAverage(maAverageType, price, fastMAbars);
plot slowMA = MovingAverage(maAverageType, price, slowMAbars);

def bullCross = fastMA > slowMA and fastMA[1] <= slowMA[1];
def bearCross = fastMA < slowMA and fastMA[1] >= slowMA[1];

# ------------------------------------
# Rules
# ------------------------------------
def posCount = if isNaN(EntryPrice()) then 0 else posCount[1] + 1;

def bullOpen  = bullCross;
def bullClose = bearCross or posCount >= holdBars;

def bearOpen  = bearCross;
def bearClose = bullCross or posCount >= holdBars;

# ------------------------------------
# Orders
# ------------------------------------
AddOrder(OrderType.BUY_TO_OPEN,   bullOpen, price, name = "BullOpen");
AddOrder(OrderType.SELL_TO_CLOSE, bullClose, price, name = "BullClose");

AddOrder(OrderType.SELL_TO_OPEN,  bearOpen, price, name = "BearOpen");
AddOrder(OrderType.BUY_TO_CLOSE,  bearClose, price, name = "BearClose");
 
Solution

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
394 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