Auto Trade (ALGO) in TOS

one way to auto trade with TD Ameritrade is purchasing the Ninjatrader platform with a multi-broker version (about $1,300) and connect to TD, but you need to program in Ninjascript.
 
I've been running a pretty simple auto trader I wrote from an aimbot type scripting utility with TOS. I have labels setup to display when to buy and sell. When the script "sees" these labels it automatically clicks on buy or sell. I use this on MES futures contracts so I also have a section where the amount of contracts I want to buy is displayed in a binary format with a different colored label representing each "bit" of the binary code. The script is "watching" this area of the screen and translates the label colors and position back to a number and types that amount in for number of contracts in the active trader panel.

Basically, I have TOS and the script utility communicating visually through the chart since they cannot through code.

Been testing on paper trade since November of last year and switched to live trading on May 25th of this year. Running 24/6, starting with only $3600 running 2 contracts on a modified study from one of the forums on this site. Its been a slow start as fewer contracts provide less profit per tick. I am now up to being able to run 4 contracts after 74 trades and have not added any additional outside funding. It does currently buy and sell at "Market Price", but since the reaction time of the script is in milliseconds, I get very good fill prices. Always within 2 ticks of target, sometimes better than target, sometimes worse than target.

I do have it back tested to account for buying above target price by 3 ticks and exiting below target price by 3 ticks and also accounts for RT cost as it increases along with number of contracts bought. A back test of 180 days on a 39 min chart with a starting amount of $3600.00 gives 231 trades, 13 contracts, and an ending total of $20,708.00. This is a worst case scenario as every trade is recorded with the 3 tick (6 tick total) discrepancy. Back tests of the same time frame with better fill prices within the 1 to 2 tick range give results of 34 contracts with $42,600.00 and 53 contracts with $65,000.00.

Yes, this does run from 6 p.m. Sunday through 5 p.m. Friday every week, while I'm at work and while I'm sleeping. Best of all, its free.
 
Hi @Svanoy thanks for your post, I was trying something similar with keyboard Maestro and MacroRecorder but never got the screen to accurately capture the Buy and Sell signals consistently and then the issue of TOS repaint, now you see it now you don't issues. So I switched to Ninjatrader, if you can write it in TOS you generally can write it in NT. NT is not forgiving and backtests rarely represent reality. If you don't mind sharing your buy sell conditions, otherwise good luck with it all.
 
Hello @irishgold thank you for the encouragement. Sorry, it is a study from the premium indicator forum so I cannot share the code here. I veered off on a tangent in my previous post anyways. the script utility is AutoHotKey. It allows the ability to define certain parts of the screen to monitor and using a label to indicate buy or sell by color displayed means I only have to monitor a small static section instead of the entire screen. It also works with the computer monitor, mouse, and keyboard disconnected from the computer. It has not missed a single signal.

As far as repaint, the study I'm using does not repaint. Yes, back testing can be very misleading. Fortunately, with the modification to the study I'm using, I'm able to see the price at which to execute a trade at all times and will eventually move to running a buy stop limit order instead of buying at market. That with a standard trailing stop, makes plotting the buy and sell very easy. Market activity may change in the future and maybe not as many trade setups will present themselves or maybe more will. I keep my chart at 180 days as this is the longest amount of time that will still allow a 39 minute bar. As days pass and that May 25th live trade start date gets further away, the constant back testing of 180 days from present has matched exactly and the Win/Loss ratio has seen little change.

In regards to NT, part of this live run I started back in May, is to see if I can start with the bare minimum cost and investment, build capital, and eventually move up to /ES. Also, since not all trades are winning trades, the less it costs the less it concerns me to lose. Actually lost $180.00 dollars today, but it was money I didn't have a week ago. Low cost and a positive Win/Loss ratio allows me to worry about keeping the program running, and not what it is actually doing at the moment.
 
Last edited:
@Svanoy Thanks for the reply. Your idea about the label has helped me greatly. Since it is easier to set the screen area where the label prints. So I use something like
def AvgPrice = GetAveragePrice();
def LongOrder = Conditions and AvgPrice <=0; # Verify no open positions
def CloseLong = Conditions and AvgPrice > 0; # Verify you have an open position to close
AddLabel(yes, " " , if LongOrder then Color.Green else Color.White); # with a White background for the chart
AddLabel(yes, " " , if CloseLong then Color.RED else Color.White);
This creates an area that Macro Recorder (macrorecorder.com) can pick up, then once it sees the green label it moves to the next step. Keydown Alt press B Keyup Alt The hot key places an order to buy at market, then the program waits for Red label and does Alt S for sale. then the whole thing cycles again. Now I need to work on the conditions for the buy and sell to be profitable.
 
