Moving Average Master Strategy for ThinkOrSwim

dap711

Active member
Hi All!

I have spent hundreds of hours developing the "Moving Average Master" strategy. Note: This strategy is best used on the lower time frames. Begin by selecting a time frame you want to trade and apply this strategy and the floating P/L study to the chart. You should see a BUNCH of trades on the chart! Right click on one of them and select "Edit Strategy" (It's important to do it from the chart! This way you can apply the new settings without having to close the edit window and you can instantly see the results of the change.)

Video about how to optimize this (or any) strategy: https://drive.google.com/file/d/1UJsCk5a2yE8kAREz429Oob0rU7R9DER_/view?usp=sharing

Video about using Marco Recorder to auto trade. https://drive.google.com/file/d/1uq1IMBaUw96mFSAgL02d1LQcJT_3V8W_/view?usp=sharing

Video of Macro Recorder in action trading paper: https://drive.google.com/file/d/1aNj1nqizMi54Tu6LuDlmGZbDfQbQU5HI/view?usp=sharing

Moving Average Master Strategy shared link: https://tos.mx/vL2BUhC

Latest code for Moving Average Master:
Ruby:
# Author - dap711 
# FloatingPL by MerryDay

#1. Set the Trend MA type, price, and length. We only take buys if price is above the trend line and sells below it.
#2. Adjust the MA lengths to achieve the best profit from the floating P/L.
#3. You can now turn off the "ShowStrategyPositions"

#Create a new strategy and copy/paste this code into it.

#Charting
input ShowStategyPositions = yes;
#Hint ShowStategyPositions: Plot the historical trades on the chart. Needed to calculate the floating P/L.
input ShowCalculatedBarColor = yes;
#Hint ShowCalculatedBarColor: Change the color of the chart candles to match the strategy.
input ShowMovingAverages = no;
#Hint ShowMovingAverages: Show the moving averages on the chart.
input ShowFloating_pl_Labels = yes;
#Hint ShowFloating_pl_Labels: Show the floatingPL labels. "show stategy positions" must be set to "yes".

#Moving averages
input MA_AverageType = AverageType.HULL;
input MA_Price = close;
input MA1_Length = 8;
input MA2_Length = 21;
input UseMA3 = yes;
input MA3_Length = 33;
input UseMA4 = no;
input MA4_Length = 54;

#Trading Times
input RiskAmount = 1000;
#Hint RiskAmount: This should be between 1-5% of your total account amount. (Recommend 1% to start with) 
input UseTradingTimes = no;
input FirstStartTradingEST = 0930;
input FirstStopTradingEST = 1200;
input SecondStartTradingEST = 1159;
input SecondStopTradingEST = 1557;
def OkToTrade = if UseTradingTimes then if(secondsFromTime(FirstStartTradingEST) >= 0 and
                secondsFromTime(FirstStopTradingEST) <= 0) or
                (secondsFromTime(SecondStartTradingEST) >= 0 and
                secondsFromTime(SecondStopTradingEST) <= 0) then yes else no else yes;


#Plots
plot MA1 = MovingAverage(MA_AverageType,MA_Price,MA1_Length);
MA1.SetHiding(!ShowMovingAverages);
MA1.SetStyle(Curve.SHORT_DASH);
MA1.SetLineWeight(1);
MA1.SetDefaultColor(Color.GRAY);

plot MA2 = MovingAverage(MA_AverageType,MA_Price,MA2_Length);
MA2.SetHiding(!ShowMovingAverages);
MA2.SetStyle(Curve.SHORT_DASH);
MA2.SetLineWeight(1);
MA2.SetDefaultColor(Color.DARK_GRAY);

plot MA3 = MovingAverage(MA_AverageType,MA_Price,MA3_Length);
MA3.SetHiding(!ShowMovingAverages or !UseMA3);
MA3.SetStyle(Curve.SHORT_DASH);
MA3.SetLineWeight(1);
MA3.SetDefaultColor(Color.DARK_GREEN);

plot MA4 = MovingAverage(MA_AverageType,MA_Price,MA4_Length);
MA4.SetHiding(!ShowMovingAverages or !UseMA4);
MA4.SetStyle(Curve.SHORT_DASH);
MA4.SetLineWeight(1);
MA4.SetDefaultColor(Color.DARK_ORANGE);

#Trading
def Buy = if MA1>MA2 and close>MA2 and
          (if UseMA3 then (if MA2>MA3 then yes else no) else yes) and
          (if UseMA4 then (if MA3>MA4 then yes else no) else yes)
          then yes else no;
 
def Sell = if MA1<MA2 and close<MA2 and
          (if UseMA3 then (if MA2<MA3 then yes else no) else yes) and
          (if UseMA4 then (if MA3<MA4 then yes else no) else yes)
          then yes else no;

AddOrder(OrderType.BUY_TO_OPEN, OkToTrade and Buy and ShowStategyPositions,   open[-1], RiskAmount/close, Color.CYAN, Color.CYAN, "EA");
AddOrder(OrderType.SELL_TO_CLOSE, (!OkToTrade or !Buy) and ShowStategyPositions, open[-1], RiskAmount/close, Color.CYAN, Color.CYAN,"");
AddOrder(OrderType.SELL_TO_OPEN, OkToTrade and Sell and ShowStategyPositions,  open[-1], RiskAmount/close, Color.RED, Color.RED,"EA");
AddOrder(OrderType.BUY_TO_CLOSE, (!OkToTrade or !Sell) and ShowStategyPositions, open[-1], RiskAmount/close, Color.RED,Color.RED, "");

#Labels
AddLabel(yes, " Buy ", if ShowCalculatedBarColor and OkToTrade and Buy  then Color.Cyan else Color.White);
AddLabel(yes, " Sell ", if ShowCalculatedBarColor and OkToTrade and Sell then Color.Red else Color.White);
AddLabel(yes, " Close ", if ShowCalculatedBarColor and !OkToTrade and !Sell and !Buy then Color.Yellow else Color.White);

AddLabel(ShowMovingAverages,"MA1="+MA1_Length,Color.GRAY);
AddLabel(ShowMovingAverages,"MA2="+MA2_Length,Color.DARK_GRAY);
AddLabel(ShowMovingAverages and UseMA3,"MA3="+MA3_Length,Color.DARK_GREEN);
AddLabel(ShowMovingAverages and UseMA4,"MA4="+MA4_Length,Color.DARK_ORANGE);

#//FloatingProfitLoss Labels
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;
}
def fplTargetWinLoss = .50;
def fplTargetWinRate = 1;
input HidePrices = no;
#Hint HidePrices: Useful to see posistions without the candles on the chart. Must have "show strategy positions" set to yes.
def fplHideFPL = yes;
def targetWinLoss = fplTargetWinLoss;
def targetWinRate = fplTargetWinRate;
def nan = Double.NaN;
def bn = if !IsNaN(close) and !IsNaN(close[1]) and !IsNaN(close[-1]) then BarNumber() else bn[1];
HidePricePlot(hidePrices);
def FPL = FPL();

