3-in-1 Simple or Exponential Moving Average for ThinkorSwim

@Jenny I'll respond on behalf of @BenTen

Here is the relevant code segment that defines the situation you were enquiring about
Simply put, a CrossUp is triggered whenever the close is ABOVE moving average 1 (MA1) and MA1 is above MA2 and MA is above MA3
This is what I would call a bullish moving average alignment of all 3 moving averages

Now the other requirement is that there needs to be a state transition to an uptrend
Meaning that the previous bar those conditions did not hold true, and hence is a state transition to uptrend

Similarly for the downtrend, the conditions are exactly opposite where we would have bearish alignment
Hope this helps

Code:
# define e-signal and crossover point
def Eup = MA1 > MA2 && MA2 > MA3;
def Edn = MA1 < MA2 && MA2 < MA3;

def CrossUp = close > MA1 && Eup && !Eup[1];
def CrossDn = close < MA1 && Edn && !Edn[1];
 
hello folks,

i am extremely new to ToS so do not know any coding, can someone write a code for strategy on 3 moving averages:

If sma 10 period crosses above sma 20 period AND price is above 50 sma then buy

opposite for the sell.

two more conditions of a) triggering the new trades between 3AM to 3PM EST only. This also means a trade triggered at say 2:30 PM EST will either run till it reaches profit points or hits the stop loss.

b) taking automatic profits at 20 pips for forex and having stop loss of 10 pip for forex.

does ToS bring out any report on the strategies like total trades, win/loss ratio, drawdown etc. if so then how to access it.

thx all for the help, newbie here so many basic questions.
 
Last edited:
FYI _ I keep a 10 year / mo chart for a loooonnnnggggg view and this 3-line SMA with 50/100/200 SMA plots. This study will not plot beyond about 3 years historical. Maybe it overruns the memory of my Mac but I kinda doubt it. I tried to rem out anything other than the plots and it had no affect. Thoughts / fix much appreciated.
 
@BenTen Could you help me add this to make a trading strategy, just keeping it simple for now with 2 moving averages and then I go from there, I want to backtest it, what would I need to add to this code for the Buy order and Sell orders to plot this on the chart along with the P&L histogram?

Something like this could i get some help adding this thanks
# Bullish Orders
AddOrder(OrderType.BUY_TO_OPEN, condition = , price = close, 100, tickcolor = Color.GREEN, arrowcolor = Color.GREEN);
AddOrder(OrderType.SELL_TO_CLOSE, condition = , price = open, 100, tickcolor = Color.RED, arrowcolor = Color.RED);

# Bearish Orders
AddOrder(OrderType.SELL_TO_OPEN, condition = , price = open, 100, tickcolor = Color.RED, arrowcolor = Color.RED);
AddOrder(OrderType.BUY_TO_CLOSE, condition = , price = close, 100, tickcolor = Color.GREEN, arrowcolor = Color.GREEN);
 
heres a scan for price crossing 4/8/21 ,ill see if i can dig up the indi later

def EMA4 = MovingAverage(AverageType.EXPONENTIAL, close, 4);
def EMA8 = MovingAverage(AverageType.EXPONENTIAL, close, 8);
def EMA21 = MovingAverage(AverageType.EXPONENTIAL, close, 21);

# check for open below EMA 4, 8, and 21
def openBelow = open < EMA4 and open < EMA8 and open < EMA 21;

# check for close above EMA 4, 8, and 21
def closeAbove = close > EMA4 and close > EMA8 and close > EMA21;

# scan for stocks that meet all conditions
plot signal = openBelow and closeAbove;
 
@Trading51 No need to use this script or make a backtesting strategy out of it. There is already a backtesting strategy in ThinkorSwim called GoldenCrossBreakouts. You can use that instead. Just adjust the two moving averages to whichever period you want.
I added it but I noticed it's not taking all the trades example I put 100 and 200 EXP and when the MA is crossing back and forth its not taking all the trades only som, in the "Orders area" would I need to adjust anything, Should it be set to auto for the buy and for the sell? I want to enter on the upward cross and I want to exit on the downward cross of the moving averages let me please thanks.
 