@irishgold That's pretty much it, I did have an issue with my script running too fast. Sometimes it wouldn't register the key press, you may have to put in a Sleep time during hot key entries of a millisecond or two. Also, you can use GetQuantity() to verify whether you have positions open or not. Greater than 0 or equals 0, use a label color to communicate this to Macro Recorder as well.

Can also use it to verify an order gets filled. Set a timer to count down after entering an order and if GetQuantiy() hasn't changed by the end of the timer, Cancel order.

If you need to communicate a number for shares/contracts or price, here is the code I wrote for mine. It only goes up to 127 as of now, but it could easily be expanded upon to go higher.

Code:
#Binary display of a number with labels
# Written by Svanoy

def size = 127; #This is the number being displayed with the labels

def onewhole = (RoundDown(size / 2, 0));
def oneremain = if (RoundDown(size / 2, 0)) - (size / 2) == 0 then 0 else 1;
def twowhole = (RoundDown(onewhole / 2, 0));
def tworemain = if (RoundDown(onewhole / 2, 0)) - (onewhole / 2) == 0 then 0 else 1;
def fourwhole = (RoundDown(twowhole / 2, 0));
def fourremain = if (RoundDown(twowhole / 2, 0)) - (twowhole / 2) == 0 then 0 else 1;
def eightwhole = (RoundDown(fourwhole / 2, 0));
def eightremain = if (RoundDown(fourwhole / 2, 0)) - (fourwhole / 2) == 0 then 0 else 1;
def sixteenwhole = (RoundDown(eightwhole / 2, 0));
def sixteenremain = if (RoundDown(eightwhole / 2, 0)) - (eightwhole / 2) == 0 then 0 else 1;
def thritytwowhole = (RoundDown(sixteenwhole / 2, 0));
def thirtytworemain = if (RoundDown(sixteenwhole / 2, 0)) - (sixteenwhole / 2) == 0 then 0 else 1;
def sixtyfourwhole = (RoundDown(thritytwowhole / 2, 0));
def sixtyfourremain = if (RoundDown(thritytwowhole / 2, 0)) - (thritytwowhole / 2) == 0 then 0 else 1;

addlabel(yes, "  ", If sixtyfourremain == 1 then color.LIGHT_GREEN else color.BLACK );
addlabel(yes, "  ", If thirtytworemain == 1 then color.LIME else color.BLACK );
addlabel(yes, "  ", If sixteenremain == 1 then color.CYAN else color.BLACK );
addlabel(yes, "  ", If eightremain == 1 then color.MAGENTA else color.BLACK );
addlabel(yes, "  ", If fourremain == 1 then color.PINK else color.BLACK );
addlabel(yes, "  ", If tworemain == 1 then color.PLUM else color.BLACK );
addlabel(yes, "  ", If oneremain == 1 then color.YELLOW else color.BLACK );
addlabel(yes, "# of contracts available to run: " + size, color.WHITE);
addlabel(yes, "Current # of contracts running: " + getquantity(),color.WHITE);

Here is how it would look displaying the number 127.
Untitled.jpg


You just translate it back to a number by associating the color of each label with its place holder and adding them together: 64+32+16+8+4+2+1=127
 
@treewind See post#2 for the answer to your question. Reading the whole thread with provide a more in-depth background
 
Last edited:
UUUUUHHHHHHH....great question?!?!?!? wow....would love to hear and see real feedback from this one!

Not over analyze the first sentence on their website, but why do they repeat themselves? " Can trade e-mini futures, indexes, stocks, futures, e-mini."

First orange flag for me! Typo?
 
@irishgold Here it is. You will of course have to change the ImageSearch and MouseClick parameters to meet your needs.
Code:
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
#SingleInstance [Forced]

CoordMode, Pixel, Screen
Delay = 30000

UpArrow = 0
DownArrow = 0
DoubleCheck = 0

PrevUpArrow = 0
PrevDownArrow = 0

Buy = 0
Sell = 0

OpenBuyOrder = 0
OpenSellOrder = 0

SixtyFour = 0
ThirtyTwo = 0
Sixteen = 0
Eight = 0
Four = 0
Two = 0
One = 0
Contracts = 0

#P:: Pause

#Z::
Goto, ContractCalc

