Multiple strategy buy signals with opened position

Bridge001

New member
Will someone PLEASE tell me how to make a strategy stop generating additional buy signals if there is an alrady an open position? The additional buy signals are valid but I don't want my strategy to create another signal until the existing position is closed out. (The position that the strategy opened). I have tried many different pieces of code but nothing is working.
 
Solution
mod note: script revised 5/8/23

USER=22581]@Bridge001[/USER]
Sorry for the delay, had to get home from work.
Old:
hRtXLGP.png


New:
J2ccjkd.png


Also, fixed your addorder entry and exits to open of bar after signal (Realistic entry/exit point).
Pretty nice indicator, back tested at $10,000.00 over 10 days w/80 trades on AAPL 10 min bar.
I suggest adding time restrictions to close out at EOD.

Ruby:
input fixedSharesRange = 1000;
input timeFilterHour = 645;
input minPctDifferenceChoice = {default "0.0005", "0.005", "0.05"};
input currentRangeChoice = {default "3", "6", "8"};
input lookbackPeriodChoice = {default "3", "6", "8"};
input lowChoice = {default "Low", "Body Low"};
input maxSpreadChoice = {default...

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

@Bridge001
You have to carry your buy signal forward and reference it to determine whether or not to generate another.
Post what you have. Will be happy to help.
Thank you so much!
I made the script. It came from my personal computer.
Below is my code as is. I will try updating it as you have suggested


Code:
input fixedSharesRange = 1000;
input timeFilterHour = 645;
input minPctDifferenceChoice = {default "0.0005", "0.005", "0.05"};
input currentRangeChoice = {default "3", "6", "8"};
input lookbackPeriodChoice = {default "3", "6", "8"};
input lowChoice = {default "Low", "Body Low"};
input maxSpreadChoice = {default "0.03", "0.05", "0.07", "0.10", "0.20", "0.50"};


def stockPrice = close;
def averageType = AverageType.WILDERS;
def allowMultiplePositions = no;
def openQuantity = GetQuantity();
def hasOpenPosition = openQuantity > 0;
def minavgvolume = 5000;
def minPctDifference;
def currentRange;
def maxSpread;
def lookbackPeriod;

def Active = SecondsFromTime(0645) >=0 and SecondsTillTime(1600) > 0;

switch (minPctDifferenceChoice) {
case "0.0005":
    minPctDifference = 0.0005;
case "0.005":
    minPctDifference = 0.005;
case "0.05":
    minPctDifference = 0.05;
}

switch (currentRangeChoice) {
case "3":
    currentRange = Average(high - low, 3);
case "6":
    currentRange = Average(high - low, 6);
case "8":
    currentRange = Average(high - low, 8);
}

switch (maxSpreadChoice) {
case "0.03":
    maxSpread = 0.03;
case "0.05":
    maxSpread = 0.05;
case "0.07":
    maxSpread = 0.07;
case "0.10":
    maxSpread = 0.10;
case "0.20":
    maxSpread = 0.20;
case "0.50":
    maxSpread = 0.50;
}

switch (lookbackPeriodChoice) {
case "3":
    lookbackPeriod = 3;
case "6":
    lookbackPeriod = 6;
case "8":
    lookbackPeriod = 8;
}

# Parameters changed less frequently
def atrPeriod = 3; # Not used
def volumeAvgPeriod = 3;

# Bid, Ask, and Spread
def bid = close(priceType = PriceType.BID);
def ask = close(priceType = PriceType.ASK);
def spread = ask - bid;
def spreadCondition = spread <= maxSpread;

# Double Bottom and Volume Check
def doubleBottom = low >= Lowest(low, lookbackPeriod) and (low - Lowest(low, lookbackPeriod)) / Lowest(low, lookbackPeriod) <= minPctDifference;
def volumeCheck = Average(volume, volumeAvgPeriod) >= minavgvolume;

# Time Filter
def timeFilter = SecondsFromTime(timeFilterHour) >= 0;

def atr = MovingAverage(AverageType.WILDERS, TrueRange(high, close, low), atrPeriod);

# Hard Stop Loss Price
def selectedLow;
switch (lowChoice) {
case "Low":
    selectedLow = low;
case "Body Low":
    selectedLow = Min(open, close);
}
def doubleBottomLow = Lowest(selectedLow, lookbackPeriod);

# Buy Signal
# Sell Signal
# Entry Price, Target Price, and Bars Since Entry
def buySignal;
def sellSignal;
def entryPrice;
def hardStopLossPrice;
def targetPrice;

if !buySignal[1] and doubleBottom and volumeCheck and timeFilter and spreadCondition and Active{
buySignal = 1;
sellSignal = 0;
entryPrice = close;
hardStopLossPrice = doubleBottomLow;
targetPrice = entryPrice + currentRange;
}
else if buySignal[1] and (low <= hardStopLossPrice[1] or high >= targetPrice[1] or !Active) {
buySignal = 0;
sellSignal = 1;
entryPrice = double.nan;
hardStopLossPrice = double.nan;
targetPrice = double.nan;
}
else {
buySignal = buySignal[1];
sellSignal = sellSignal[1];
entryPrice = entryPrice[1];
hardStopLossPrice = hardStopLossPrice[1];
targetPrice = targetPrice[1];
}

AddOrder(OrderType.BUY_TO_OPEN, buySignal, open[-1], fixedSharesRange, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_TO_CLOSE, sellSignal, open[-1], fixedSharesRange, Color.RED, Color.RED);

plot target = if targetPrice then targetPrice else Double.NaN;
target.SetDefaultColor(Color.CYAN);
target.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Plot Hard Stop Loss Price and Trailing Stop
def entryBarNumber = if (buySignal) then BarNumber() else entryBarNumber[1];

plot hardStop = if hardStopLossPrice then hardStopLossPrice else Double.NaN;
hardStop.SetDefaultColor(Color.YELLOW);
hardStop.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Buy Signal Arrow Plot
plot currentBarBuySignal = if !IsNaN(close) and buySignal and !buySignal[1] then low - 0.2 * atr else Double.NaN;
currentBarBuySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
currentBarBuySignal.AssignValueColor(Color.GREEN);
currentBarBuySignal.SetLineWeight(3);

# Buy and sell execution prices
def buyExecutionPrice = if buySignal then close else buyExecutionPrice[1];
def sellExecutionPrice = if sellSignal then close else sellExecutionPrice[1];

# Buy and sell execution prices
def buyExecPrice;
def sellExecPrice;
if (buySignal) {
    buyExecPrice = close;
} else {
    buyExecPrice = buyExecPrice[1];
}

if (sellSignal) {
    sellExecPrice = close;
} else {
    sellExecPrice = sellExecPrice[1];
}
 
Last edited by a moderator:
mod note: script revised 5/8/23

USER=22581]@Bridge001[/USER]
Sorry for the delay, had to get home from work.
Old:
hRtXLGP.png