i wanted to get long when the 100 crosses above the 200 and when the 100 crosses the 200 on the downside i wanted to get short
 
@Trading51 If you want to include both long and short strategy, you would need to edit the script. By default, it's set to Auto, which will likely not include everything. You want a Buy to Open / Sell to Close and Sell to Open / Buy to Close.
 
@Trading51 If you want to include both long and short strategy, you would need to edit the script. By default, it's set to Auto, which will likely not include everything. You want a Buy to Open / Sell to Close and Sell to Open / Buy to Close.
Just to confirm I only need to add the Golden cross script once not twice to add these 4 inputs ?
 
Am new to thinkscript coding, so verifying if this is correct. I want to replace chart bubbles with arrows, so am adding this code.

Code:
input show_arrows = yes;

# Plot Up / Down Arrow
plot up_signal = SignalUp;
up_signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
up_signal.SetDefaultColor(Color.GREEN);
up_signal.SetHiding(!show_arrows);
plot down_signal = SignalDn;
down_signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
down_signal.SetDefaultColor(Color.RED);
down_signal.SetHiding(!show_arrows);
 
Last edited by a moderator:
@Trading51 If you want to include both long and short strategies, you would need to edit the script. By default, it's set to Auto, which will likely not include everything. You want a Buy to Open / Sell to Close and Sell to Open / Buy to Close.
@BenTen I couldn't add all 4 inputs to one code so i added the code twice and added all for but it still doesn't capture all the crosses of the Moving averages, can you let me know what I'm missing?
 
I also tried to make a watchlist column out of it, similar to the MACD one. I modified the original code and added the signal lines to show background color. Does this look right? I used it on the futures symbols, looks okay

Code:
# 3-in-1 moving avg crossover watchlist column

declare upper;
input lookback = 5;
input short_average = 5;
input medium_average = 8;
input long_average = 13;
input average_type = {default "EMA", "SMA"};
input show_arrows = yes;

def MA1;
def MA2;
def MA3;
switch (average_type) {
case "SMA":
    MA1 = Average(close, short_average);
    MA2 = Average(close, medium_average);
    MA3 = Average(close, long_average);
case "EMA":
    MA1 = ExpAverage(close, short_average);
    MA2 = ExpAverage(close, medium_average);
    MA3 = ExpAverage(close, long_average);
}

# define e-signal and crossover point
def Eup = MA1 > MA2 && MA2 > MA3;
def Edn = MA1 < MA2 && MA2 < MA3;

def CrossUp = close > MA1 && Eup && !Eup[1];
def CrossDn = close < MA1 && Edn && !Edn[1];

# Define up and down signals
def higherHigh = close > Highest(max(open,close), 3)[1];
def lowerLow = close < Lowest(min(open,close), 3)[1];
def SignalUp = if (CrossUp && higherHigh)
    then 1
        else if    (CrossUp[1] && higherHigh && !higherHigh[1])
    then 1
        else if    (CrossUp[2] && higherHigh && !higherHigh[1] && !higherHigh[2])
    then 1
        else 0;
def SignalDn = if (CrossDn && lowerLow)
    then 1
        else if (CrossDn[1] && lowerLow && !lowerLow[1])
    then 1
        else if (CrossDn[2] && lowerLow && !lowerLow[1] && !lowerLow[2])
    then 1
        else 0;

def bull_lookback = highest(SignalUp, lookback);
def bear_lookback = highest(SignalDn, lookback);

plot signal = if bull_lookback then 2 else if bear_lookback then 1 else 0;
signal.AssignValueColor(if signal == 2 then Color.Dark_Green else if signal == 1 then Color.Dark_Red else Color.WHITE);
AssignBackgroundCOlor(if signal == 2 then Color.Dark_Green else if signal == 1 then Color.Dark_Red else Color.WHITE);
 
Hi There,

I am looking for a code modifications to throw an alert green, or red when it 13,30 moves 200 EMA on 5day 5 min charts for below code for my watch list. could someone pls help.

Code:
declare lower;