Main:
ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w14 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\UpTrendLabel.tiff
If (ErrorLevel = 0)
{
OpenBuyOrder = 1
}
Else If (ErrorLevel = 1)
{
OpenBuyOrder = 0
}

ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w14 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\DownTrendLabel.tiff
If (ErrorLevel = 0)
{
OpenSellOrder = 1
}
Else If (ErrorLevel = 1)
{
OpenSellOrder = 0
}

Check:
Loop{

ImageSearch, FoundX, FoundY, 0, 0, 1900, 1050, *w23 *h23 C:\Users\Home\Desktop\AutoHotKey Images\TVOK.tiff
If (ErrorLevel = 0)
{
;MouseMove, (FoundX-22), (FoundY+11)
MouseClick, Left, (FoundX-22), (FoundY+11), 1, 0
MouseClick, Left, (FoundX-22), (FoundY+11), 1, 0
Sleep,5000
MouseClick, Left, 875, 30, 1, 0
}
Else If (ErrorLevel = 1)
{
}

ImageSearch, FoundX, FoundY, 0, 0, 1900, 1050, *w38 *h22 C:\Users\Home\Desktop\AutoHotKey Images\OK2.tiff
If (ErrorLevel = 0)
{
;MouseMove, 300, -190
;MouseClick, Left, (FoundX-22), (FoundY+11), 1, 0
;MouseClick, Left, (FoundX-22), (FoundY+11), 1, 0
;Sleep,5000
MouseClick, Left, 300, -190, 1, 0
}
Else If (ErrorLevel = 1)
{
}

ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w14 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\UpTrendLabel.tiff
If (ErrorLevel = 0 and OpenBuyOrder = 0)
{
UpArrow = 1
If PrevUpArrow != %UpArrow%
{
DoubleCheck = 1
PrevUpArrow := UpArrow
}
}
Else If (ErrorLevel = 1)
{
OpenBuyOrder = 0
UpArrow = 0
If PrevUpArrow != %UpArrow%
{
DoubleCheck = 1
PrevUpArrow := UpArrow
}
}

ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w14 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\DownTrendLabel.tiff
If (ErrorLevel = 0 and OpenSellOrder = 0)
{
DownArrow = 1
If PrevDownArrow != %DownArrow%
{
DoubleCheck = 1
PrevDownArrow := DownArrow
}
}

Else If (ErrorLevel = 1)
{
OpenSellOrder = 0
DownArrow = 0
If PrevDownArrow != %DownArrow%
{
DoubleCheck = 1
PrevDownArrow := DownArrow
}
}

If DoubleCheck = 1
{
;Sleep, Delay
DoubleCheck = 0
Goto, Check
}


If (UpArrow = 0 and DownArrow = 1)
{
If (Buy = 0 and Sell = 0)
{
;Click Sell Button
;Send +S
MouseClick, Left, 1580, 125, 1, 0
MouseClick, Left, 875, 30, 1, 0
Buy = 0
Sell = 1
;Sleep, Delay
}

Else If (Buy = 1 and Sell = 0)
{
;Click Flatten Button
MouseClick, Left, 1818, 125, 1, 0
MouseClick, Left, 875, 30, 1, 0

;Click Sell Button
;MouseClick, Left, 1580, 125, 1, 0
;MouseClick, Left, 875, 30, 1, 0
Buy = 0
Sell = 0
Goto, Wait
}

}
Else If (UpArrow = 1 and DownArrow = 0)
{
if (Buy = 0 and Sell = 0)
{
;Click Buy Button
;Send +B
MouseClick, Left, 1495, 125, 1, 0
MouseClick, Left, 875, 30, 1, 0
Buy = 1
Sell = 0
;Sleep, Delay
}

Else If (Buy = 0 and Sell = 1)
{
;Click Flatten Button
MouseClick, Left, 1818, 125, 1, 0
MouseClick, Left, 875, 30, 1, 0

;Click Buy Button
;MouseClick, Left, 1495, 125, 1, 0
;MouseClick, Left, 875, 30, 1, 0
Buy = 0
Sell = 0
Goto, Wait
}

}
Else If (UpArrow = 0 and DownArrow = 0)
{
If (Buy = 1 and Sell = 0)
{
;Click Sell Button
;Buy = 0
;Sell = 0
;Send +S
;MouseClick, Left, 1570, 125, 1, 0
;MouseClick, Left, 875, 30, 1, 0

;Click Flatten Button
;MouseClick, Left, 1818, 125, 1, 0
;MouseClick, Left, 875, 30, 1, 0
;Sleep, Delay
;Goto, ContractCalc
}

Else If (Buy = 0 and Sell = 1)
{
;Click Buy Button
;Buy = 0
;Sell = 0
;Send +B
;MouseClick, Left, 1495, 125, 1, 0
;MouseClick, Left, 875, 30, 1, 0

;Click Flatten Button
;MouseClick, Left, 1818, 125, 1, 0
;MouseClick, Left, 875, 30, 1, 0
;Sleep, Delay
;Goto, ContractCalc
}
}
Else If (UpArrow = 1 and DownArrow = 1)
{
If (Buy = 1 and Sell = 0)
{
;Click Sell Button
;Buy = 0
;Sell = 0
;Send +S
;MouseClick, Left, 1570, 135, 1, 0
;MouseClick, Left, 875, 30, 1, 0
;Sleep, Delay
;Goto, Main
}

Else If (Buy = 0 and Sell = 1)
{
;Click Buy Button
;Buy = 0
;Sell = 0
;Send +B
;MouseClick, Left, 1495, 135, 1, 0
;MouseClick, Left, 875, 30, 1, 0
;Sleep, Delay
;Goto, Main
}
}
}
Return

