Rob Smiths TheStrat x ORB with Targets For ThinkOrSwim

aaronjure

New member
* * UPDATED ENTRY/EXIT MARKS BASED OFF BARBAROS INPUT IN OUR DISCORD!! THANKS FOR THE HELP! --- UPDATED 3.14.22* *

Here is a price action (TheStrat) based ORB strategy with targets. It is ready to go and battle the markets.

I am always looking to improve the coding and strategy, any and all suggestions welcome.
Lots of credit to @Pelonsax for helping with coding and providing his codes to the public!

Link for importing here :

- ORBxSTRAT : http://tos.mx/j2Wpjeb

- ORBxSTRATxMA : http://tos.mx/CRxpCiA

BONUS

- STRATx9MA : http://tos.mx/OipPRLo
============================================================================================

Documentation for ORBxSTRAT trading system -

All trades are entered before 11:00am EST

FTC = Day/Hour/Thirty continuity // WFTC = Week/Day/Hour/Thirty continuity

CrossAbove = price crosses ORHigh // CrosseBelow = price crosses below ORLow

RL = 4hr reversal long // RS = 4hr reversal short
- - - > 4hr patterns must complete ( 2-1-2 // 3-2-2 // 1-2-2 // 2-2 // 3-1-2 // 1-1 OR 1 )

CL = 4hr continuation // CS = 4hr continuation
- - - > 4hr patterns must complete ( 2-2 // 1-2 // 3-2 )

RL2 = day reversal SETUP long // RS2 = day reversal SETUP short
- - - > I highlight SETUP because these patterns do not have to be complete, we are looking at the daily for the reversal setups ( 2-1 // 3-2 // 1-2 // 2 // 3-1 // 1-1 OR 3)

CL2 = day continuation SETUP long // CS2 = day continuation SETUP short
- - - > I highlight SETUP because these patterns do not have to be complete, we are looking at the daily for the reversal setups ( 2 // 1 // 3 )

LONG criteria -

Reversals Long - When there is RL2 ( 2D-1 // 2D // 3D-1 // 1-2D ) you must have one of the RL ( 2D-1-2U // 2D-2U // 3-1-2U // 1-1-2U // 1-2D-2U // 3-2U ) setups complete. This can be a gap or happen when the opening range causes the new 4hr bar to complete the Strat pattern. FTC UP must also be true to get a signal. Entry is CrossAbove.

Continuations long - To get a signal long when a stock is running you must have WFTC UP. A CL2 setup ( previous daily bar is 2U, inside, or 3U) must be present. CL ( 2U-2U // 1-2U // 3-2U // 2U // 3U ) or RL setup must also be complete. Entry is CrossAbove.

SHORT criteria -

Reversals Short - When there is RS2 ( 2U-1 // 2U // 3U-1 // 1-2U ) you must have one of the RS ( 2U-1-2D // 2U-2D // 3-1-2D // 1-1-2D // 1-2U-2D // 3-2D ) setups complete. This can be a gap or happen when the opening range causes the new 4hr bar to complete the Strat pattern. FTC DOWN must also be true to get a signal. Entry is CrossBelow.

Continuations long - To get a signal SHORT when a stock is falling you must have WFTC DOWN. A CS2 setup ( previous daily bar is 2D, inside, or 3D) must be present. CS ( 2D-2D // 1-2D // 3-2D // 2D // 3D ) or CS setup must also be complete. Entry is CrossBelow.

EXITS -

Targets are retracements of the range of the opening range. For example….if the OR range is 10 and the high is 100 and low is 90, then targets long are 110 then 120 and short are 80 then 70. This creates an easy 1:1 and 1:2 risk/reward profile using the opposite end of the opening range as your stop.

If you see a better way to stop out please share, I have found it too costly to use the midway point of the opening range when trading options.

I choose to exit at target 1 long and short, this is the exit with greatest probability but am working on a selling partial at target 1, move stop to break even, and hold for target 2 with remaining.
 
Last edited by a moderator:
This looks like an awesome strategy. Thanks for building it. I like that you also put the stop loss price in the text of the order.

I'm thinking that the price for the BUY_TO_OPEN and SELL_TO_OPEN orders should be specified as the crossover price. It looks like the price would be the open price, but we wouldn't know that we're buying in until after the price crosses over a hurdle.

line 330: AddOrder(OrderType.BUY_TO_OPEN, buy[-1], tickcolor = Color.LIME, arrowcolor = Color.LIME, name = "LONG : " + ORLow);

Maybe change line 330 to specify a price and similar for sell to open:
AddOrder(OrderType.BUY_TO_OPEN, buy[-1], price=?????[-1] , tickcolor = Color.LIME, arrowcolor = Color.LIME, name = "LONG : " + ORLow);

###########
lines 28-29:
def ORHigh = if FirstMinute then high else if OpenRangeTime and high > ORHigh[1] then high else ORHigh[1];
def ORLow = if FirstMinute then low else if OpenRangeTime and low < ORLow[1] then low else ORLow[1];

lines 318-319:
def crossAbove = high crosses above ORHigh;
def crossBelow = low crosses below ORLow;

lines 325-326:
def buy = if (FTCUP and Active and crossAbove and RL and RL2) then 1 else if (WFTCUP and Active and crossAbove and CL and CL2) then 1 else 0;
def sell = if (FTCDN and Active and crossBelow and RS and RS2) then 1 else if (WFTCDN and Active and crossBelow and CS and CS2) then 1 else 0;

Thanks again for building this. I think it's awesome.
 
This looks like an awesome strategy. Thanks for building it. I like that you also put the stop loss price in the text of the order.

I'm thinking that the price for the BUY_TO_OPEN and SELL_TO_OPEN orders should be specified as the crossover price. It looks like the price would be the open price, but we wouldn't know that we're buying in until after the price crosses over a hurdle.

line 330: AddOrder(OrderType.BUY_TO_OPEN, buy[-1], tickcolor = Color.LIME, arrowcolor = Color.LIME, name = "LONG : " + ORLow);

Maybe change line 330 to specify a price and similar for sell to open:
AddOrder(OrderType.BUY_TO_OPEN, buy[-1], price=?????[-1] , tickcolor = Color.LIME, arrowcolor = Color.LIME, name = "LONG : " + ORLow);

###########
lines 28-29:
def ORHigh = if FirstMinute then high else if OpenRangeTime and high > ORHigh[1] then high else ORHigh[1];
def ORLow = if FirstMinute then low else if OpenRangeTime and low < ORLow[1] then low else ORLow[1];

lines 318-319:
def crossAbove = high crosses above ORHigh;
def crossBelow = low crosses below ORLow;

lines 325-326:
def buy = if (FTCUP and Active and crossAbove and RL and RL2) then 1 else if (WFTCUP and Active and crossAbove and CL and CL2) then 1 else 0;
def sell = if (FTCDN and Active and crossBelow and RS and RS2) then 1 else if (WFTCDN and Active and crossBelow and CS and CS2) then 1 else 0;

Thanks again for building this. I think it's awesome.
Thanks! No problem, hopefully a few people make use of it!

Yeah so TOS strategies lock the entry price to the open of the bar but the entry is actually once price crosses the ORHigh or ORLow. That being said it is a quicker strategy and I'm working on writing documentation of what it is actually doing so people can better plan for entry!
 
This is a really cool concept. A couple of questions: 1- how are the timeframe inputs intended to be set? If I trade off a 5min chart, should I leave the inputs as 15m, 1D ? 2- I like to use a 30min ORB and potentially take trades until 3pm. Can I just change to inputs to ORB 1000am, and close 1500pm?
 
This is a really cool concept. A couple of questions: 1- how are the timeframe inputs intended to be set? If I trade off a 5min chart, should I leave the inputs as 15m, 1D ? 2- I like to use a 30min ORB and potentially take trades until 3pm. Can I just change to inputs to ORB 1000am, and close 1500pm?
Definitely play around with all the settings and find what works best for you, I actually like to use the 4hr and Daily charts, not the 15 even though that is default
 
This is a really cool concept. A couple of questions: 1- how are the timeframe inputs intended to be set? If I trade off a 5min chart, should I leave the inputs as 15m, 1D ? 2- I like to use a 30min ORB and potentially take trades until 3pm. Can I just change to inputs to ORB 1000am, and close 1500pm?
and yes, definitely you can change the ORB time and the market close time to reflect your parameters
 
Thanks for posting Aaron. I'm confused by the buy[-1] and the sell [-1] in the opening trades. Doesn't this mean that the code is looking ahead, something that is impossible to do when actually trading? You'll only know if the condition has been met when the bar closes so shouldn't it be buy[1] and sell[1]? Thanks again - Matt.
 
Thanks for posting Aaron. I'm confused by the buy[-1] and the sell [-1] in the opening trades. Doesn't this mean that the code is looking ahead, something that is impossible to do when actually trading? You'll only know if the condition has been met when the bar closes so shouldn't it be buy[1] and sell[1]? Thanks again - Matt.
Edit it and test it out! Let me know what you find!
 
Traders, What happened here. Thread went quiet since mid January. I am interested to know the outcome of the testing and changes made if any. Has anyone used this strat trading options? Thanks to all!
 
  • Like
Reactions: Ccd
Hi @aaronjure ! This is truly a fantastic script/strategy. One request and one question:
  1. Request: Since learning The Strat a couple years ago, I understand that the magnitidue(or take profit, or price targets) are the highs of the candles that have not been already crossed by the current candle. So- the PT(price target) is NOT just the most recent high, one would have to look for the most recent high that is higher than the current candle. Request: Can you plot 2 of those lines in your study, showing 2 most recent Highs/ Lows that are higher/lower than the current daily candle?
  2. Question on your entry criteria being met: basing my assumption here on this criteria you listed out in the code:
    1. if TFC/WFTC in place
    2. (and) Daily CL2/RL2/CS2/RS2 is setup for a strat pattern (ie 2-1)
    3. (and) 4h CL/RL/CS/RS strat pattern is COMPLETE (or gaps to complete) (ie prev day 4h's were 3-1)
    4. (and) ORB cross above/below
    5. Then enter long/short
---> however, the CL/RL/CS/CL 4h strat pattern doesnt always complete, and yet it triggers entry. Is the pattern complete whenever the 1/5/15/30/1h would, in theory, make that 4h pattern complete? On certain charts it doesnt complete at all (ie the first 15 min is a 3, making it a 3-1 from prev days 4h, and the 15 is a 3) but triggers entry anyway.
--->Can you clarify the criteria for the Long/Short entry on the 4h criteria ? When does the 4h completed pattern trigger as complete enough to enter? Also, based on the strat, shouldnt an additional criteria also be that entry should be when there is also a cross above the previous HOD/LOD?

**(also think there's a typo in your criteria listed above, you wrote 'Continuations Long' under the 'Short Criteria' section, think you meant 'Continuations Short')
 
Last edited:
Hi @aaronjure ! This is truly a fantastic script/strategy. Few questions:
1. Since learning The Strat a couple years ago, the take profit/ price target/magnitude points are the highs of the candles that have not been already crossed by the current candle. Can you plot those higher highs (as lines) and use those as the TP(TakeProfit)? Can the take profit lines (TP) be the highs from the candles of the day prior, that werent already crossed by that day's high? Can you add to the lines showing the 2 most recent H/L's? reason being the take profit (or target, or magnitude) with The Strat is usually the most recent highs (when entering calls), and lows (when entering puts). 2. Can you clarify the criteria for the Long/Short entry? Your criteria is a. Daily CL2/RL2/CS2/RS2 should be in a setup (ie 2-1), b. 4h CL/RL/CS/RS is complete or gaps up and c. the ORB cross above/below- but I notice the 4h strat pattern doesnt always complete(even if its within the first 15-30 mins) and the entry fires anyway.
Hey there, thank you!

ill number my answers to your questions!

1) This is easily done by using thinkorswims own "Daily High/Low" script. The way i use this strategy is to take advantage of quick moves, using my included targets, not the whole move because a lot of times magnitude is not always reached.

2) There is documentation in the original post of what i am looking for, the daily setup does not need to be complete (trigger doesnt have to be hit), BUT the 4 hour setup does need to complete within opening 5/15 min range (whichever you choose to use) or i dont not want to trade that stock, there is still indecision in my opinion in this case.
 
Hey there, thank you!

ill number my answers to your questions!

1) This is easily done by using thinkorswims own "Daily High/Low" script. The way i use this strategy is to take advantage of quick moves, using my included targets, not the whole move because a lot of times magnitude is not always reached.

2) There is documentation in the original post of what i am looking for, the daily setup does not need to be complete (trigger doesnt have to be hit), BUT the 4 hour setup does need to complete within opening 5/15 min range (whichever you choose to use) or i dont not want to trade that stock, there is still indecision in my opinion in this case.
Hi @aaronjure awesome, thank you for the response!
1. paint only if previous high is higher than current high/ lower than current low- just the previous highs/lows arent useful, since it has to be higher than the current daily candle/lower than current daily candle, and I only seem to find scripts that are JUST the highs /lows of previous days... not painting only the actual magnitude.
2. Understood- so this strategy enters on the 4h being complete in >15 min. Personally thats I've found success if either the previous daily high/low was crossed (thus creating a complete daily pattern) OR if the 4h of the previous high/low was crossed (creating a 4h complete pattern) AND if the ORB was crossed in first 5 min, AND as long as the ATR(average true range) is within the close of the previous candle + magnitude is also within the ATR have been trying to create a scan (or strategy to backtest) but its difficult.
 
@aaronjure The TOS links are not working. Would you mind posting the codes individually?
The links work fine. Are you following these instructions: Click here for --> Easiest way to load shared links
The OP did save his charts w/ invalid characters in its name so you may see this:
qWYh3qp.png

So make sure to save the charts with a name that does not include illegal characters such as dots.


@aaronjure
 
Last edited:
* * I BELIEVE I FIXED REPAINTING --- UPDATED 1.19.22* *

Here is a price action (TheStrat) based ORB strategy with targets. It is ready to go and battle the markets.

I am always looking to improve the coding and strategy, any and all suggestions welcome.
Lots of credit to @Pelonsax for helping with coding and providing his codes to the public!

Link for importing here :
- ORBxSTRAT : http://tos.mx/mRdp958

- ORBxSTRATxMA : http://tos.mx/EC9TYtC

DISCORD : https://discord.gg/BcMw45EU

13686[/ATTACH]']
1vBfRuG.png

============================================================================================

Documentation for ORBxSTRAT trading system -

All trades are entered before 11:00am EST

FTC = Day/Hour/Thirty continuity // WFTC = Week/Day/Hour/Thirty continuity

CrossAbove = price crosses ORHigh // CrosseBelow = price crosses below ORLow

RL = 4hr reversal long // RS = 4hr reversal short
- - - > 4hr patterns must complete ( 2-1-2 // 3-2-2 // 1-2-2 // 2-2 // 3-1-2 // 1-1 OR 1 )

CL = 4hr continuation // CS = 4hr continuation
- - - > 4hr patterns must complete ( 2-2 // 1-2 // 3-2 )

RL2 = day reversal SETUP long // RS2 = day reversal SETUP short
- - - > I highlight SETUP because these patterns do not have to be complete, we are looking at the daily for the reversal setups ( 2-1 // 3-2 // 1-2 // 2 // 3-1 // 1-1 OR 3)

CL2 = day continuation SETUP long // CS2 = day continuation SETUP short
- - - > I highlight SETUP because these patterns do not have to be complete, we are looking at the daily for the reversal setups ( 2 // 1 // 3 )

LONG criteria -

Reversals Long - When there is RL2 ( 2D-1 // 2D // 3D-1 // 1-2D ) you must have one of the RL ( 2D-1-2U // 2D-2U // 3-1-2U // 1-1-2U // 1-2D-2U // 3-2U ) setups complete. This can be a gap or happen when the opening range causes the new 4hr bar to complete the Strat pattern. FTC UP must also be true to get a signal. Entry is CrossAbove.

Continuations long - To get a signal long when a stock is running you must have WFTC UP. A CL2 setup ( previous daily bar is 2U, inside, or 3U) must be present. CL ( 2U-2U // 1-2U // 3-2U // 2U // 3U ) or RL setup must also be complete. Entry is CrossAbove.

SHORT criteria -

Reversals Short - When there is RS2 ( 2U-1 // 2U // 3U-1 // 1-2U ) you must have one of the RS ( 2U-1-2D // 2U-2D // 3-1-2D // 1-1-2D // 1-2U-2D // 3-2D ) setups complete. This can be a gap or happen when the opening range causes the new 4hr bar to complete the Strat pattern. FTC DOWN must also be true to get a signal. Entry is CrossBelow.

Continuations long - To get a signal SHORT when a stock is falling you must have WFTC DOWN. A CS2 setup ( previous daily bar is 2D, inside, or 3D) must be present. CS ( 2D-2D // 1-2D // 3-2D // 2D // 3D ) or CS setup must also be complete. Entry is CrossBelow.

EXITS -

Targets are retracements of the range of the opening range. For example….if the OR range is 10 and the high is 100 and low is 90, then targets long are 110 then 120 and short are 80 then 70. This creates an easy 1:1 and 1:2 risk/reward profile using the opposite end of the opening range as your stop.

If you see a better way to stop out please share, I have found it too costly to use the midway point of the opening range when trading options.

I choose to exit at target 1 long and short, this is the exit with greatest probability but am working on a selling partial at target 1, move stop to break even, and hold for target 2 with remaining.
Great work, looks awesome, but I am not getting anything on screen other the top description. Any idea how I am messing this up:

gtQcpo7.png

Any idea? there is nothing on chart other than candles
 

Attachments

  • 1vBfRuG.png
    1vBfRuG.png
    358.7 KB · Views: 338
Last edited by a moderator:
this looks awesome, seems to give best results mostly on the 30-minute charts
has anyone been able to integrate the position sizing calculator to this so it shows the number of shares per trade according to personal risk tolerance? that would make this strategy perfect
 
Code:
#A.URExPELONSAX - CUSTOM ORB-FTFC STRATEGY

AddLabel(yes, “ ORBxSTRATxMA.1  ”, color.yellow);

input OpenRangeMinutes = 5;
input MarketOpenTime = 0930;
input StartTime = 0930;
input MarketCloseTime = 1105;
input Time_Frame = AggregationPeriod.FOUR_HOURS;
input Time_Frame2 = AggregationPeriod.DAY;
input MA_TimeFrame = AggregationPeriod.DAY;
input ShowTodayOnly = no;
input price = close;
input securityType = { default "stocks"};

#--------- Choose Target ----------

input use_T1 = no;
input use_T2 = no;
input use_T3 = yes;
input use_T4 = yes;
input use_T5 = yes;
input use_T6 = yes;

#--------------ORB-----------------

def Today = if GetDay() == GetLastDay() then 1 else 0;
def FirstMinute = if SecondsFromTime(MarketOpenTime) < 60 then 1 else 0;
def OpenRangeTime = if SecondsFromTime(MarketOpenTime) < 60 * OpenRangeMinutes then 1 else 0;

def ORHigh =  if FirstMinute then high else if OpenRangeTime and high > ORHigh[1] then high else ORHigh[1];
def ORLow = if FirstMinute then low else if OpenRangeTime and low < ORLow[1] then low else ORLow[1];

plot OpenRangeHigh = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORHigh else Double.NaN;
plot OpenRangeLow = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORLow else Double.NaN;

def Active;
if securityType == securityType.stocks {
    Active = if (SecondsFromTime(StartTime) > 0 and SecondsTillTime(MarketCloseTime) > 0) then 1 else 0;
} else {
    Active = 1;  
    #Active = if ((SecondsFromTime(0500) > 0 and SecondsTillTime(0800) > 0)) or ((SecondsFromTime(1700) > 0 and SecondsTillTime(2100) > 0)) then 1 else 0;
}

OpenRangeHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OpenRangeHigh.SetDefaultColor(Color.YELLOW);
OpenRangeHigh.SetLineWeight(1);
OpenRangeLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OpenRangeLow.SetDefaultColor(Color.YELLOW);
OpenRangeLow.SetLineWeight(1);

def half = (ORHigh + ORLow) / 2;
def rangee = OpenRangeHigh - OpenRangeLow;
def T1 = ORHigh + (rangee / 2);
def T2 = ORLow - (rangee / 2);
plot T3 = ORHigh + (rangee);
plot T4 = ORLow - (rangee);
plot T5 = ORHigh + (rangee * 2);
plot T6 = ORLow - (rangee * 2);
#plot mid = half;

AddLabel(yes, Round(T5, 2) + " ", Color.CYAN);
AddLabel(yes, Round(T3, 2) + " ", Color.CYAN);
AddLabel(yes, Round(rangee, 2) + " ", Color.YELLOW);
AddLabel(yes, Round(T4, 2) + " ", Color.MAGENTA);
AddLabel(yes, Round(T6, 2) + " ", Color.MAGENTA);

T3.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T3.SetDefaultColor(Color.CYAN);
T3.SetLineWeight(1);
T4.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T4.SetDefaultColor(Color.MAGENTA);
T4.SetLineWeight(1);
T5.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T5.SetDefaultColor(Color.CYAN);
T5.SetLineWeight(1);
T6.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T6.SetDefaultColor(Color.MAGENTA);
T6.SetLineWeight(1);

# -----------------------------------
# HIGHER TIMEFRAMES
# -----------------------------------

def H1 = high(period = Time_Frame);
def L1 = low(period = Time_Frame);
def O1 = open(period = Time_Frame);
def C1 = close(period = Time_Frame);

def H2 = high(period = Time_Frame2);
def L2 = low(period = Time_Frame2);
def O2 = open(period = Time_Frame2);
def C2 = close(period = Time_Frame2);

#------------------------------------
# DEFINE SCENARIOS
#------------------------------------

def insidebar =  (H1 < H1[1] and L1 > L1[1]) or (H1 == H1[1] and L1 > L1[1]) or (H1 < H1[1] and L1 == L1[1]) or (H1 == H1[1] and L1 == L1[1]);
def outsidebar =  H1  > H1[1] and L1 <  L1[1];
def insidebarup  = insidebar and O1 < C1;
def twoup  = H1 > H1[1] and L1 >= L1[1];
def outsidebarup  = outsidebar and O1 < C1;
def insidebardown  = insidebar and O1 > C1;
def twodown  = H1 <= H1[1] and L1 < L1[1];
def outsidebardown  = outsidebar and O1 > C1;

#------------------------------------
# DEFINE SCENARIOS 4HR
#------------------------------------

def fourlong = twoup or outsidebarup;
def fourshort = twodown or outsidebardown;

def fourcontlong = ((twoup[1] or (twoup[2] or outsidebar[2] and insidebar[1]) or (insidebar[2] and insidebar[1]) or outsidebar[1]) and twoup);
def fourcontshort = ((twodown[1] or (twodown[2] or outsidebar[2] and insidebar[1]) or (insidebar[2] and insidebar[1]) or outsidebar[1]) and twodown);

#------------------------------------
# DEFINE SCENARIOS DAY
#------------------------------------

def insidebar2 =  (H2 < H2[1] and L2 > L2[1]) or (H2 == H2[1] and L2 > L2[1]) or (H2 < H2[1] and L2 == L2[1]) or (H2 == H2[1] and L2 == L2[1]);
def outsidebar2 =  H2  > H2[1] and L2 <  L2[1];
def insidebarup2  = insidebar2 and O2 < C2;
def twoup2  = H2 > H2[1] and L2 >= L2[1];
def outsidebarup2  = outsidebar2 and O2 < C2;
def insidebardown2  = insidebar2 and O2 > C2;
def twodown2  = H2 <= H2[1] and L2 < L2[1];
def outsidebardown2  = outsidebar2 and O2 > C2;

#------------------------------------
# DEFINE REVERSALS DAILY SETUP
#------------------------------------

def daylongsetup = twodown2[1] or outsidebar2[1] or ((twodown2[2] or outsidebar2[2]) and insidebar2[1]);
def dayshortsetup = twoup2[1] or outsidebar2[1] or ((twoup2[2] or outsidebar2[2]) and insidebar2[1]);

def daycontlong = twoup2[1] or (twoup2[2] or outsidebar2[2] and insidebar2[1]) or outsidebarup2[1];
def daycontshort = twodown2[1] or (twodown2[2] or outsidebar2[2] and insidebar2[1]) or outsidebardown2[1];

#------------FTFC--------------

def "30mAGG" = AggregationPeriod.THIRTY_MIN;
def "1hAGG" = AggregationPeriod.HOUR;
def "dAGG" = AggregationPeriod.DAY;
def "wAGG" = AggregationPeriod.WEEK;

def thirty = open(period = "30mAGG");
def hour = open(period = "1hAGG");
def dayy = open(period = "dAGG");
def week = open(period = "wAGG");

def UP = if thirty >=
hour and thirty >=
dayy then thirty  else

if hour >=
thirty and hour >=
dayy then hour else

if dayy >=
thirty and dayy >=
hour then dayy

else Double.NaN;

def DOWN = if thirty <=
hour and thirty <=
dayy then thirty  else

if hour <=
thirty and hour <=
dayy then hour else

if dayy <=
thirty and dayy <=
hour then dayy

else Double.NaN;

#WFTC----------------------

def WEEKUP =

if thirty >=
hour and thirty >=
dayy and thirty >=
week then thirty  else

if hour >=
thirty and hour >=
dayy and hour >=
week then hour else

if dayy >=
thirty and dayy >=
hour and dayy >=
week then dayy else

if week >=
thirty and week >=
hour and week >=
dayy then week

else Double.NaN;

def WEEKDN =

if thirty <= hour
and thirty <=
dayy and thirty <=
week then thirty  else

if hour <=
thirty and hour <=
dayy and hour <=
week then hour else

if dayy <=
thirty and dayy <=
hour and dayy <=
week then dayy else

if week <=
thirty and week <=
hour and week <=
dayy then week

else Double.NaN;

def FTCUP = close > UP;
def FTCDN = close < DOWN;
def WFTCUP = close > WEEKUP;
def WFTCDN = close < WEEKDN;

#------------HALF----------------

def h = H1;
def l = H1;

def halfrange = (h[1] - l[1]) / 2;
def stop = h[1] - halfrange;

def overhalf = price > stop;
def underhalf = price < stop;

#------------STOPS---------------

def LX = low crosses below ORLow;
def SX = high crosses above ORHigh;

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

def MA_close = close(period = MA_TimeFrame);

def MA1 = Average(MA_close, 9);
def MA2 = Average(MA_close, 21);

plot ln1 = MA1;
     ln1.SetDefaultColor(color.gray);
     ln1.SetLineWeight(3);

#def over_ma = MA1 > MA2;
#def under_ma = MA1 < MA2;
def overdayma = price > MA1;
def underdayma = price < MA1;

def crossAbove = high crosses above ORHigh;
def crossBelow = low crosses below ORLow;

def fourhourhigh = H1[1];
def fourhourlow = L1[1];

def fhcl = ORHigh >= fourhourhigh and overdayma;
def fhcs = ORLow <= fourhourlow and underdayma;

#def buy = FTCUP and Active and crossAbove and (daylongsetup);
#def sell = FTCDN and Active and crossBelow and (dayshortsetup);

def buy = (if (FTCUP and Active and crossAbove and (fourcontlong or fourlong) and daylongsetup and fhcl) then 1 else if (WFTCUP and Active and crossAbove and (fourcontlong or fourlong) and daycontlong and fhcl) then 1 else 0);
def sell = (if (FTCDN and Active and crossBelow and (fourcontshort or fourshort) and dayshortsetup and fhcs) then 1 else if (WFTCDN and Active and crossBelow and (fourcontshort or fourshort) and daycontshort and fhcs) then 1 else 0);

#ENTRY-----------------------

AddOrder(OrderType.BUY_TO_OPEN, buy[-1], tickcolor = Color.LIME, arrowcolor = Color.LIME, name = "LONG : " + ORLow);
AddOrder(OrderType.SELL_TO_OPEN, sell[-1], tickcolor = Color.RED, arrowcolor = Color.RED, name = "SHORT : " + ORHigh);

#OUTS_-----------------------

def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];

def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());

def afterEnd = GetTime() > RegularTradingEnd(GetYYYYMMDD());

def firstBarOfDay = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;

def lastBarOfDay = if

    (afterEnd[-2] == 1 and afterEnd == 0) or

    (isRollover[-2] and firstBarOfDay[-2])

    then 1

    else 0;

AddOrder(OrderType.SELL_TO_CLOSE, high[-1] crosses above (if use_T1 and T1 then T1 else if use_T3 and T3 then T3 else if use_T5 and T5 then T5 else 0), tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "TP");
AddOrder(OrderType.BUY_TO_CLOSE, low[-1] crosses below (if use_T2 and T2 then T2 else if use_T4 and T4 then T4 else if use_T6 and T6 then T6 else 0), tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "TP");

AddOrder(OrderType.SELL_TO_CLOSE, lastBarOfDay, tickcolor = Color.PLUM, arrowcolor = Color.PLUM, name = "EOD");
AddOrder(OrderType.BUY_TO_CLOSE, lastBarOfDay, tickcolor = Color.PLUM, arrowcolor = Color.PLUM, name = "EOD");

AddOrder(OrderType.SELL_TO_CLOSE, LX[-1], tickcolor = Color.YELLOW, arrowcolor = Color.YELLOW, name = "STOP");
AddOrder(OrderType.BUY_TO_CLOSE, SX[-1], tickcolor = Color.YELLOW, arrowcolor = Color.YELLOW, name = "STOP");

#RISK - EMILY IN DISCORD


# Input max percentage of a portfolio that one stock should be
input Max_Percent = 0.01;


def netliq = GetNetLiq ();

input scale_in = yes;
input times_to_scale_in = 2;

### Risk of Portfolio

def twoperc = netliq * (Max_Percent / 1);
AddLabel(yes, Max_Percent + "% ActRisk " + AsDollars(twoperc), Color.CYAN);

# Input position risk
input RiskPercent = .02;

# Position Size
def currentPrice = close;
def dollarRisk = (currentPrice * RiskPercent);
def stopPrice = (currentPrice - dollarRisk);
def SHAREStoBUY = twoperc / (currentPrice - stopPrice);

input showlabel = yes;
AddLabel (yes, " shares to buy " + roundup ((SHAREStoBUY),0), Color.CYAN);


#AddLabel (yes, " shares to BUY 3 times " + roundup ((SHAREStoBUY /3),0), Color.CYAN);

AddLabel (yes, AsPercent(RiskPercent)+ " Stop " + AsDollars (currentPrice - (currentPrice * RiskPercent)), Color.light_red);

AddLabel (yes, " Total Capital this trade " + AsDollars (SHAREStoBUY * currentPrice), Color.CYAN);
#Globals
def nan = Double.NaN;
def bn = if !IsNaN(close) and !IsNaN(close[1]) and !IsNaN(close[-1]) then BarNumber() else bn[1];

#Inputs
input fplTargetWinLoss = .50;
#hint fplTargetWinLoss: sets the target winlossRatio (in percent) which determines display colors of the W/L label.

input fplTargetWinRate = 1;
#hint fplTargetWinRate: sets the target winRate (float) which determines display colors of the WinRate label;

input fplHidePrice = no;
#hint fplHidePrice: hide's the underlying price graph. \nDefault is no.

input fplHideFPL = yes;
#hint fplHideFPL: hide's the underlying P&L graph.\nDefault is yes.

#temp input var references
def targetWinLoss = fplTargetWinLoss;
def targetWinRate = fplTargetWinRate;
def hidePrice = fplHidePrice;
def hideFPL = fplHideFPL;

#hide chart candles
HidePricePlot(hidePrice);

#Plot default Floating P&L
plot FPL = FPL();
FPL.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
FPL.DefineColor("Positive and Up", Color.GREEN);
FPL.DefineColor("Positive and Down", Color.DARK_GREEN);
FPL.DefineColor("Negative and Down", Color.RED);
FPL.DefineColor("Negative and Up", Color.DARK_RED);
FPL.AssignValueColor(if FPL >= 0
                        then if FPL > FPL[1]
                        then FPL.Color("Positive and Up")
                        else FPL.Color("Positive and Down")
                        else if FPL < FPL[1]
                        then FPL.Color("Negative and Down")
                        else FPL.Color("Negative and Up"));
FPL.SetHiding(hideFPL);

plot ZeroLine = if IsNaN(close)
            then nan
            else 0;
ZeroLine.SetDefaultColor(Color.GRAY);
ZeroLine.SetHiding(hideFPL);

#Global Scripts
script incrementValue {
    input condition = yes;
    input increment =  1;
    input startingValue = 0;

    def _value = CompoundValue(1,
                if condition
                then _value[1] + increment
                else _value[1], startingValue);

    plot incrementValue = _value;
}
;

# Entry Calculations.  Note: Only parses on a Strategy Chart
def entry = EntryPrice();

def entryPrice = if !IsNaN(entry)
                then entry
                else entryPrice[1];

def hasEntry = !IsNaN(entry);

def isNewEntry = entryPrice != entryPrice[1];

#is active trade
def highFPL = HighestAll(FPL);
def lowFPL = LowestAll(FPL);

def fplreturn = (FPL - FPL[1]) / FPL[1];
def cumsum = Sum(fplreturn);

def highBarNumber = CompoundValue(1, if FPL == highFPL
                                    then bn
                                    else highBarNumber[1], 0);

def lowBarNumber = CompoundValue(1, if FPL == lowFPL
                                then bn
                                else lowBarNumber[1], 0);

#Win/Loss ratios
def entryBarsTemp = if hasEntry
                then bn
                else nan;

def entryBarNum = if hasEntry and isNewEntry
                then bn
                else entryBarNum[1];

def isEntryBar = entryBarNum != entryBarNum[1];

def entryBarPL = if isEntryBar
                then FPL
                else entryBarPL[1];

def exitBarsTemp = if !hasEntry
                and bn > entryBarsTemp[1]
                then bn
                else nan;

def exitBarNum = if !hasEntry and !IsNaN(exitBarsTemp[1])
                then bn
                else exitBarNum[1];

def isExitBar = exitBarNum != exitBarNum[1];

def exitBarPL = if isExitBar
            then FPL
            else exitBarPL[1];

def entryReturn = if isExitBar then exitBarPL - exitBarPL[1] else entryReturn[1];
def isWin = if isExitBar and entryReturn >= 0 then 1 else 0;
def isLoss = if isExitBar and entryReturn < 0 then 1 else 0;
def entryReturnWin = if isWin then entryReturn else entryReturnWin[1];
def entryReturnLoss = if isLoss then entryReturn else entryReturnLoss[1];
def entryFPLWins = if isWin then entryReturn else 0;
def entryFPLLosses = if isLoss then entryReturn else 0;
def entryFPLAll = if isLoss or isWin then entryReturn else 0;

#Counts
def entryCount = incrementValue(entryFPLAll);
def winCount = incrementValue(isWin);
def lossCount = incrementValue(isLoss);

def highestReturn = if entryReturnWin[1] > highestReturn[1]
                then entryReturnWin[1]
                else highestReturn[1];

def lowestReturn = if entryReturnLoss[1] < lowestReturn[1]
                then entryReturnLoss[1]
                else lowestReturn[1];


def winRate = winCount / lossCount;
def winLossRatio = winCount / entryCount;
def avgReturn = TotalSum(entryFPLAll) / entryCount;
def avgWin = TotalSum(entryFPLWins) / winCount;
def avgLoss = TotalSum(entryFPLLosses) / lossCount;

#Labels

AddLabel(yes,
        text = "Total Trades: " + entryCount + "  ",
        color = Color.WHITE
        );

#AddLabel(yes,
       # text = "WinCount: " + winCount +
           # " | LossCount: " + lossCount +
           # " | WinRate: " + Round(winRate, 2) + "  ",
       # color = if winRate >= targetWinRate
               # then Color.CYAN
               # else Color.MAGENTA
       # );

AddLabel(yes,
        text = "W/L: " + AsPercent(winLossRatio) + " ",
        color = if winLossRatio > targetWinLoss
                then Color.CYAN
                else Color.MAGENTA
        );

#AddLabel(yes,
       # text = "AvgReturn: " + AsDollars(avgReturn) +
           # " | AvgWin: " + AsDollars(avgWin) +
           # " | AvgLoss: " + AsDollars(avgLoss) + "   ",
       # color = if avgReturn >= 0
               # then Color.CYAN
               # else Color.MAGENTA
       # );

AddLabel(yes,
        text = "Total Profit: " + AsDollars(FPL) + "  ",
        color = if FPL > 0
                then Color.CYAN
                else Color.MAGENTA
    );
 
I like this code, I havent tried it out live yet but i spent a lot of time this weekend trying it out with the on demand feature and it was successful much more than unsuccessful on the 30 minute chart, I hacked this code up a little trying to add the position size calculator to it. I can get the labels to show for the position size calculator but i cant figure out how to get them to show in the "add order" portion of the code so that it give real time live position to take according to account size and also realistically give what your P/L would be if you traded according to the back test trade report. Lines 320 through 344 are the code i hacked up to work,. can someone possible try to make the add order portion to
Code:
#A.URExPELONSAX - CUSTOM ORB-FTFC STRATEGY

AddLabel(yes, “ ORBxSTRATxMA.1  ”, color.yellow);

input OpenRangeMinutes = 5;
input MarketOpenTime = 0930;
input StartTime = 0930;
input MarketCloseTime = 1105;
input Time_Frame = AggregationPeriod.FOUR_HOURS;
input Time_Frame2 = AggregationPeriod.DAY;
input MA_TimeFrame = AggregationPeriod.DAY;
input ShowTodayOnly = no;
input price = close;
input securityType = { default "stocks"};

#--------- Choose Target ----------

input use_T1 = no;
input use_T2 = no;
input use_T3 = yes;
input use_T4 = yes;
input use_T5 = yes;
input use_T6 = yes;

#--------------ORB-----------------

def Today = if GetDay() == GetLastDay() then 1 else 0;
def FirstMinute = if SecondsFromTime(MarketOpenTime) < 60 then 1 else 0;
def OpenRangeTime = if SecondsFromTime(MarketOpenTime) < 60 * OpenRangeMinutes then 1 else 0;

def ORHigh =  if FirstMinute then high else if OpenRangeTime and high > ORHigh[1] then high else ORHigh[1];
def ORLow = if FirstMinute then low else if OpenRangeTime and low < ORLow[1] then low else ORLow[1];

plot OpenRangeHigh = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORHigh else Double.NaN;
plot OpenRangeLow = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORLow else Double.NaN;

def Active;
if securityType == securityType.stocks {
    Active = if (SecondsFromTime(StartTime) > 0 and SecondsTillTime(MarketCloseTime) > 0) then 1 else 0;
} else {
    Active = 1;   
    #Active = if ((SecondsFromTime(0500) > 0 and SecondsTillTime(0800) > 0)) or ((SecondsFromTime(1700) > 0 and SecondsTillTime(2100) > 0)) then 1 else 0;
}

OpenRangeHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OpenRangeHigh.SetDefaultColor(Color.YELLOW);
OpenRangeHigh.SetLineWeight(1);
OpenRangeLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OpenRangeLow.SetDefaultColor(Color.YELLOW);
OpenRangeLow.SetLineWeight(1);

def half = (ORHigh + ORLow) / 2;
def rangee = OpenRangeHigh - OpenRangeLow;
def T1 = ORHigh + (rangee / 2);
def T2 = ORLow - (rangee / 2);
plot T3 = ORHigh + (rangee);
plot T4 = ORLow - (rangee);
plot T5 = ORHigh + (rangee * 2);
plot T6 = ORLow - (rangee * 2);
#plot mid = half;

AddLabel(yes, Round(T5, 2) + " ", Color.CYAN);
AddLabel(yes, Round(T3, 2) + " ", Color.CYAN);
AddLabel(yes, Round(rangee, 2) + " ", Color.YELLOW);
AddLabel(yes, Round(T4, 2) + " ", Color.MAGENTA);
AddLabel(yes, Round(T6, 2) + " ", Color.MAGENTA);

T3.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T3.SetDefaultColor(Color.CYAN);
T3.SetLineWeight(1);
T4.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T4.SetDefaultColor(Color.MAGENTA);
T4.SetLineWeight(1);
T5.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T5.SetDefaultColor(Color.CYAN);
T5.SetLineWeight(1);
T6.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
T6.SetDefaultColor(Color.MAGENTA);
T6.SetLineWeight(1);

# -----------------------------------
# HIGHER TIMEFRAMES
# -----------------------------------

def H1 = high(period = Time_Frame);
def L1 = low(period = Time_Frame);
def O1 = open(period = Time_Frame);
def C1 = close(period = Time_Frame);

def H2 = high(period = Time_Frame2);
def L2 = low(period = Time_Frame2);
def O2 = open(period = Time_Frame2);
def C2 = close(period = Time_Frame2);

#------------------------------------
# DEFINE SCENARIOS
#------------------------------------

def insidebar =  (H1 < H1[1] and L1 > L1[1]) or (H1 == H1[1] and L1 > L1[1]) or (H1 < H1[1] and L1 == L1[1]) or (H1 == H1[1] and L1 == L1[1]);
def outsidebar =  H1  > H1[1] and L1 <  L1[1];
def insidebarup  = insidebar and O1 < C1;
def twoup  = H1 > H1[1] and L1 >= L1[1];
def outsidebarup  = outsidebar and O1 < C1;
def insidebardown  = insidebar and O1 > C1;
def twodown  = H1 <= H1[1] and L1 < L1[1];
def outsidebardown  = outsidebar and O1 > C1;

#------------------------------------
# DEFINE SCENARIOS 4HR
#------------------------------------

def fourlong = twoup or outsidebarup;
def fourshort = twodown or outsidebardown;

def fourcontlong = ((twoup[1] or (twoup[2] or outsidebar[2] and insidebar[1]) or (insidebar[2] and insidebar[1]) or outsidebar[1]) and twoup);
def fourcontshort = ((twodown[1] or (twodown[2] or outsidebar[2] and insidebar[1]) or (insidebar[2] and insidebar[1]) or outsidebar[1]) and twodown);

#------------------------------------
# DEFINE SCENARIOS DAY
#------------------------------------

def insidebar2 =  (H2 < H2[1] and L2 > L2[1]) or (H2 == H2[1] and L2 > L2[1]) or (H2 < H2[1] and L2 == L2[1]) or (H2 == H2[1] and L2 == L2[1]);
def outsidebar2 =  H2  > H2[1] and L2 <  L2[1];
def insidebarup2  = insidebar2 and O2 < C2;
def twoup2  = H2 > H2[1] and L2 >= L2[1];
def outsidebarup2  = outsidebar2 and O2 < C2;
def insidebardown2  = insidebar2 and O2 > C2;
def twodown2  = H2 <= H2[1] and L2 < L2[1];
def outsidebardown2  = outsidebar2 and O2 > C2;

#------------------------------------
# DEFINE REVERSALS DAILY SETUP
#------------------------------------

def daylongsetup = twodown2[1] or outsidebar2[1] or ((twodown2[2] or outsidebar2[2]) and insidebar2[1]);
def dayshortsetup = twoup2[1] or outsidebar2[1] or ((twoup2[2] or outsidebar2[2]) and insidebar2[1]);

def daycontlong = twoup2[1] or (twoup2[2] or outsidebar2[2] and insidebar2[1]) or outsidebarup2[1];
def daycontshort = twodown2[1] or (twodown2[2] or outsidebar2[2] and insidebar2[1]) or outsidebardown2[1];

#------------FTFC--------------

def "30mAGG" = AggregationPeriod.THIRTY_MIN;
def "1hAGG" = AggregationPeriod.HOUR;
def "dAGG" = AggregationPeriod.DAY;
def "wAGG" = AggregationPeriod.WEEK;

def thirty = open(period = "30mAGG");
def hour = open(period = "1hAGG");
def dayy = open(period = "dAGG");
def week = open(period = "wAGG");

def UP = if thirty >=
hour and thirty >=
dayy then thirty  else

if hour >=
thirty and hour >=
dayy then hour else

if dayy >=
thirty and dayy >=
hour then dayy

else Double.NaN;

def DOWN = if thirty <=
hour and thirty <=
dayy then thirty  else

if hour <=
thirty and hour <=
dayy then hour else

if dayy <=
thirty and dayy <=
hour then dayy

else Double.NaN;

#WFTC----------------------

def WEEKUP =

if thirty >=
hour and thirty >=
dayy and thirty >=
week then thirty  else

if hour >=
thirty and hour >=
dayy and hour >=
week then hour else

if dayy >=
thirty and dayy >=
hour and dayy >=
week then dayy else

if week >=
thirty and week >=
hour and week >=
dayy then week

else Double.NaN;

def WEEKDN =

if thirty <= hour
and thirty <=
dayy and thirty <=
week then thirty  else

if hour <=
thirty and hour <=
dayy and hour <=
week then hour else

if dayy <=
thirty and dayy <=
hour and dayy <=
week then dayy else

if week <=
thirty and week <=
hour and week <=
dayy then week

else Double.NaN;

def FTCUP = close > UP;
def FTCDN = close < DOWN;
def WFTCUP = close > WEEKUP;
def WFTCDN = close < WEEKDN;

#------------HALF----------------

def h = H1;
def l = H1;

def halfrange = (h[1] - l[1]) / 2;
def stop = h[1] - halfrange;

def overhalf = price > stop;
def underhalf = price < stop;

#------------STOPS---------------

def LX = low crosses below ORLow;
def SX = high crosses above ORHigh;

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

def MA_close = close(period = MA_TimeFrame);

def MA1 = Average(MA_close, 9);
def MA2 = Average(MA_close, 21);

plot ln1 = MA1;
     ln1.SetDefaultColor(color.gray);
     ln1.SetLineWeight(3);

#def over_ma = MA1 > MA2;
#def under_ma = MA1 < MA2;
def overdayma = price > MA1;
def underdayma = price < MA1;

def crossAbove = high crosses above ORHigh;
def crossBelow = low crosses below ORLow;

def fourhourhigh = H1[1];
def fourhourlow = L1[1];

def fhcl = ORHigh >= fourhourhigh and overdayma;
def fhcs = ORLow <= fourhourlow and underdayma;

#def buy = FTCUP and Active and crossAbove and (daylongsetup);
#def sell = FTCDN and Active and crossBelow and (dayshortsetup);

def buy = (if (FTCUP and Active and crossAbove and (fourcontlong or fourlong) and daylongsetup and fhcl) then 1 else if (WFTCUP and Active and crossAbove and (fourcontlong or fourlong) and daycontlong and fhcl) then 1 else 0);
def sell = (if (FTCDN and Active and crossBelow and (fourcontshort or fourshort) and dayshortsetup and fhcs) then 1 else if (WFTCDN and Active and crossBelow and (fourcontshort or fourshort) and daycontshort and fhcs) then 1 else 0);

#ENTRY-----------------------

AddOrder(OrderType.BUY_TO_OPEN, buy[-1], tickcolor = Color.LIME, arrowcolor = Color.LIME, name = "LONG : " + ORLow);
AddOrder(OrderType.SELL_TO_OPEN, sell[-1], tickcolor = Color.RED, arrowcolor = Color.RED, name = "SHORT : " + ORHigh);

#OUTS_-----------------------

def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];

def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());

def afterEnd = GetTime() > RegularTradingEnd(GetYYYYMMDD());

def firstBarOfDay = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;

def lastBarOfDay = if

    (afterEnd[-2] == 1 and afterEnd == 0) or

    (isRollover[-2] and firstBarOfDay[-2])

    then 1

    else 0;

AddOrder(OrderType.SELL_TO_CLOSE, high[-1] crosses above (if use_T1 and T1 then T1 else if use_T3 and T3 then T3 else if use_T5 and T5 then T5 else 0), tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "TP");
AddOrder(OrderType.BUY_TO_CLOSE, low[-1] crosses below (if use_T2 and T2 then T2 else if use_T4 and T4 then T4 else if use_T6 and T6 then T6 else 0), tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "TP");

AddOrder(OrderType.SELL_TO_CLOSE, lastBarOfDay, tickcolor = Color.PLUM, arrowcolor = Color.PLUM, name = "EOD");
AddOrder(OrderType.BUY_TO_CLOSE, lastBarOfDay, tickcolor = Color.PLUM, arrowcolor = Color.PLUM, name = "EOD");

AddOrder(OrderType.SELL_TO_CLOSE, LX[-1], tickcolor = Color.YELLOW, arrowcolor = Color.YELLOW, name = "STOP");
AddOrder(OrderType.BUY_TO_CLOSE, SX[-1], tickcolor = Color.YELLOW, arrowcolor = Color.YELLOW, name = "STOP");

#RISK - EMILY IN DISCORD


# Input max percentage of a portfolio that one stock should be
input Max_Percent = 0.01;


def netliq = GetNetLiq ();

input scale_in = yes;
input times_to_scale_in = 2;

### Risk of Portfolio

def twoperc = netliq * (Max_Percent / 1);
AddLabel(yes, Max_Percent + "% ActRisk " + AsDollars(twoperc), Color.CYAN);

# Input position risk
input RiskPercent = .02;

# Position Size
def currentPrice = close;
def dollarRisk = (currentPrice * RiskPercent);
def stopPrice = (currentPrice - dollarRisk);
def SHAREStoBUY = twoperc / (currentPrice - stopPrice);

input showlabel = yes;
AddLabel (yes, " shares to buy " + roundup ((SHAREStoBUY),0), Color.CYAN);


#AddLabel (yes, " shares to BUY 3 times " + roundup ((SHAREStoBUY /3),0), Color.CYAN);

AddLabel (yes, AsPercent(RiskPercent)+ " Stop " + AsDollars (currentPrice - (currentPrice * RiskPercent)), Color.light_red);

AddLabel (yes, " Total Capital this trade " + AsDollars (SHAREStoBUY * currentPrice), Color.CYAN);
#Globals
def nan = Double.NaN;
def bn = if !IsNaN(close) and !IsNaN(close[1]) and !IsNaN(close[-1]) then BarNumber() else bn[1];

#Inputs
input fplTargetWinLoss = .50;
#hint fplTargetWinLoss: sets the target winlossRatio (in percent) which determines display colors of the W/L label.

input fplTargetWinRate = 1;
#hint fplTargetWinRate: sets the target winRate (float) which determines display colors of the WinRate label;

input fplHidePrice = no;
#hint fplHidePrice: hide's the underlying price graph. \nDefault is no.

input fplHideFPL = yes;
#hint fplHideFPL: hide's the underlying P&L graph.\nDefault is yes.

#temp input var references
def targetWinLoss = fplTargetWinLoss;
def targetWinRate = fplTargetWinRate;
def hidePrice = fplHidePrice;
def hideFPL = fplHideFPL;

#hide chart candles
HidePricePlot(hidePrice);

#Plot default Floating P&L
plot FPL = FPL();
FPL.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
FPL.DefineColor("Positive and Up", Color.GREEN);
FPL.DefineColor("Positive and Down", Color.DARK_GREEN);
FPL.DefineColor("Negative and Down", Color.RED);
FPL.DefineColor("Negative and Up", Color.DARK_RED);
FPL.AssignValueColor(if FPL >= 0
                        then if FPL > FPL[1]
                        then FPL.Color("Positive and Up")
                        else FPL.Color("Positive and Down")
                        else if FPL < FPL[1]
                        then FPL.Color("Negative and Down")
                        else FPL.Color("Negative and Up"));
FPL.SetHiding(hideFPL);

plot ZeroLine = if IsNaN(close)
            then nan
            else 0;
ZeroLine.SetDefaultColor(Color.GRAY);
ZeroLine.SetHiding(hideFPL);

#Global Scripts
script incrementValue {
    input condition = yes;
    input increment =  1;
    input startingValue = 0;

    def _value = CompoundValue(1,
                if condition
                then _value[1] + increment
                else _value[1], startingValue);

    plot incrementValue = _value;
}
;

# Entry Calculations.  Note: Only parses on a Strategy Chart
def entry = EntryPrice();

def entryPrice = if !IsNaN(entry)
                then entry
                else entryPrice[1];

def hasEntry = !IsNaN(entry);

def isNewEntry = entryPrice != entryPrice[1];

#is active trade
def highFPL = HighestAll(FPL);
def lowFPL = LowestAll(FPL);

def fplreturn = (FPL - FPL[1]) / FPL[1];
def cumsum = Sum(fplreturn);

def highBarNumber = CompoundValue(1, if FPL == highFPL
                                    then bn
                                    else highBarNumber[1], 0);

def lowBarNumber = CompoundValue(1, if FPL == lowFPL
                                then bn
                                else lowBarNumber[1], 0);

#Win/Loss ratios
def entryBarsTemp = if hasEntry
                then bn
                else nan;

def entryBarNum = if hasEntry and isNewEntry
                then bn
                else entryBarNum[1];

def isEntryBar = entryBarNum != entryBarNum[1];

def entryBarPL = if isEntryBar
                then FPL
                else entryBarPL[1];

def exitBarsTemp = if !hasEntry
                and bn > entryBarsTemp[1]
                then bn
                else nan;

def exitBarNum = if !hasEntry and !IsNaN(exitBarsTemp[1])
                then bn
                else exitBarNum[1];

def isExitBar = exitBarNum != exitBarNum[1];

def exitBarPL = if isExitBar
            then FPL
            else exitBarPL[1];

def entryReturn = if isExitBar then exitBarPL - exitBarPL[1] else entryReturn[1];
def isWin = if isExitBar and entryReturn >= 0 then 1 else 0;
def isLoss = if isExitBar and entryReturn < 0 then 1 else 0;
def entryReturnWin = if isWin then entryReturn else entryReturnWin[1];
def entryReturnLoss = if isLoss then entryReturn else entryReturnLoss[1];
def entryFPLWins = if isWin then entryReturn else 0;
def entryFPLLosses = if isLoss then entryReturn else 0;
def entryFPLAll = if isLoss or isWin then entryReturn else 0;

#Counts
def entryCount = incrementValue(entryFPLAll);
def winCount = incrementValue(isWin);
def lossCount = incrementValue(isLoss);

def highestReturn = if entryReturnWin[1] > highestReturn[1]
                then entryReturnWin[1]
                else highestReturn[1];

def lowestReturn = if entryReturnLoss[1] < lowestReturn[1]
                then entryReturnLoss[1]
                else lowestReturn[1];


def winRate = winCount / lossCount;
def winLossRatio = winCount / entryCount;
def avgReturn = TotalSum(entryFPLAll) / entryCount;
def avgWin = TotalSum(entryFPLWins) / winCount;
def avgLoss = TotalSum(entryFPLLosses) / lossCount;

#Labels

AddLabel(yes,
        text = "Total Trades: " + entryCount + "  ",
        color = Color.WHITE
        );

#AddLabel(yes,
       # text = "WinCount: " + winCount +
           # " | LossCount: " + lossCount +
           # " | WinRate: " + Round(winRate, 2) + "  ",
       # color = if winRate >= targetWinRate
               # then Color.CYAN
               # else Color.MAGENTA
       # );

AddLabel(yes,
        text = "W/L: " + AsPercent(winLossRatio) + " ",
        color = if winLossRatio > targetWinLoss
                then Color.CYAN
                else Color.MAGENTA
        );

#AddLabel(yes,
       # text = "AvgReturn: " + AsDollars(avgReturn) +
           # " | AvgWin: " + AsDollars(avgWin) +
           # " | AvgLoss: " + AsDollars(avgLoss) + "   ",
       # color = if avgReturn >= 0
               # then Color.CYAN
               # else Color.MAGENTA
       # );

AddLabel(yes,
        text = "Total Profit: " + AsDollars(FPL) + "  ",
        color = if FPL > 0
                then Color.CYAN
                else Color.MAGENTA
    );
 

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

Thread starter Similar threads Forum Replies Date
Pelonsax Indicator for Think or Swim based on Rob Smith's The STRAT Strategies & Chart Setups 469

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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