New:
J2ccjkd.png


Also, fixed your addorder entry and exits to open of bar after signal (Realistic entry/exit point).
Pretty nice indicator, back tested at $10,000.00 over 10 days w/80 trades on AAPL 10 min bar.
I suggest adding time restrictions to close out at EOD.

Ruby:
input fixedSharesRange = 1000;
input timeFilterHour = 645;
input minPctDifferenceChoice = {default "0.0005", "0.005", "0.05"};
input currentRangeChoice = {default "3", "6", "8"};
input lookbackPeriodChoice = {default "3", "6", "8"};
input lowChoice = {default "Low", "Body Low"};
input maxSpreadChoice = {default "0.03", "0.05", "0.07", "0.10", "0.20", "0.50"};


def stockPrice = close;
def averageType = AverageType.WILDERS;
def allowMultiplePositions = no;
def openQuantity = GetQuantity();
def hasOpenPosition = openQuantity > 0;
def minavgvolume = 5000;
def minPctDifference;
def currentRange;
def maxSpread;
def lookbackPeriod;

def Active = SecondsFromTime(0645) >=0 and SecondsTillTime(1600) > 0;

switch (minPctDifferenceChoice) {
case "0.0005":
    minPctDifference = 0.0005;
case "0.005":
    minPctDifference = 0.005;
case "0.05":
    minPctDifference = 0.05;
}

switch (currentRangeChoice) {
case "3":
    currentRange = Average(high - low, 3);
case "6":
    currentRange = Average(high - low, 6);
case "8":
    currentRange = Average(high - low, 8);
}

switch (maxSpreadChoice) {
case "0.03":
    maxSpread = 0.03;
case "0.05":
    maxSpread = 0.05;
case "0.07":
    maxSpread = 0.07;
case "0.10":
    maxSpread = 0.10;
case "0.20":
    maxSpread = 0.20;
case "0.50":
    maxSpread = 0.50;
}

switch (lookbackPeriodChoice) {
case "3":
    lookbackPeriod = 3;
case "6":
    lookbackPeriod = 6;
case "8":
    lookbackPeriod = 8;
}

# Parameters changed less frequently
def atrPeriod = 3; # Not used
def volumeAvgPeriod = 3;

# Bid, Ask, and Spread
def bid = close(priceType = PriceType.BID);
def ask = close(priceType = PriceType.ASK);
def spread = ask - bid;
def spreadCondition = spread <= maxSpread;

# Double Bottom and Volume Check
def doubleBottom = low >= Lowest(low, lookbackPeriod) and (low - Lowest(low, lookbackPeriod)) / Lowest(low, lookbackPeriod) <= minPctDifference;
def volumeCheck = Average(volume, volumeAvgPeriod) >= minavgvolume;

# Time Filter
def timeFilter = SecondsFromTime(timeFilterHour) >= 0;

def atr = MovingAverage(AverageType.WILDERS, TrueRange(high, close, low), atrPeriod);