# 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 = if winCount == 0 and lossCount == 0 then 0 else if lossCount == 0 then 1 else winCount / lossCount;
def winLossRatio = winCount / entryCount;
def avgReturn = TotalSum(entryFPLAll) / entryCount;
def avgWin = TotalSum(entryFPLWins) / winCount;
def avgLoss = TotalSum(entryFPLLosses) / lossCount;

#Floating P/L labels
AddLabel(ShowFloating_pl_Labels and ShowStategyPositions,"Total Trades: " + entryCount + "  ", Color.Cyan);
AddLabel(ShowFloating_pl_Labels and ShowStategyPositions,"WinCount: " + winCount + " | LossCount: " + lossCount , color = if winRate >= targetWinRate then Color.Green else Color.Red);
AddLabel(ShowFloating_pl_Labels and ShowStategyPositions,"W/L: " + AsPercent(winLossRatio) + " ", color = if winLossRatio > targetWinLoss then Color.Green else Color.Red);
AddLabel(ShowFloating_pl_Labels and ShowStategyPositions,"AvgWin: "+AsDollars(avgWin)+" | AvgLoss: "+AsDollars(avgLoss),color = if TotalSum(entryFPLAll) >= 0 then color.Green else Color.Red);
AddLabel(ShowFloating_pl_Labels and ShowStategyPositions,"Total Profit: " + AsDollars(TotalSum(entryFPLAll)), color = if TotalSum(entryFPLAll) > 0 then Color.Green else Color.Red);