;#########################################################################################

Wait:

ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w8 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\PositionOpen.tiff
If (ErrorLevel = 0)
{
Goto, Wait
}
Else If (ErrorLevel = 1)
{
Goto, ContractCalc
}

;#########################################################################################

#C::
ContractCalc:
ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\64.tiff
If (ErrorLevel = 0)
{
SixtyFour = 64
}
Else
{
SixtyFour = 0
}

ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\32.tiff
If (ErrorLevel = 0)
{
ThirtyTwo = 32
}
Else
{
ThirtyTwo = 0
}

ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\16.tiff
If (ErrorLevel = 0)
{
Sixteen = 16
}
Else
{
Sixteen = 0
}

ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\8.tiff
If (ErrorLevel = 0)
{
Eight = 8
}
Else
{
Eight = 0
}

ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\4.tiff
If (ErrorLevel = 0)
{
Four = 4
}
Else
{
Four = 0
}

ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\2.tiff
If (ErrorLevel = 0)
{
Two = 2
}
Else
{
Two = 0
}

ImageSearch, FoundX, FoundY, 0, 500, 125, 1000, *w8 *h17 C:\Users\Home\Desktop\AutoHotKey Images\1.tiff
If (ErrorLevel = 0)
{
One = 1
}
Else
{
One = 0
}

Contracts := SixtyFour + ThirtyTwo + Sixteen + Eight + Four + Two + One
;MsgBox, 0, , %Contracts%, 5
MouseClick, Left, 1510, 168, 1, 0

count = 0
Loop{
Send {Delete}
count := count + 1
sleep, 10
} Until count = 5

SendInput, %Contracts%
MouseClick, Left, 750, 250, 1, 0
MouseClick, Left, 875, 30, 1, 0
Goto, Check

;################################################################################################

#B::
Buy = 1
Sell = 0
Goto, ContractCalc

;#################################################################################################

#S::
Buy = 0
Sell = 1
Goto, ContractCalc
 
Last edited by a moderator:
@Svanoy Question on script TVOK.tiff and OK2.tiff what do they represent? are they just OK buttons that might popup, like the thinkorswim is running slow type message? I got my label images all working. I'm using a different scheme just using the hotkeys AltB and Alt S and AltF for now. I also have about four exit images Downtrend, exit on ASI signal, exit on Profit target, and exit on stoploss, I hope it works, we will see.
Having trouble with no activation of either hot key being sent or tried with mouseclick with coordinate I used from Window Spy.
even created a simple program to do a mouseclick and it does not work with thinkorswim in focus. I created simple mouse click to open Chrome from desktop taskbar and it works.
 
@Svanoy Yes I changed all AutoHotKey.exe under Properties- Compatibility, to Run As Administrator. As I was only wanting to go Long at least for now, I had to change some of the code not to Sell if DownArrow and Buy = 0, It is a learning curve and I'm sure your code is a reflection of after many efforts and tweaks to get it right. I added some code to write to a csv file the datetime and whether it was Buy or Flatten, it could be useful even if I don't actually trade it can tell me the code is working. I changed all my other labels to Red for the time being so if it hits stoploss, profit target, or alternate exit signal the same effect to exit the trade will take place. Thanks again.
 

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