Auto Trade (ALGO) in TOS

@aCuddlyTurtle
if you were in a long position then it would be: If (ErrorLevel = 0 and Buy = 1) then Buy = 0.
if you were in a short position then it would be If (ErrorLevel = 0 and Sell = 1) then Sell = 0.

Issues: You have two labels, they will never be both on so a white label will always be on screen.

So really you have to also add a fourth image search and change one the the labels to a different color when off.
 
@Svanoy I think I got it, yeah I now have 4 image searches and 4 colors. so for example if (ErrorLevel =0 and Buy =1) what would i do to just reset?
I thought I had it figured out but if buy or sell =1 I dont want it to buy or sell i just want it to reset and wait.
 
@aCuddlyTurtle
That's what you have to understand about programming, the buy and sell variables in the script are what is telling the script to wait.
The variable track the trade state.
Now if you are sure that your buy or sell labels won't "turn on" again while in a trade (except in the case of reversing a trade) then just set which ever variable is 1 to 0. (ex: in my last post). At that point AHK is just waiting for a label to change color again.
 
@Svanoy This is what I added.
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

Buy = 0
Sell = 0
Delay = 10000

^0:: Pause
^9::
Loop{

;Watch for Buy Signal
ImageSearch, FoundX, FoundY, 27, 230, 161, 269, *w20 *h20 *TransBlack *1 C:\Users\bqe27\OneDrive\Desktop\AutoHotKey Images\BuyLabel.tiff

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + b key combo.
    If (ErrorLevel = 0 and Buy = 0)
        {
        MouseClick, Left, 1747, 248, 1, 0
        delay = 10
        Send ^{f}
        delay = 10
        Send ^{b}
        Buy = 1
        Sell = 0
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }
;Watch for Sell Signal
ImageSearch, FoundX, FoundY, 27, 230, 161, 269, *w20 *h20 *TransBlack *1 C:\Users\bqe27\OneDrive\Desktop\AutoHotKey Images\SellLabel.tiff

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + s key combo.
    If (ErrorLevel = 0 and Sell = 0)
        {
        MouseClick, Left, 1747, 248, 1, 0
        delay = 10
        Send ^{f}
        delay = 10
        Send ^{s}
        Buy = 0
        Sell = 1
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }
;Watch for Yellow label
ImageSearch, FoundX, FoundY, 27, 230, 161, 269, *w20 *h20 *TransBlack *1 C:\Users\bqe27\OneDrive\Desktop\AutoHotKey Images\YellowLabel.tiff

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + s key combo.
    If (ErrorLevel = 0 and Buy = 1)
        {
        Buy = 0
        Sell = 0
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }
;Watch for Magenta label
ImageSearch, FoundX, FoundY, 27, 230, 161, 269, *w20 *h20 *TransBlack *1 C:\Users\bqe27\OneDrive\Desktop\AutoHotKey Images\MagentaLabel.tiff

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + s key combo.
    If (ErrorLevel = 0 and Sell = 1)
        {
        Buy = 0
        Sell = 0
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }

}Return
 
Is it possible, to have a strategy open and close LIVE trades? Strategies are mainly used for backtesting ideas, logic, etc. My understanding. I would like to open actual trades in a LIVE ToS account. The main logic and code is already written, looking to enhance the strategy by actually open and close trades in a LIVE ToS account.

I read about an API that connects code from Ninjatrader and executes actual orders in ToS. Is anyone familiar with this approach?

Thank you for your time and consideration on this matter.
 
Last edited by a moderator:
You will likely be directed either here:

https://usethinkscript.com/threads/auto-trade-algo-in-tos.7546/
This first thread addresses a technique which reads visual signals from the ToS application itself using AutoHotKey, a legacy windows-based scripting language. This system is very much 'DIY' and there is not much info on the web regarding its usage with trading platforms, but AHK is easy, requiring little programming knowledge.

Or here:

https://github.com/TreyThomas93/python-trading-bot-with-thinkorswim

This second is a more involved way of routing alerts to an external email address which a Python-based bot scrapes, routes to an online database, then inputs orders via ToS API which requires registering for a developer account and inputting access keys intermittently. This system has a Discord with programmers who are willing to help.
 
For those running VM.......Running my script on VM while attended works fine. But while unattended it does not carry out any mouse functions. What setup am I missing to have this script running 24/7.
 
MouseClick works fast enough for me. The default cursor speed is 0 (fastest) which is pretty much instantaneous.
If you open up your script while it is running you can observe it in real time.
057: PixelGetColor,positionLabel%loopCount%,arrayPosX[loopCount],arrayPosY[loopCount],RGB (0.03)
This pixelGetColor command took 0.03 seconds to check if I had an open position. The mouse click adds no time at all if instructed to flatten.
 
Mouse move and click then move away and click on chart to prevent accidental click on button incase something bumps against the mouse.
 
@Svanoy @Jonessw1 Ok perfect, Thanks guys. That's what I'm going to use is mouse click to buy then click away. My keybinds were having issues because while testing and adjusting the script in ahk everytime I would minimize tos then open it again I would have to deal with a "ok button box" when trying to buy/sell with the keybind for the first time. also @Svanoy how exactly does your script deal with TeamViewer? does it recognize it and then click back on tos? Im testing my pc with teamviewer and so far it doesn't seem to get in the way when I open and close it.
 