#Candle Colors
def Candle_Plot = if Buy then 1 else if Sell then -1 else 0;
AssignPriceColor(if ShowCalculatedBarColor then if Candle_Plot > 0 then Color.CYAN
                 else if Candle_Plot <0 then Color.RED else Color.GRAY
                 else Color.CURRENT);


#“Make everything as simple as possible, but not simpler.” Albert Einstein.
 
Last edited:

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

I didn't have much time when I first posted the strategy to explain how I use it. I take trades using an application called Macro Recorder to generate the key stokes to buy and sell. Moving Average Master will generate a label to either buy, sell, or close the trades. Marco Recorder monitors for the color of the labels and then generates the key strokes for the trades. I have been running this system for several months now and it hasn't missed a trade yet! :)

I only trade one stock at a time that I pick from my scan in the morning. I look for something that has high relative volume and a price around $5-$25. I then optimize the strategy for that stock using the floating P/L study and adjusting the settings. I then let'r rip for the day while I go about my business. I'm sure this system isn't for everyone, but if you're interested in ALGO trading, we share the same!

ThinkOrSwim does not feature auto trading. But there are ways around this limitation with a little imagination and by using programs like Macro Recorder. I'm successfully trading my ALGO automatically without using the API. There is another thread that shows how another program called Auto Hot Key (AHK) has done the same. Read here ..

Here is my Macro Recorder script ..

3hzKlBb.jpg
 
Last edited:
I didn't have much time when I first posted the strategy to explain how I use it. I use a TDA API to take trades using an application called Macro Recorder to generate the key stokes to buy and sell. Moving Average Master will generate a label to either buy, sell, or close the trades. Marco Recorder monitors for the color of the labels and then generates the key strokes for the trades. I have been running this system for several months now and it hasn't missed a trade yet! :)

I only trade one stock at a time that I pick from my scan in the morning. I look for something that has high relative volume and a price around $5-$25. I then optimize the strategy for that stock using the floating P/L study and adjusting the settings. I then let'r rip for the day while I go about my business. I'm sure this system isn't for everyone, but if you're interested in ALGO trading, we share the same!

ThinkOrSwim does not feature auto trading. But there are ways around this limitation with a little imagination and by using programs like Macro Recorder. I'm successfully trading my ALGO automatically without using the API. There is another thread that shows how another program called Auto Key has done the same. Read here ..

Here is my Macro Recorder script ..

3hzKlBb.jpg
Can you explain a bit more about your "Macro Recorder script"? Thanks
 
Hi All!