# Hard Stop Loss Price
def selectedLow;
switch (lowChoice) {
case "Low":
    selectedLow = low;
case "Body Low":
    selectedLow = Min(open, close);
}
def doubleBottomLow = Lowest(selectedLow, lookbackPeriod);

# Buy Signal
# Sell Signal
# Entry Price, Target Price, and Bars Since Entry
def buySignal;
def sellSignal;
def entryPrice;
def hardStopLossPrice;
def targetPrice;

if !buySignal[1] and doubleBottom and volumeCheck and timeFilter and spreadCondition and Active{
buySignal = 1;
sellSignal = 0;
entryPrice = close;
hardStopLossPrice = doubleBottomLow;
targetPrice = entryPrice + currentRange;
}
else if buySignal[1] and (low <= hardStopLossPrice[1] or high >= targetPrice[1] or !Active) {
buySignal = 0;
sellSignal = 1;
entryPrice = double.nan;
hardStopLossPrice = double.nan;
targetPrice = double.nan;
}
else {
buySignal = buySignal[1];
sellSignal = sellSignal[1];
entryPrice = entryPrice[1];
hardStopLossPrice = hardStopLossPrice[1];
targetPrice = targetPrice[1];
}

AddOrder(OrderType.BUY_TO_OPEN, buySignal, open[-1], fixedSharesRange, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_TO_CLOSE, sellSignal, open[-1], fixedSharesRange, Color.RED, Color.RED);

plot target = if targetPrice then targetPrice else Double.NaN;
target.SetDefaultColor(Color.CYAN);
target.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Plot Hard Stop Loss Price and Trailing Stop
def entryBarNumber = if (buySignal) then BarNumber() else entryBarNumber[1];

plot hardStop = if hardStopLossPrice then hardStopLossPrice else Double.NaN;
hardStop.SetDefaultColor(Color.YELLOW);
hardStop.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Buy Signal Arrow Plot
plot currentBarBuySignal = if !IsNaN(close) and buySignal and !buySignal[1] then low - 0.2 * atr else Double.NaN;
currentBarBuySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
currentBarBuySignal.AssignValueColor(Color.GREEN);
currentBarBuySignal.SetLineWeight(3);

# Buy and sell execution prices
def buyExecutionPrice = if buySignal then close else buyExecutionPrice[1];
def sellExecutionPrice = if sellSignal then close else sellExecutionPrice[1];

# Buy and sell execution prices
def buyExecPrice;
def sellExecPrice;
if (buySignal) {
    buyExecPrice = close;
} else {
    buyExecPrice = buyExecPrice[1];
}

if (sellSignal) {
    sellExecPrice = close;
} else {
    sellExecPrice = sellExecPrice[1];
}
 
Last edited by a moderator:
Solution
OMG! I can't tell you how much I apprecitae your help with this. I have spent MANY hours on this one issue, even taking vacation hours from work (I have a day job too). Thank you so very very much. And thank you for those other changes and improvements. If you have any other suggestions I am open to them as well. I wish there were something I could do to help you but you are way beyond my level of assistance :). Thanks again!!
 
OMG! I can't tell you how much I apprecitae your help with this. I have spent MANY hours on this one issue, even taking vacation hours from work (I have a day job too). Thank you so very very much. And thank you for those other changes and improvements. If you have any other suggestions I am open to them as well. I wish there were something I could do to help you but you are way beyond my level of assistance :). Thanks again!!
I did want to ask you one other thing. I want the strategy to execute it's buy orders on the ask and sell orders on the bid only because I can only trade premarket (for now) and this the way I have to buy and sell. What do I need to change to have the strategy mirror this? Thanks again.
 
Can I bother you with another question please. As you can see, there are a number of parameter settings to toggle thru to arrive at what performs best on the stock I am watching at the time. What would be the easiest way to work thru the different settings quickly, instead of going into edit strategies and changing the inputs one at a time? How would you set that up? I change 3 inputs most frequently and each input has 3 options so that is 27 different combinations of input settings. Any suggestions? Thanks.
 
@Bridge001
I suppose you could setup a single input with an if/then/else statement containing 27 sections for inputs 1 through 27. Then change the original inputs to def and define 1 of each possible combination in each section. Would take a while to write out but would allow you to change multiple parameters with 1 input change.
 
It's because your definition of 'double bottom' uses lowest low with a length of [-1].
You have to change your buysignal to reference 'doublebottom[1]'.
 
I notice it repaints. Any way to lower the instances of it repainting?
Its like Wack-A-Mole! I fix 4, break 1, then miss the active[-1]!

Okay, @TDTOS I am going out on a limb and saying that with @HODL-Lay-HE-hoo! assistance; this is the FINAL non-repainting version:
https://usethinkscript.com/threads/...gnals-with-opened-position.15228/#post-123959

Please note, this script is going to have downright ugly albeit more realistic p/l results now that all the repainting has been removed.
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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