@aCuddlyTurtle Sometimes after disconnecting Team Viewer will display a pop up box asking for feedback or something like that. All I did was take a snippet of the OK button on the pop up and add that in as an Image Search in the same loop as the Buy/Sell loop Image Search loop. If AHK detects it then it just clicks on the OK button and then clicks back on the chart in the same place that it goes after clicking the buy or sell button.
 
@Svanoy Shortly after I sent you that message I had the feedback box popup... ok so i'll add that to my script as well. Now do you have it set to where when it sees the ok button it doesnt matter where on screen it pops up the mouse will go to it and click it? or does the feedback button pop up in the same spot everytime so I would just need to find 1 mouse pos?
 
Refer back to the commented script I posted for you a little while back. The Image Search returns values of upper left pixel of where on screen it finds the image you are looking for, FoundX and FoundY. Use those values, and add an amount to each, to exectute a mouse click on the center of the OK button. This way it doesn't matter where on screen the button is.
 
On a side note, does anyone have experience with Cheat Engine and Ultimap, or similar programs? Why I am asking is it should be possible to write a lua script to detect the op code execution that displays the alert box in TOS, then pull the text of that alert box and send commands back to TOS based on the text of the alert box(eg: if text of alert box contains the text "BUY" then send ctrl+B)

This would make it possible to run on Virtual Machines as a graphics card is not need to provide an interface. It all would be contained in memory.

I used these programs years ago for similar scripts, but it has been so long that I have forgotten much of it. I had forgotten it existed at all until this week
.
 
@Svanoy Well since we last talked on here I have been running my script. so far it seems to be running good, still doing minor adjustments here and there. Well I have a new issue. I have been letting all my trades exit automatically on a tos stoploss or takeprofit, but now I want to make a label that will change color when my stoploss or takeprofit has been hit, So I can have my script get me out of the trade. I have tried making a few labels with some of the stuff in my script that I have defined but the label just stays the color black. I'm thinking i may not be able to make a label that can determine when I'm in a trade? Could you see what you think? The issue is on line 45, its the 3rd label that I'm trying to add.
Code:
###rsi####
input price = close;
input length = 14;
input OB = 70;
input OS = 30;
input rsiAverageType = AverageType.WILDERS;

def over_bought = OB;
def over_sold = OS ;
def rsi = reference RSI(price = price, length = length, averageType = rsiAverageType);
#### Stop Loss / Profit Target ####
input offsetType = {default percent, value, tick};
input longstop = 0.05;
input shortstop = 0.05;
input longtarget = 1.2;
input shorttarget = 1.2;

def entryPrice = EntryPrice();
def mult;
switch (offsetType) {
case percent:
    mult = entryPrice / 100;
case value:
    mult = 1;
case tick:
    mult = TickSize();
}
def longstopPrice = entryPrice - longstop * mult;
def shortstopPrice = entryPrice + shortstop * mult;
def longTargetPrice = entryPrice + longtarget * mult;
def shortTargetPrice = entryPrice - shorttarget * mult;
############
def long =  rsi[0] crosses above over_sold[0];
def longexit =  low <= longstopPrice or high >= longTargetPrice or rsi[0] crosses below over_bought[0];
def short = rsi[0] crosses below over_bought[0];
def shortexit = high >= shortstopPrice or low<= shortTargetPrice or rsi[0] crosses above over_sold[0];

AddOrder(OrderType.BUY_AUTO, long, tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "LE");
AddOrder(OrderType.SELL_TO_CLOSE, longexit, tickcolor = GetColor(5), arrowcolor = GetColor(5), name = "stop");
AddOrder(OrderType.SELL_AUTO, short, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "SE");
AddOrder(OrderType.BUY_TO_CLOSE, shortexit, tickcolor = GetColor(5), arrowcolor = GetColor(5), name = "stop");
#### Labels ####
AddLabel(yes, "       ", if long[1] then Color.GREEN else Color.MAGENTA);
AddLabel(yes, "       ", if short[1] then Color.RED else Color.YELLOW);
AddLabel(yes, "       ", if  then Color.BLUE else Color.CYAN);

def NewBar = if close[1] != close[2] or high[1] != high[2] or low[1] != low[2] then yes else Double.NaN;
def Clock = if !IsNaN(NewBar) and Clock[1] == 1 then 0 else if !IsNaN(NewBar) and Clock[1] == 0 then 1 else Clock[1];
AddLabel(yes, "       ", if Clock == 0 then Color.VIOLET else Color.Gray);
 
@aCuddlyTurtle I'll give this a look when I get back from vacation. Out on the coast right now. It is possible, I have similar stoploss in mine that calculates a percent loss of my account total when the trade opened and automatically exits the trade if hit.
 
@Svanoy I think I have it figured out, now I just need to add it into my autohotkey. This is what I added.
Code:
AddLabel(yes, "       ", if  long[1] and longexit[1] or short[1] and shortexit[1] then Color.BLUE else Color.CYAN);
 
@aCuddlyTurtle I think your on the right track, but you have to remember that a defined stop would act upon the current bar, not at open after the bar that triggers the stop.

If you don't mind, please explain which labels and colors are triggering the trade opens and exits. This will help me troubleshoot your code.
 

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