input lookback = 1;
input short_average = 13;
input medium_average = 30;
input long_average = 200;
input averageType = AverageType.EXPONENTIAL;
input showBreakoutSignals = no;

def MA1;
def MA2;
def MA3;
MA1 = Average(close, short_average);
MA2 = Average(close, medium_average);
MA3 = Average(close, long_average);

# define e-signal and crossover point
def Eup = MA1 > MA2 && MA2 > MA3;
def Edn = MA1 < MA2 && MA2 < MA3;

plot signal = if Eup then 2 else if Edn then 1 else 0;
signal.AssignValueColor(if signal == 2 then Color.Dark_Green else if signal == 1 then Color.Dark_Red else Color.Dark_Orange);
AssignBackgroundCOlor(if signal == 2 then Color.Dark_Green else if signal == 1 then Color.Dark_Red else Color.Dark_Orange);

#Alert(close >= 5 and close < 10, "100 <= Tick < 10!", #Alert.TICK, Sound.Ding);
#Alert(close >= 5, "Tick > 10!", Alert.TICK, Sound.Chimes);
 
@BenTen can you create a scanner for this --not my script--- For the "Up and Down Signals"

Code:
# E-Charts v2

declare upper;
input short_average = 5;
input medium_average = 10;
input long_average = 20;
input average_type = {default "SMA", "EMA"};
input show_vertical_line = no;
input show_bubble_labels = yes;

def MA1;
def MA2;
def MA3;
switch (average_type) {
case "SMA":
    MA1 = Average(close, short_average);
    MA2 = Average(close, medium_average);
    MA3 = Average(close, long_average);
case "EMA":
    MA1 = ExpAverage(close, short_average);
    MA2 = ExpAverage(close, medium_average);
    MA3 = ExpAverage(close, long_average);
}

# define e-signal and crossover point
def Eup = MA1 > MA2 && MA2 > MA3;
def Edn = MA1 < MA2 && MA2 < MA3;

def CrossUp = close > MA1 && Eup && !Eup[1];
def CrossDn = close < MA1 && Edn && !Edn[1];

# Define up and down signals
def higherHigh = close > Highest(max(open,close), 3)[1];
def lowerLow = close < Lowest(min(open,close), 3)[1];
def SignalUp = if (CrossUp && higherHigh)
    then 1
        else if    (CrossUp[1] && higherHigh && !higherHigh[1])
    then 1
        else if    (CrossUp[2] && higherHigh && !higherHigh[1] && !higherHigh[2])
    then 1
        else Double.NaN;
def SignalDn = if (CrossDn && lowerLow)
    then 1
        else if (CrossDn[1] && lowerLow && !lowerLow[1])
    then 1
        else if (CrossDn[2] && lowerLow && !lowerLow[1] && !lowerLow[2])
    then 1
        else Double.NaN;
       
# Plot the moving average lines
plot ln1 = MA1;
ln1.SetDefaultColor(CreateColor(145, 210, 144));
ln1.SetLineWeight(2);
plot ln2 = MA2;
ln2.SetDefaultColor(CreateColor(111, 183, 214));
ln2.SetLineWeight(2);
plot ln3 = MA3;
ln3.SetDefaultColor(CreateColor(249, 140, 182));
ln3.SetLineWeight(2);
   
# Draw vertical line to indicate call and put signals
AddVerticalLine(SignalUp && show_vertical_line, "Up", Color.UPTICK);
AddVerticalLine(SignalDn && show_vertical_line, "Down", Color.LIGHT_RED);

# Show Call / Put Signal in a Chart Bubble
AddChartBubble(SignalUp && show_bubble_labels, low - 0.3, "Up", Color.UPTICK, no);
AddChartBubble(SignalDn && show_bubble_labels, high + 0.3, "Dn", Color.LIGHT_RED);

# Add label for Eup or Edn
AddLabel(Eup, "E Up", Color.GREEN);
AddLabel(Edn, "E Dn", Color.RED);
 
@petey You can actually do that without any script. Here is an example of 9 EMA crossing above 20 EMA.

uNoyX9G.png


You can build this via the Scan tab in ThinkorSwim.
 

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