AddOrder based upon a previous AddOrder

Sergio123

New member
VIP
I would like to know if I can use If....Then..Else... setting up the condition argument of an AddOrder
OrderType.SELL_AUTO based upon a previous OrderType.BUY_AUTO in a strategy script.

For example - for a Bollinger Band Strategy if the previous OrderType.BUY_AUTO was placed based upon a crossing of price above the lower band then I would like to place OrderType.SELL_AUTO on the crossing ABOVE the upper band. However if the OrderType.BUY_AUTO was placed based upon a crossing of price ABOVE the middle line, then I would like to place the OrderType.SELL_AUTO on the price crossing BELOW the upper band.

Can someone point me to an example of a script that uses conditional orders based upon the previous order?
 

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

Yes.

It doesn't matter what order type is, it's the same problem of knowing which event triggered the previous order. I am exploring doing it through recursion.
 
Yes.

It doesn't matter what order type is, it's the same problem of knowing which event triggered the previous order. I am exploring doing it through recursion.
The event is the condition for the order which you can append text to as comment and displays with the entry.
If you need to know the whether the is an active open order check entrprice()
Also you can always issue a close order regardless if any already
open.
the auto will issue a close all open orders and issue a reopen in the other direction.
you can see records of that in the strategy report.
 
Yes. I have it setup without using multiple entries:

globalstrategysettings.PNG


My conditional AddOrder setups are as follows:

def buycondition1= (close crosses above lowerBand)
def buycondition2= (close crosses above average)
def sellcondion1= (close crosses above UpperBand);
def sellcondition2= (close crosses below UpperBand);

I would only want sellcondition1 to trigger if buycondition1 triggered the very last order and sellcondition2 to trigger if buycondition2 triggered the very last order.
 
You can also use this code twice for each condition module...
So duplicate the code per condition set and check the
For the position status that is long and only close when its true.


input useStops = yes;

def BuySignal = rs_buy; # insert condition to create long position
def SellSignal = rs_sell; # insert condition to create short position
def BuyStop = 1 ; # insert condition to stop in place of the 0 after else
def SellStop = 1 ; # insert condition to stop in place of the 0 after else



#######################################
## Maintain the position of trades
#######################################