I have spent hundreds of hours developing the "Moving Average Master" strategy. Note: This strategy is best used on the lower time frames. Begin by selecting a time frame you want to trade and apply this strategy and the floating P/L study to the chart. You should see a BUNCH of trades on the chart! Right click on one of them and select "Edit Strategy" (It's important to do it from the chart! This way you can apply the new settings without having to close the edit window and you can instantly see the results of the change to the settings.)

Code:
#1. Set the Trend MA type, price, and length. We only take buys if price is above the trend line and sells below it.
#2. Adjust the MA length to achieve the best profit from the floating P/L.
#3. Adjust the MA displacement for the highest profit.
#4. Repeat steps 2 and 3 until you are satisfied with the results.
#5. Adjust the smoothing up or down and repeat steps 2, 3 and 4. Now you see where this is going! LOL
input BackTestTradeSize = 1;
input ShowBackTestPositions = yes;
input TrendAvgType = AverageType.SIMPLE;
input TrendPrice = OHLC4;
input TrendLength = 200;
input UseVolumeAsFilter = yes;
input MAType = AverageType.HULL;
input MAPrice = Open;
input MALength = 3;
input MADisplace = 3;
input UseSmoothing = yes;
input SmoothingType = AverageType.WEIGHTED;
input SmoothingLength = 5;


input AlertOnSignal = no;
input ShowAutoKeyLabels = yes; #(I use Macro Recorder to auto trade. Ask me about my setup by emailing me at the above address!)

#Average the volume and only open trades when volume is higher than the average.
def VolStrength = lg(volume[1]) - lg(SimpleMovingAvg(volume[1], 2000));

def Value = MovingAverage(MAType, MAPrice, MALength*100) -  MovingAverage(MAType, MAPrice, MALength*100)[MADisplace];
def diff;
if UseSmoothing then {diff  = MovingAverage(SmoothingType, Value, SmoothingLength);} else {diff = Value;}

plot MA = MovingAverage(TrendAvgType, TrendPrice, TrendLength);
MA.DefineColor("Up", GetColor(1));
MA.DefineColor("Down", GetColor(0));
MA.AssignValueColor(if MA > MA[1] then MA.color("Up") else MA.color("Down"));

#Open the orders on the chart for back testing and optimizing the settings
AddOrder(OrderType.BUY_TO_OPEN, diff > diff[1] and low > MA and (if UseVolumeAsFilter then VolStrength>0 else yes) and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.CYAN, Color.CYAN, "");
AddOrder(OrderType.SELL_TO_CLOSE, ( diff < diff[1] or close < MA ) and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.CYAN,Color.CYAN, "");
AddOrder(OrderType.SELL_TO_OPEN, diff < diff[1] and high < MA and (if UseVolumeAsFilter then VolStrength>0 else yes) and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.RED, Color.RED,"");
AddOrder(OrderType.BUY_TO_CLOSE, ( diff > diff[1] or close > MA )  and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.RED, Color.RED,"");

#Add the auto trade labels
def OpenOrders = GetQuantity();
AddLabel(diff[1] > diff[2] and low > MA and OpenOrders < 1 and (if UseVolumeAsFilter then VolStrength>0 else yes),  "     BUY      ", CreateColor(153, 255, 153));
AddLabel(( diff[1] < diff[2] or close < MA ) and OpenOrders > 0, "     CLOSE     ", CreateColor(102, 0, 0));
AddLabel(diff[1] < diff[2] and high < MA and OpenOrders < 1 and (if UseVolumeAsFilter then VolStrength>0 else yes), "     SELL     ", CreateColor(255, 102, 102));
AddLabel(( diff[1] > diff[2] or close > MA ) and OpenOrders < 0 , "     CLOSE     ", CreateColor(102, 0, 0));

#Sound the bell. (If alerts are turn on)
Alert(diff[1] > diff[2] and low > MA and OpenOrders < 1 and AlertOnSignal, "Buy Open Signal", Alert.Bar, Sound.Ding);
Alert( ( diff < diff[1] or close < MA ) and OpenOrders > 0 and OpenOrders != 0 and AlertOnSignal, "Buy Close Signal", Alert.Bar, Sound.Bell);
Alert(diff[1] < diff[2] and high < MA and OpenOrders > -1 and AlertOnSignal, "Sell Open Signal", Alert.Bar, Sound.Ding);
Alert( ( diff > diff[1] or close > MA ) and OpenOrders > 0 and OpenOrders != 0 and AlertOnSignal, "Sell Close Signal", Alert.Bar, Sound.Bell);

AddLabel(UseVolumeAsFilter, if VolStrength > 0 then "   Trading allowed. Volume Strength: " + (VolStrength) + "  "  else "   Trading isn't allowed - Volume Strength: " + (VolStrength) + "  " , if (VolStrength < 0) then Color.RED else Color.Red);
[code]
Does this repaint?
 
Can you explain a bit more about your "Macro Recorder script"? Thanks
Be happy to .. but first, let's do some house cleaning. The script above had some tests in it, and I needed to do a correction.
Updated Code can be found in the top post.

Now, about the strategy and Marco Recorder .. the strategy can be used without Marco Recorder.. just buy when the "Buy" label appears and sell when "Sell" appears .. simple enough! I like to trade the lower time frames (one, three and five minutes) but I don't like to sit in front of a monitor waiting on the signals. I have a life that needs living. :) So, I use the color on the labels to trigger a response from Macro Recorder to generate the hot key strokes in ToS automatically. The screenshot I posted is what I use to monitor ToS. It won't help you unless you are using Macro Recorder. If you are, it will save you a bunch of time creating one from scratch.

I think one of the greatest failures of ToS is it doesn't have a way to optimize the settings of a strategy. The only way I have found to optimize, is to sit there and change each setting until you get the best performance. Please tell me if there is better way! I'm kinda new to ToS, as I have been working with MetaTrader for the past 10 years.
 
Last edited by a moderator:
Does this repaint?
No, it does not repaint.

Repaint .. what a subject .. I've noticed that almost all the MTF indicators in ToS are not written correctly. Bold statement right? There is a simple way write MTF code that will overcome repainting. Let's take a moving average for example. A 100 period moving average on the one minute chart is the same as a 20 period moving average on the 5 minute chart (100 divided by 5 min = 20 .. try it if you don't believe me!), so to show the 20 period five minute on a one minute chart, just do a 100 period and the indicator won't repaint! Couldn't be easier! You can apply the same rule to almost any indicator based on price movement and some that aren't. There are other ways to overcome repainting, but those are my trade secrets .. LOL

mod note:
On a daily chart a 50 SMA would equal a 10 SMA on a weekly chart
On a 1 Min Chart a 50 SMA would equal a 10 SMA on a 5 Min Chart
On a 1 Min Chart a 300 SMA would equal a 10 SMA on a Hourly Chart
On a 1 Min Chart a 1950 SMA would equal a 10 SMA on a Daily Chart
 
Last edited:
Cool! I'll take a look at this tonight. What settings/timeframe do you typically use @dap711 ? Thanks for sharing!!

It all depends on the stock I've chosen to trade for that day. I have to optimize the settings each day. That is why I've gone into detail about how to optimize.
 
I might also mention a little about trading this with paper money. When you trade paper using Macro Recorder, your open trades are delayed several minutes and the strategy relies heavily on the GetQuantity() (Tells how many orders you are trading) function. Without knowing if an order has been placed, The label and alert will continue to be generated. If using Marco Recorder, it will keep sending the keystrokes to buy and sell!
 
Updated Version as of: 1/7/2023
Hi All!

I have spent hundreds of hours developing the "Moving Average Master" strategy. Note: This strategy is best used on the lower time frames. Begin by selecting a time frame you want to trade and apply this strategy and the floating P/L study to the chart. You should see a BUNCH of trades on the chart! Right click on one of them and select "Edit Strategy" (It's important to do it from the chart! This way you can apply the new settings without having to close the edit window and you can instantly see the results of the change to the settings.)

Here is the updated code:
Ruby:
#1. Set the Trend MA type, price, and length. We only take buys if price is above the trend line and sells below it.
#2. Adjust the MA length to achieve the best profit from the floating P/L.
#3. Adjust the MA displacement for the highest profit.
#4. Repeat steps 2 and 3 until you are satisfied with the results.
#5. Adjust the smoothing up or down and repeat steps 2, 3 and 4. Now you see where this is going! LOL
#6. Share you insights for the best time frames and settings to help everyone!


input BackTestTradeSize = 1;
input ShowBackTestPositions = yes;
input TrendPeriod = AggregationPeriod.FIVE_MIN;
input TrendAvgType = AverageType.SIMPLE;
input TrendPrice = fundamentalType.OHLC4;
input TrendLength = 200;
input UseVolumeAsFilter = yes;
input MAType = AverageType.HULL;
input MAPrice = Open;
input MALength = 3;
input MADisplace = 3;
input UseSmoothing = yes;
input SmoothingType = AverageType.WEIGHTED;
input SmoothingLength = 5;
input AlertOnSignal = no;
input ShowAutoKeyLabels = yes; #(I use Macro Recorder to auto trade. Ask me about the setup at [email protected])

#Average the volume and only open trades when volume is higher than the average.
def VolStrength = lg(volume[1]) - lg(SimpleMovingAvg(volume[1], 2000));
def Value = MovingAverage(MAType, MAPrice, MALength*100) -  MovingAverage(MAType, MAPrice, MALength*100)[MADisplace];
def diff;
if UseSmoothing then {diff  = MovingAverage(SmoothingType, Value, SmoothingLength);} else {diff = Value;}
plot MA = MovingAverage(TrendAvgType, fundamental(TrendPrice,period=TrendPeriod), TrendLength);
MA.DefineColor("Up", GetColor(1));
MA.DefineColor("Down", GetColor(0));
MA.AssignValueColor(if MA > MA[1] then MA.color("Up") else MA.color("Down"));

#Open the orders on the chart for back testing and optimizing the settings
AddOrder(OrderType.BUY_TO_OPEN, diff > diff[1] and low > MA and (if UseVolumeAsFilter then VolStrength>0 else yes) and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.CYAN, Color.CYAN, "");
AddOrder(OrderType.SELL_TO_CLOSE, ( diff < diff[1] or close < MA ) and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.CYAN,Color.CYAN, "");
AddOrder(OrderType.SELL_TO_OPEN, diff < diff[1] and high < MA and (if UseVolumeAsFilter then VolStrength>0 else yes) and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.RED, Color.RED,"");
AddOrder(OrderType.BUY_TO_CLOSE, ( diff > diff[1] or close > MA )  and ShowBackTestPositions, open[-1], BackTestTradeSize, Color.RED, Color.RED,"");

#Add the auto trade labels
def OpenOrders = GetQuantity();
AddLabel(ShowAutoKeyLabels and diff[1] > diff[2] and low > MA and OpenOrders < 1 and (if UseVolumeAsFilter then VolStrength>0 else yes),  "     BUY      ", CreateColor(153, 255, 153));
AddLabel(ShowAutoKeyLabels and ( diff[1] < diff[2] or close < MA ) and OpenOrders > 0, "     CLOSE     ", CreateColor(102, 0, 0));
AddLabel(ShowAutoKeyLabels and diff[1] < diff[2] and high < MA and OpenOrders < 1 and (if UseVolumeAsFilter then VolStrength>0 else yes), "     SELL     ", CreateColor(255, 102, 102));
AddLabel(ShowAutoKeyLabels and ( diff[1] > diff[2] or close > MA ) and OpenOrders < 0 , "     CLOSE     ", CreateColor(102, 0, 0));

#Sound the bell. (If alerts are turn on)
Alert(diff[1] > diff[2] and low > MA and OpenOrders < 1 and AlertOnSignal, "Buy Open Signal", Alert.Bar, Sound.Ding);
Alert( ( diff[1] < diff[2] or close < MA ) and OpenOrders > 0 and AlertOnSignal, "Buy Close Signal", Alert.Bar, Sound.Bell);
Alert(diff[1] < diff[2] and high < MA and OpenOrders > -1 and AlertOnSignal, "Sell Open Signal", Alert.Bar, Sound.Ding);
Alert( ( diff[1] > diff[2] or close > MA ) and OpenOrders < 0 and AlertOnSignal, "Sell Close Signal", Alert.Bar, Sound.Bell);

AddLabel(UseVolumeAsFilter, if VolStrength > 0 then "   Trading allowed. Volume Strength: " + (VolStrength) + "  "  else "   Trading isn't allowed - Volume Strength: " + (VolStrength) + "  " , if (VolStrength < 0) then Color.RED else Color.Red);

Do you have a sharable link?
 
I didn't have much time when I first posted the strategy to explain how I use it. I use a TDA API to take trades using an application called Macro Recorder to generate the key stokes to buy and sell. Moving Average Master will generate a label to either buy, sell, or close the trades. Marco Recorder monitors for the color of the labels and then generates the key strokes for the trades. I have been running this system for several months now and it hasn't missed a trade yet! :)

I only trade one stock at a time that I pick from my scan in the morning. I look for something that has high relative volume and a price around $5-$25. I then optimize the strategy for that stock using the floating P/L study and adjusting the settings. I then let'r rip for the day while I go about my business. I'm sure this system isn't for everyone, but if you're interested in ALGO trading, we share the same!

ThinkOrSwim does not feature auto trading. But there are ways around this limitation with a little imagination and by using programs like Macro Recorder. I'm successfully trading my ALGO automatically without using the API. There is another thread that shows how another program called Auto Key has done the same. Read here ..

Here is my Macro Recorder script ..

3hzKlBb.jpg
What timeframe do you use with best results?
 
What timeframe do you use with best results?

That depends on what the chart looks like. If there is a huge gap, one minute, if it's a slow trend up or down, three minute. I'm day trading high relative volume stocks, but there is no reason it won't work on a 5 or 15 minute TSLA or META. I wouldn't go much higher than 15 minute. Seems like the market has been in whipsaw mode lately. That's why I like the one minute. If a trade goes against me, I like to know up front so the auto trader can respond quicker. But that is a double-sided sword, as getting out of a trade to soon cuts the profit. So, what I'm trying to say .. how do you want to trade it? It's up to your risk factor .. This strategy has the ability to be profitable, but it's like any other tool, it has to be mastered and understood. The settings give you ever option under the sun when using a moving average to trade. It even provides a volume filter if wanted. I'm experimenting with VWAP as an additional filter .. next release .. if it works out.
 
Be happy to .. but first, let's do some house cleaning. The script above had some tests in it, and I needed to do a correction.
Updated Code can be found in the top post.

Now, about the strategy and Marco Recorder .. the strategy can be used without Marco Recorder.. just buy when the "Buy" label appears and sell when "Sell" appears .. simple enough! I like to trade the lower time frames (one, three and five minutes) but I don't like to sit in front of a monitor waiting on the signals. I have a life that needs living. :) So, I use the color on the labels to trigger a response from Macro Recorder to generate the hot key strokes in ToS automatically. The screenshot I posted is what I use to monitor ToS. It won't help you unless you are using Macro Recorder. If you are, it will save you a bunch of time creating one from scratch.

I think one of the greatest failures of ToS is it doesn't have a way to optimize the settings of a strategy. The only way I have found to optimize, is to sit there and change each setting until you get the best performance. Please tell me if there is better way! I'm kinda new to ToS, as I have been working with MetaTrader for the past 10 years.
Thanks for your reply. Is it possible for you to share the macro record file (.mrf) files? I just downloaded the program and want to create a script like you.
 
That depends on what the chart looks like. If there is a huge gap, one minute, if it's a slow trend up or down, three minute. I'm day trading high relative volume stocks, but there is no reason it won't work on a 5 or 15 minute TSLA or META. I wouldn't go much higher than 15 minute. Seems like the market has been in whipsaw mode lately. That's why I like the one minute. If a trade goes against me, I like to know up front so the auto trader can respond quicker. But that is a double-sided sword, as getting out of a trade to soon cuts the profit. So, what I'm trying to say .. how do you want to trade it? It's up to your risk factor .. This strategy has the ability to be profitable, but it's like any other tool, it has to be mastered and understood. The settings give you ever option under the sun when using a moving average to trade. It even provides a volume filter if wanted. I'm experimenting with VWAP as an additional filter .. next release .. if it works out.
Thank you for sharing. I typically use a 1m chart for entry and exit and mainly trade high liquid option stocks. I tested this strat using the 1m and did not get good results with the FloatingPL. I did try changing many of the settings options and still wasn't able to produce good results however, I did get pretty good results with a 5m chart. I tested MSFT,AAPL,TSLA, and NFLX. Do you mind sharing your 1m chart settings within this Strat?
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
427 Online
Create Post

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