def CurrentPosition; # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
CurrentPosition = 0;
} else {
if CurrentPosition[1] == 0 { # FLAT
if (BuySignal) {
CurrentPosition = 1;
} else if (SellSignal) {
CurrentPosition = -1;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == 1 { # LONG
if (SellSignal) {
CurrentPosition = -1;
} else if (BuyStop) {
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else if CurrentPosition[1] == -1 { # SHORT
if (BuySignal) {
CurrentPosition = 1;
} else if (SellStop) {
CurrentPosition = 0;
} else {
CurrentPosition = CurrentPosition[1];
}
} else {
CurrentPosition = CurrentPosition[1];
}
}

def isLong = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat = if CurrentPosition == 0 then 1 else 0;
 
This may help you:

# wipCounterScriptlet_JQ
# Based on:
# Condition Counter
# Nube 9.25.18



# Internal Script Reference - Scriptlet
script Count {
input condition = 0;
def counter = if barnumber()<= 1
then 0
else CompoundValue(
"length" = 1,
"Visible Data" = if condition
then counter[1] + 1
else counter[1],
"historical data" = 0);
plot
count = counter;
}
# End Scriptlet

# Average Definitions
plot shortAverage = MovingAverage(data = close, length = 5, averageType = AverageType.EXPONENTIAL);
shortAverage. setdefaultColor(Color.magenta);

plot longAverage = MovingAverage(data = close, length = 10);
LongAverage. setdefaultColor(Color.blue);


# crossAbove
def crossabove = shortAverage crosses above longAverage;
plot crossAboveArrow = if shortAverage crosses above longAverage then shortaverage else double.nan;
crossAboveArrow.setPaintingStrategy(PaintingStrategy.ARROW_UP);
crossAboveArrow.assignValueColor(shortAverage.takevaluecolor());
crossAboveArrow.setLineWeight(3);


# crossBelow
def crossbelow = shortAverage crosses below longAverage;
plot crossBelowArrow = if shortAverage crosses below longAverage then longaverage else double.nan;
crossbelowArrow.setPaintingStrategy(PaintingStrategy.ARROW_UP);
crossbelowArrow.assignValueColor(longAverage.takevaluecolor());
crossbelowArrow.setLineWeight(3);

# counts
def count1 = Count(condition = crossabove);
addchartbubble(1, lowestall(low), "C1\n" + count1, color.white,no);
def count2 = Count(condition = crossBelow);
addchartbubble(1, lowestall(low), "C2\n" + count2, color.white,no);

# Labels
AddLabel(1," CrossAbove: "+count1+" | CrossBelow: "+count2+" ", Color.Gray);
 
Have you implemented a stop loss strategy in which you ONLY want the stop loss to trigger > X number of bars after the buy order triggered.

For example if I have:

BuyCondtion1: = close crosses above lowerband; # Buy Long
StopLossCondtion1: = close crosses below lowerband; # Stop Loss Sell Close Long


In the pic below. I don't want it to immediately stop loss out when it crosses below the lower band at 200.3, but rather I would like to put more bars in between the buy order give it more chance to move up.

Stop Loss delay.PNG
 
I would like to know if I can use If....Then..Else... setting up the condition argument of an AddOrder
OrderType.SELL_AUTO based upon a previous OrderType.BUY_AUTO in a strategy script.

For example - for a Bollinger Band Strategy if the previous OrderType.BUY_AUTO was placed based upon a crossing of price above the lower band then I would like to place OrderType.SELL_AUTO on the crossing ABOVE the upper band. However if the OrderType.BUY_AUTO was placed based upon a crossing of price ABOVE the middle line, then I would like to place the OrderType.SELL_AUTO on the price crossing BELOW the upper band.

Can someone point me to an example of a script that uses conditional orders based upon the previous order?


this is a strategy

this will execute the appropriate buy/sell order set,
based on which buy condition occurs.

trades and vertical line colors

trade1
1 BUY , price crosses ABOVE the lower b band - GREEN
2 SELL , price crosses ABOVE the upper band - RED

trade2
3 BUY , price crosses ABOVE the middle bb line - CYAN
4 SELL , price crosses BELOW the upper b band - YELLOW

if price moves the wrong way, a cancel signal will happen.

it draws a zero line, from the open of first bar on chart
from this reference line, a profit/loss cyan line is drawn. this line is updated on each sell signal

from the zero line, are lines that indicate which condition is happening, 1 and 2, or 3 and 4.
the numbers listed above in trade conditions.

these extra lines can be turned off.


Code:
#order_2bb_rules_

#https://usethinkscript.com/threads/addorder-based-upon-a-previous-addorder.17600/
#AddOrder based upon a previous AddOrder
#Sergio123  1/1

#I would like to know if I can use If....Then..Else... setting up the condition argument of an AddOrder
#OrderType.SELL_AUTO based upon a previous OrderType.BUY_AUTO in a strategy script.

#For example - for a Bollinger Band Strategy if the previous OrderType.BUY_AUTO was placed based upon a crossing of price above the lower band then I would like to place OrderType.SELL_AUTO on the crossing ABOVE the upper band. However if the OrderType.BUY_AUTO was placed based upon a crossing of price ABOVE the middle line, then I would like to place the OrderType.SELL_AUTO on the price crossing BELOW the upper band.

#Can someone point me to an example of a script that uses conditional orders based upon the previous order?


#rewrite the rules

# trade1
#  OrderType.BUY_AUTO , price crosses above the lower b band
#  OrderType.SELL_AUTO , price crosses ABOVE the upper band. 

# trade2
#  OrderType.BUY_AUTO , price crosses ABOVE the middle bb line,
#  OrderType.SELL_AUTO , price crosses BELOW the upper b band.

#addlabel(1, "-");

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

# ref line
def opn = if bn == 1 then round(open,0) else opn[1];


#-------------------------
# BollingerBands
# TD Ameritrade IP Company, Inc. (c) 2007-2023

input price = close;
input displace = 0;
input length = 20;
input Num_Dev_Dn = -2.0;
input Num_Dev_up = 2.0;
input averageType = AverageType.Simple;

def sDev = stdev(data = price[-displace], length = length);

plot MidLine = MovingAverage(averageType, data = price[-displace], length = length);
plot LowerBand = MidLine + num_Dev_Dn * sDev;
plot UpperBand = MidLine + num_Dev_Up * sDev;

LowerBand.SetDefaultColor(GetColor(0));
MidLine.SetDefaultColor(GetColor(1));
UpperBand.SetDefaultColor(GetColor(5));

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


# trade1
# 1  BUY , price crosses above the lower b band
# 2  SELL , price crosses ABOVE the upper band. 

# trade2
# 3  BUY , price crosses ABOVE the middle bb line,
# 4  SELL , price crosses BELOW the upper b band.


def trade = if bn == 1 then 0
 else if close crosses below lowerband then 0
 else if close crosses above LowerBand then 1
# else if trade[1] == 3 and close crosses above UpperBand then 2
 else if trade[1] == 1 and close crosses above UpperBand then 2
 else if trade[1] != 1 and close crosses above MidLine then 3
 else if trade[1] == 3 and close crosses below UpperBand then 4
 else if trade[1] == 2 or trade[1] == 4 then 0
 else trade[1];


def b1 = if bn == 1 then 0 else if trade[1] != 1 and trade[0] == 1 then 1 else 0;
def s1 = if bn == 1 then 0 else if trade[1] == 1 and trade[0] == 2 then 1 else 0;
def b2 = if bn == 1 then 0 else if trade[1] != 3 and trade[0] == 3 then 1 else 0;
def s2 = if bn == 1 then 0 else if trade[1] == 3 and trade[0] == 4 then 1 else 0;

def cancel = if bn == 1 then 0 else 
 if s1[1] or s2[1] then 0 else
 if (trade == 0 and trade[1] > 0) then 1
 else 0;


addOrder(
  type = OrderType.BUY_to_open,
  condition = b1,
  price =  open[-1],
  tradeSize = 1,
  tickColor = color.green,
  arrowColor = Color.green,
  name = "BUY"
);


addOrder(
  type = OrderType.sell_to_close,
  condition = s1,
  price =  open[-1],
  tradeSize = 1,
  tickColor = color.red,
  arrowColor = Color.red,
  name = "SELL"
);


addOrder(
  type = OrderType.BUY_to_open,
  condition = b2,
  price =  open[-1],
  tradeSize = 1,
  tickColor = color.cyan,
  arrowColor = Color.cyan,
  name = "BUY"
);

addOrder(
  type = OrderType.sell_to_close,
  condition = s2,
  price =  open[-1],
  tradeSize = 1,
  tickColor = color.yellow,
  arrowColor = Color.yellow,
  name = "SELL"
);


#addOrder(OrderType.BUY_to_open, b1);
#addOrder(OrderType.sell_to_close, s1);
#addOrder(OrderType.BUY_to_open, b2);
#addOrder(OrderType.sell_to_close, s2);

addverticalline(b1, "BUY", color.green);
addverticalline(s1, "SELL", color.red);
addverticalline(b2, "BUY", color.cyan);
addverticalline(s2, "SELL", color.yellow);

addverticalline(cancel, "     CANCEL", color.WHITE, Curve.firm);


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

input test_signal_lines = yes;
plot z0 = if test_signal_lines then opn else na;
plot z1 = if test_signal_lines then (opn + trade) else na;
z0.setdefaultcolor(color.orange);
z1.setdefaultcolor(getcolor(2));
#z1.setdefaultcolor(color.dark_red);
#z1.setlineweight(4);

# gains
def openx = if bn == 1 then 0 
 else if b1 or b2 then close
 else openx[1];

def gains = if bn == 1 then 0
 else if s1 or s2 or cancel then round(gains[1] + (close - openx),2)
 else gains[1];

input gains_line = yes;
plot zg = if gains_line then z0 + gains else na;
zg.SetDefaultColor(Color.cyan);
zg.setlineweight(3);
zg.hidebubble();

def t = 2;
def x = (!isnan(close[t]) and isnan(close[t-1]));

addchartbubble(gains_line and x, (gains[t] + opn[t]),
gains[t]
, color.yellow, no);

addchartbubble(0, opn,
gains
, color.yellow, no);
#

ABT hour
iSr4QGV.jpg
 
Thank you very much, halcyonGuy.

There are quite a number of things in this script for me to unpack. I didn't know about the barnumber() function and haven't used the vertical lines in any of my scripts before now.

But this code will help a lot in developing out this strategy.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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