Auto Trade (ALGO) in TOS

I remote in with Chrome Remote Desktop as well.. and wanted to share another way to exit the script quickly pause and show info etc.. its GUI time!

I use your script now its just well thought out and handles things perfectly. Thanks again @Kevin N. GUI in AHK is ever simple. From the website look for "SmartGUI" to download. This small program helps you build the GUI.

Here is my simple Gui code:


Code:
;Put this at the top of the script right below the variables
Gui, Destroy
Gui,+AlwaysOnTop
Gui, Font, S8 CDefault Bold, Verdana
Gui, Add, Button, x2 y-4 w60 h30 , Start
Gui, Add, Button, x62 y-4 w60 h30 , Pause
Gui, Add, Button, x122 y-4 w60 h30 , Exit
; Generated using SmartGUI Creator 4.0
Gui, Show, x950 y32 h58 w865, Your ALGO window title name goes here
Return


ButtonExit:
GuiClose:
ExitApp

ButtonPause:
pause

---------------------------------
;Main: See Below I changed from loop to toggle to break the loop and pause
ButtonStart:
sleep 1000
a := entryDelay
;checkForErrors()
Toggle := !Toggle
While Toggle {
;loop {

;Put this text box inside of the loop to have access to the info within the loop script
Gui, Add, Text, x12 y26 w850 h20 ,  Status: %status% | Algo is Running ESC to pause | Trades: %trades% of %tradeLimit% | Count: %countDownTime% | Entry: %entryTime% | Time: %TimeString%



XZIKiBA.png
 
Last edited:
Code:
; Version Beta .07 - Last Modified: 11-14-22 09:18 - Added option to disable pre-buy/sell flatten for quicker entries.
; double tap the flatten button.
; last mod creates a delay after trade closes and new trade allowed
; .07 Added entryPause Added error clearing feature.
; ver .062 Added pause for x number of minutes features.
; Made some adjustments to the screen and added auto status.  This version to be used with the algo version 5.5 or later.
#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, ToolTip, Screen
CoordMode, Pixel, Screen
CoordMode, Mouse, Screen

; CheapWindowsVPS_10
; User Defineable variables
; Use the following to set the vertical and horizontal coordinates for each.
buttonsHorizontal     = 130     ; Horizontal Coordinates, this will be the same for buy, flat, sell.
buyCoord              = 75     ; Vertical Coordinates, middle of button
flatCoord             = 150     ; Vertical Coordinates, middle of button
sellCoord             = 240     ; Vertical Coordinates, middle of button
statusHorizontal     = 125     ; The horizontal setting for the status bar
statusCoord          = 320     ; The vertical setting for the status bar
labelSearchX         = 275     ; How far to the right to search for the buy/sell label
labelSearchY         = 275     ; How far down to search for the buy/sell label

tradeLimit             = 5     ; How many trades are allowed in clearCounterPeriod before sitting out resetPeriod
resetPeriod         = 900     ; In Seconds, if tradeLimit is reached in clearCounterPeriod, how long to wait before another trade
clearCounterPeriod     = 1800     ; In Seconds, if tradeLimit is reached in this amount of time, sit out resetPeriod
entryDelay             = 0     ; In Seconds, the amount of time that must pass before another entry is allowed
exitDelay            = 0        ; In Seconds, Time that must pass after a trade exits before its allowed to buy again.
delayTime             = 0     ; In Seconds, the amount of time to wait sleep after buy, short, or flat.
entryPause            = 0        ; In Seconds, the amount of seconds to pause before pressing the buy/sell button.
flatBeforeEntry        = 0        ; In Seconds, amount of time to wait after pre-buy/sell flatten, if 0 then no pre-buy/sell flatten.
                            ;  - this is used to make sure we're flat before hitting the buy or sell entries buttons.
useTradovate        = 0     ; default is 1 (on), off is 0 (zero)
tradoBuyCoord          = 900    ; Vertical Coordinates, middle of button
tradoFlatCoord         = 1010     ; Vertical Coordinates, middle of button
tradoSellCoord         = 1135     ; Vertical Coordinates, middle of button
tradoAlignH            = 233    ; Alignment tool, this will be your horizontal setting for buy/Exit/Sell buttons.
tradoAlginV            = 1140    ; Alignment tool, this should align to the right of all your buttons.
tradoAlignT            = 0        ; 1 - yes, 0 - no, Use/display Align Tool

; End user defineable
status                 = 0
trades                 = 0
stopTimer             = 0
tosErrors            = 0

^B:: MouseClick, Left, %buyCoord%,  %buttonsHorizontal%, 1, 0
^F:: MouseClick, Left, %flatCoord%, %buttonsHorizontal%, 1, 0
^S:: MouseClick, Left, %sellCoord%, %buttonsHorizontal%, 1, 0
^P:: Pause
^E:: checkForErrors()
^R:: trades = 0  ; Reset the trades
^T:: stopTimer = 0
^D:: delayFunction(86400,"Waiting") ; 86400 = 1 Day
^F1:: delayFunction(3600,"Pausing for 1 hour")
^F2:: delayFunction(7200,"Pausing for 2 hours")
^F4:: delayFunction(14400,"Pausing for 4 hours")
^0:: status = 0 ; use this and the next two below to adjust trade status, 0 = Flat
^1:: status = 1    ; 1 = We are long
^2:: status = 2 ; 2 = We are short;

esc::
Main:
sleep 1000
a := entryDelay
;checkForErrors()

loop {
    sleep 1000
    a++
    b++     
    if (status != 1 and a >= entryDelay or status == 2 and a >= entryDelay) {
        ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w50 *h15 *10 images\white.png
        if (ErrorLevel = 0) {
            if (entryPause > 0) {
                k := entryPause
                while (k > 0) {
                    tooltip Status: Delaying Entry: %k% Seconds, %statusCoord%, %buttonsHorizontal%
                    sleep 1000
                    k--
                }
            }
          
            ;Click Flatten Button
            if (flatBeforeEntry > 0) {
                MouseClick, Left, %flatCoord%, %buttonsHorizontal%, 1, 0
          
                ;TradoVate ------------
                if (useTradovate == 1) {
                    MouseClick, Left, %tradoFlatCoord%, %tradoAlignH%, 1, 0
                }     
                delayFunction(flatBeforeEntry, "Flat Before Next Entry")
            }
          
            ;Click Buy Button if green status and we're not already in a trade
            MouseClick, Left, %buyCoord%, %buttonsHorizontal%, 1, 0
          
            ;TradoVate ------------
            if (useTradovate == 1) {
                MouseClick, Left, %tradoBuyCoord%, %tradoAlignH%, 1, 0
            }
          
            status = 1
            a = 0
            trades++
            tooltip Status: Buy Image Cords: %FoundX% x %FoundY%, %statusCoord%, %buttonsHorizontal%
            sleep delayTime * 1000
            ;checkForErrors()
        }
    } 
    if (status != 0) {
        ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w50 *h15 *10 images\blue.png
        if (ErrorLevel = 0) {
            ;Click Flatten Button
            MouseClick, Left, %flatCoord%, %buttonsHorizontal%, 1, 0
          
            ;TradoVate ------------
            if (useTradovate == 1) {
                MouseClick, Left, %tradoFlatCoord%, %tradoAlignH%, 1, 0
            }
          
            delayFunction(15, "Waiting to hit the flat button again")
          
            ; Lets hit the flat button again, to be sure after delay above
            if (useTradovate == 1) {
                MouseClick, Left, %tradoFlatCoord%, %tradoAlignH%, 1, 0
            }
            ;Click Flatten Button
            ; Let's hit TOS flat once more
            MouseClick, Left, %flatCoord%, %buttonsHorizontal%, 1, 0         
      
          
            status = 0
            tooltip Status: Flat Image Cords: %FoundX% x %FoundY%, %statusCoord%, %statusHorizontal%
            sleep delayTime * 1000
            ;checkForErrors()
            delayFunction(exitDelay, "Next Entry is Delayed")
          
        }
    }
    if (status != 2 and a >= entryDelay or status == 1 and a >= entryDelay) {
        ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w50 *h15 *10 images\dark_orange.png
        if (ErrorLevel = 0) {         
            if (entryPause > 0) {
                k := entryPause
                while (k > 0) {
                    tooltip Status: Delaying Entry: %k% Seconds, %statusCoord%, %buttonsHorizontal%
                    sleep 1000
                    k--
                }
            }
            ;Click Flatten Button
            if (flatBeforeEntry > 0) {
                MouseClick, Left, %flatCoord%, %buttonsHorizontal%, 1, 0
          
                ;TradoVate ------------
                if (useTradovate == 1) {
                    MouseClick, Left, %tradoFlatCoord%, %tradoAlignH%, 1, 0
                }     
                delayFunction(flatBeforeEntry, "Flat Before Next Entry")
            }
          
            ;Click Sell (short)
            MouseClick, Left, %sellCoord%, %buttonsHorizontal%, 1, 0
          
            ;TradoVate -------------
            if (useTradovate == 1) {
                MouseClick, Left, %tradoSellCoord%, %tradoAlignH%, 1, 0
            }
          
            status = 2
            a = 0
            trades++
            tooltip Status: Short Image Cords: %FoundX% x %FoundY%, %statusCoord%, %statusHorizontal%
            sleep delayTime * 1000
            ;checkForErrors()
        }
    }
  
    timeLeft := clearCounterPeriod - b
    entryTime := FormatSeconds(a)
    countdownTime := FormatSeconds(timeLeft)
    FormatTime, TimeString,, Time
  
    ;tooltip Status: %status%  Trades: %trades%  Count: %TimeLeft%  Entry: %a%  Time: %TimeString%, %statusCoord%, %statusHorizontal%
    tooltip Status: %status% | Trades: %trades% of %tradeLimit% | Count: %countDownTime% | Entry: %entryTime% | Time: %TimeString% | Errors: %tosErrors%, %statusCoord%, %statusHorizontal%
  
    ; Tradovate
    if (tradoAlignT == 1) {
        tooltip "<----", %tradoAlignV%, %tradoAlignH%, 2
    }
  
    if (trades >= tradeLimit) {
        trades = 0
        ;Click Flatten Button
        MouseClick, Left, %flatCoord%, %buttonsHorizontal%, 1, 0
        sleep resetPeriod * 1000
        j++
      
        if (j == 2 ) {
            tooltip Reset Count: %j% Time: %TimeString%, %statusCoord%, %statusHorizontal%
            exit
        }
    }
    if (b >= clearCounterPeriod) {
        b = 0
        trades = 0
        checkForErrors()
    }
}

return

FormatSeconds(NumberOfSeconds)  ; Convert the specified number of seconds to hh:mm:ss format.
{
    time := 19990101  ; *Midnight* of an arbitrary date.
    time += NumberOfSeconds, seconds
    FormatTime, mmss, %time%, mm:ss
    return NumberOfSeconds//3600 ":" mmss
    /*
    ; Unlike the method used above, this would not support more than 24 hours worth of seconds:
    FormatTime, hmmss, %time%, h:mm:ss
    return hmmss
    */
}

delayFunction(SecondsToWait, Message )
{
    k := SecondsToWait
    global stopTimer = 1
    global statusCoord
    global statusHorizontal
    while (k > 0)
    {
        if (stopTimer != 1) {
            break
        }
        timeLeft:= FormatSeconds(k)
        tooltip %Message%: %timeLeft%, %statusCoord%, %statusHorizontal%
        sleep 1000
        k--
    }
    stopTimer = 0
}

checkForErrors()
{ 
    global statusCoord
    global statusHorizontal
    global tosErrors
  
    tosHorizontal := statusHorizontal - 30
    tooltip Errors:  %tosErrors% | %FoundX% x %FoundY%, %statusCoord%, %tosHorizontal%
  
    ImageSearch, FoundX, FoundY, 0, 0, %A_ScreenWidth%, %A_ScreenHeight%, *50 images\tosWarningOK.bmp
    if (ErrorLevel = 0) {
            ;Clear the TOS Performance Issue Message
            FoundX:=FoundX+5, FoundY:=FoundY+5
            MouseClick, Left, %FoundX%, %FoundY%, 1, 0
            tosErrors++
            tooltip OK Warnings Cleared: %tosErrors% | %FoundX% x %FoundY%, %statusCoord%, %tosHorizontal%

    }
    ImageSearch, FoundX, FoundY, 0, 0, %A_ScreenWidth%, %A_ScreenHeight%, *140 images\tosWarningContinue.png
    if (ErrorLevel = 0) {
            ;Clear the TOS Order Submit Error Message
            FoundX:=FoundX+10, FoundY:=FoundY+10
            MouseClick, Left, %FoundX%, %FoundY%, 1, 0
            tosErrors++
            tooltip CONTINUE Warnings Cleared: %tosErrors% | %FoundX% x %FoundY%, %statusCoord%, %tosHorizontal%
    }
  
    ; Lets mouse click top left to clear this weird drop down menu error I've received many times
    MouseClick, Left, 5, 5, 1, 0
  
    return 
}

I forgot to mention above, run the script as administrator, that's the only way it will click the buttons for you. Also, to start the script hit the esc on your keyboard, then there are several keys I did not comment what they are, but should be kinda obvious, it's all the ones that have the ^ (Ctrl) in front of them, so Ctrl + F1 will pause the script for one hour, etc...

is this placing a (paper) trade on TOS and real trade on Tradovate?
 
@SilverWolf I like it, I never really fooled with a GUI. I may play with this some and make a gui optional.

@Goingdark365, in the previous image I posted, I was running my algo on a simulated account in TOS, then it would take real trades on two prop accounts via Tradovate. I do also having it take real trades. You can run a strategy on paper or real, doesn't matter, they work the same..... BUT, make sure you contact TOS support and ask them to turn on real time data on your paper account.
 
@Kevin N thank you
well im stuck with the exit/stop lables changing color or changing color on time im trying use
long_stop = low crosses below entryprice() - stop
long_target = high closses above entryprice() + target

only time i got it to chage was bar after crossing stop/target any ideas
 
@SilverWolf thank you ive been trying this method but no luck(at least with my script) if im in a short pos -1, if a green or red lable come up it will flatten then enter the new trade
im going to try your script and report back
thanks again
@Goingdark365 we can continue this convo over here.. as to keep that one about Indicators. So is that what you want it to do? If you are short you code needs to hold that info and only do the if statement if short = yes or like in my script its status = 2.

So i have something like this. The only way it will even look for the a new entry for example is if im flat. (status = 0)

CSS:
 if (status = 0 and a >= entryDelay) { ;Long
        ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w20 *h20 *10 images\BuyLabel.tiff
 
@SilverWolf
(not sure what happen to my last post seems it got delited but )
like this since im using active trader for stop and target


Code:
#
#NoEnv
#SingleInstance, Force
SendMode, Input
SetBatchLines, -1
SetWorkingDir, %A_ScriptDir%
CoordMode, Pixel, Screen
Delay = 10000
esc:: Pause
^9::
Loop
{
   ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w59 *h26 Images\Positive.tiff
        if (ErrorLevel = 0){
            status = 1
           
            sleep 100
        }
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w58 *h26 Images\Negative.tiff
        if (ErrorLevel = 0){
            status = 2
            
            sleep 100
        }
    ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w71 *h26 Images\FlatPic.tiff
        if (ErrorLevel = 0){
            status = 0
            sleep 100
        }
;====================looking for a long 
        if (status = 0 and a >= entryDelay) { ;Long
    ImageSearch, FoundX, FoundY, 0, 0, 540, 160, *w20 *h20 *10 images\BuyLabel.tiff
        }If (ErrorLevel = 0 )
        {
    ;mouse to open space
        delay = 10
        MouseClick, Left, 777, 95, 1, 0
        delay = 10
    ;mouse move to flatten
        delay = 10
        MouseClick, Left, 700, 95, 1, 0
        delay = 10
    ;mouse move to buy
        delay = 10
        MouseClick, Left, 533, 95, 1, 0
        delay = 10
    ;mouse move back to open space
        delay = 10
        MouseClick, Left, 777, 95, 1, 0
        delay = 10
        }
        ;If not found do nothing
        Else If (ErrorLevel = 1)
        {
        }
;=====================looking for a short 
    if (status = 0 and a >= entryDelay){ ; short
    ImageSearch, FoundX, FoundY, 0, 0, 540,160, *w20 *h20 *10 images\shortLabel.tiff
    ;mouse to open space
        delay = 10
        MouseClick, Left, 777,95, 1, 0
        delay = 10
    ;move mouse to flatten
        MouseClick, Left, 700,95, 1, 0
        delay = 10
    ;move mouse to short
        delay = 10
        MouseClick, Left, 608,95, 1, 0
        delay = 10
    ;move mouse back to open space
        delay = 10
        MouseClick, Left, 777,95, 1, 0
        delay = 10
        }
    ;If not found do nothing
        Else If (ErrorLevel = 1)
        {
        }
}
Return
 
Last edited:
You can remove the entryDelay if you dont intend to use an entry delay.

and a >= entryDelay <--- is not needed


That looks like it should work. So now it will only buy or sell if you are flat. you could try it with ONdemand
 
This script will look at lower indicators as well as the chart. if the chart and lower indicators agree then action is taken. create your image files and ensure dimensions are correct where theyll be located in the script. This is a modification of @Kevin N supplied script. Thanks again. I also have add a user interface. The buttons call files created by TinyTask. https://tinytask.en.softonic.com/ that reorganize the chart, purge the garbage and other things. For the script to see the lowers you will have to modify your lower indicators to have a buy/sell bullish/bearish label.

Example:
CSS:
Addlabel(yes,  if bullishMACD then " Lw2$ " else " !Lw2 ", if bullishMACD then color.Green else color.Red);



CSS:
; Created/Shared by Kevin N altered by SilverWolf
; https://usethinkscript.com/threads/auto-trade-algo-in-tos.7546/post-114283
; Version Beta .11 - Last Modified: 12-27-22  - Added GUI and introduced Lower indicator calculations
;Added option to disable pre-buy/sell flatten for quicker entries.
; double tap the flatten button.
; last mod creates a delay after trade closes and new trade allowed
; .07 Added entryPause Added error clearing feature.
; ver .062 Added pause for x number of minutes features.
; Made some adjustments to the screen and added auto status.  This version to be used with the algo version 5.5 or later.
#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, ToolTip, Screen
CoordMode, Pixel, Screen
CoordMode, Mouse, Screen


; CheapWindowsVPS_10
; User Defineable variables
; Use the following to set the vertical and horizontal coordinates for each.
buttonsHorizontal     = 1630    ; Horizontal Coordinates, this will be the same for buy, flat, sell.
buyCoord              = 155     ; Vertical Coordinates, middle of button
sellCoord             = 193     ; Vertical Coordinates, middle of button
flatCoord             = 225     ; Vertical Coordinates, middle of button
statusHorizontal      = 75     ; The horizontal setting for the status bar
statusCoord           = 760    ; The vertical setting for the status bar
labelSearchX          = 1160     ; How far to the right to search for the buy/sell label
labelSearchY          = 260     ; How far down to search for the buy/sell label


SingleShare            = 1
tradeLimit             = 100     ; How many trades are allowed in clearCounterPeriod before sitting out resetPeriod
resetPeriod            = 900     ; In Seconds, if tradeLimit is reached in clearCounterPeriod, how long to wait before another trade
clearCounterPeriod     = 1800     ; In Seconds, if tradeLimit is reached in this amount of time, sit out resetPeriod
entryDelay             = 5     ; In Seconds, the amount of time that must pass before another entry is allowed
exitDelay              = 0        ; In Seconds, Time that must pass after a trade exits before its allowed to buy again.
delayTime              = 0     ; In Seconds, the amount of time to wait sleep after buy, short, or flat.
entryPause             = 0        ; In Seconds, the amount of seconds to pause before pressing the buy/sell button.
flatBeforeEntry        = 0        ; In Seconds, amount of time to wait after pre-buy/sell flatten, if 0 then no pre-buy/sell flatten.


; End user defineable
status                 = 0
trades                 = 0
stopTimer              = 0
tosErrors              = 0


Gui, Destroy
;Gui,+AlwaysOnTop
Gui -Caption +ToolWindow +Border +LastFound +AlwaysOnTop -Border +hWndhGUI
Gui, Color, 313131
Gui, Font, S7 CDefault Bold, Verdana
Gui, Add, Button, x2 y-4 w50 h30 , Start
Gui, Add, Button, x52 y-4 w50 h30 , Pause
Gui, Add, Button, x362 y-4 w50 h30 , Exit
Gui, Add, Button, x102 y-4 w50 h30 , Reset
Gui, Add, Button, x202 y-4 w50 h30 , Garbage
Gui, Add, Button, x152 y-4 w50 h30 , Refresh
Gui, Add, Button, x252 y-4 w50 h30 , Focus
Gui, Add, Button, x302 y-4 w30 h30 , 1
Gui, Add, Button, x332 y-4 w30 h30 , 2

; Generated using SmartGUI Creator 4.0
Gui, Show, x760 y51 h21 w418, TOS Algo Trading System
Return


ButtonExit:
GuiClose:
ExitApp   2

ButtonPause:
Send Esc
Pause,, 1
tooltip  Algo is PAUSED, %statusCoord%, %statusHorizontal%
Return

ButtonReset:
status =    0
UpBuySignal = 0
Lw1Bsignal = 0
Lw2Bsignal = 0
BUYvalue = 0
UpSellSignal = 0
Lw1Ssignal = 0
Lw2Ssignal = 0
SELLvalue = 0
statusWord = Flat
trades =    0
stopTimer = 0
Return

ButtonRefresh:
Run, lib/TOS refresh chart
Return

ButtonGarbage:
Run, lib/TOS collect garbage
Return

ButtonFocus:
Run, lib/TOS focus
Return

Button1:
Run, lib/TOS ActiveTrader
Return

Button2:
Run, lib/TOS Chart
Return


^B:: MouseClick, Left,  %buttonsHorizontal%, %buyCoord%, 1, 0
^F:: MouseClick, Left, %buttonsHorizontal%, %flatCoord%, 1, 0
^S:: MouseClick, Left, %buttonsHorizontal%, %sellCoord%, 1, 0
^ESC:: ExitApp
ESC:: Pause
^R:: trades = 0  ;Reset the trades
^T:: stopTimer = 0
^D:: delayFunction(86400,"Waiting") ; 86400 = 1 Day
^F1:: delayFunction(3600,"Pausing for 1 hour")
^F2:: delayFunction(7200,"Pausing for 2 hours")
^F4:: delayFunction(14400,"Pausing for 4 hours")
^0:: status = 0
^1:: status = 1  
^2:: status = 2

ButtonStart:
;Main:
a := entryDelay
Toggle := !Toggle
While Toggle {
sleep 1000
    a++
    b++

        status = 0
        UpBuySignal = 0
        Lw1Bsignal = 0
        Lw2Bsignal = 0
        BUYvalue = 0
        UpSellSignal = 0
        Lw1Ssignal = 0
        Lw2Ssignal = 0
        SELLvalue = 0

            ;Maintain single share
            ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w70 *h26 Images\TwoBuy.tiff
                if (ErrorLevel = 0 and SingleShare = 1){
                status = 1
                    ;Correct and sell one back
                               MouseClick, Left, %buttonsHorizontal%, %sellCoord%, 1, 0
                    sleep 3000
                }
            ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w71 *h26 Images\TwoSell.tiff
                if (ErrorLevel = 0 and SingleShare = 1){
                status = 2
                    ;Correct and buy one back
                                MouseClick, Left, %buttonsHorizontal%, %buyCoord%,  1, 0
                    sleep 3000
                }

            ;Get status from TOS        
            ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w71 *h26 Images\FlatPic.tiff
                if (ErrorLevel = 0){
                    status = 0
                    statusWord = Flat
                    sleep 100
                }        
            ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w59 *h26 Images\Positive.tiff
                if (ErrorLevel = 0){
                    status = 1
                    statusWord = Long
                    sleep 100
                }
            ImageSearch, FoundX, FoundY, 0, 0, 1840, 440,  *w58 *h26 Images\Negative.tiff
                if (ErrorLevel = 0){
                    status = 2
                    statusWord = Short
                    sleep 100
                }
       
            ;Three indicator buy signal
            ImageSearch, FoundX, FoundY, 150, 205, 1200, 235, *w31 *h21 Images\ABuyLabel.tiff
                if (ErrorLevel = 0){
                    UpBuySignal = 1
                    ;FindText().MouseTip(v.x, v.y)
                }
            ImageSearch, FoundX, FoundY, 0, 700, 400, 1000, *w40 *h21 Images\ALwr1Buy.tiff
                if (ErrorLevel = 0){
                    Lw1Bsignal = 1
                    ;FindText().MouseTip(v.x, v.y)
                }
            ImageSearch, FoundX, FoundY, 0, 700, 400, 1000, *w40 *h20 Images\ALwr2Buy.tiff
                if (ErrorLevel = 0){
                    Lw2Bsignal = 1
                    ;FindText().MouseTip(v.x, v.y)
                }
                BUYvalue := UpBuySignal+Lw1Bsignal+Lw2Bsignal
                ;MsgBox, % "Buy Total: " BUYvalue
               

            ;Three indicator sell signal
            ImageSearch, FoundX, FoundY, 150, 205, 1200, 235, *w28 *h20 Images\ASellLabel.tiff
                if (ErrorLevel = 0){
                    UpSellSignal = 1
                    ;FindText().MouseTip(v.x, v.y)
                }
            ImageSearch, FoundX, FoundY, 0, 700, 400, 1000, *w38 *h20 Images\ALwr1Sell.tiff
                if (ErrorLevel = 0){
                    Lw1Ssignal = 1
                    ;FindText().MouseTip(v.x, v.y)
                }
            ImageSearch, FoundX, FoundY, 0, 700, 400, 1000, *w38 *h20 Images\ALwr2Sell.tiff
                if (ErrorLevel = 0){
                    Lw2Ssignal = 1
                    ;FindText().MouseTip(v.x, v.y)
                }
                SELLvalue := UpSellSignal+Lw1Ssignal+Lw2Ssignal
                ;MsgBox, % "Sell Total: " SELLvalue



            ;Evaluate and Go Long
            if (BUYvalue >= 3 and status = 0 and a >= entryDelay) { ;goLong          
                    if (entryPause > 0) {
                        k := entryPause
                        while (k > 0) {
                            ;tooltip Status: Delaying Entry: %k% Seconds, %statusCoord%, %buttonsHorizontal%
                            sleep 100
                            k--          
                        }
                    }  
                    ;Click Flatten Button
                    if (flatBeforeEntry > 0) {
                        MouseClick, Left, %buttonsHorizontal%, %flatCoord%, 1, 0
                    delayFunction(flatBeforeEntry, "Flat Before Next Entry")
                    }
               
                    ;Click Buy (Long)
                    MouseClick, Left, %buttonsHorizontal%, %buyCoord%,  1, 0
                    MouseMove,  1800, 175, 100

                    status = 1
                    statusWord = Long

                    a = 0
                    trades++
                    sleep delayTime * 100
            }  

            ;Evaluate and Go Short
            if (SELLvalue >= 3  and status = 0 and a >= entryDelay) { ;goShort        
                    if (entryPause > 0) {
                        k := entryPause
                        while (k > 0) {
                            ;tooltip Status: Delaying Entry: %k% Seconds, %statusCoord%, %buttonsHorizontal%
                            sleep 100
                            k--
                        }
                    }
                    ;Click Flatten Button
                    if (flatBeforeEntry > 0) {
                        MouseClick, Left, %buttonsHorizontal%, %flatCoord%, 1, 0
                    delayFunction(flatBeforeEntry, "Flat Before Next Entry")
                    }
               
                    ;Click Sell (short)
                    MouseClick, Left, %buttonsHorizontal%, %sellCoord%,  1, 0
                    MouseMove,  1800, 175, 100

                    status = 2
                    statusWord = Short

                    a = 0
                    trades++
                    sleep delayTime * 100
            }

            ImageSearch, FoundX, FoundY, 150, 205, 1200, 235, *w30 *h20 Images\ABuyFlat.tiff
            if (ErrorLevel = 0 and status = 1)  { ;Long Close
                        ;Click Flatten Button
                        MouseClick, Left, %buttonsHorizontal%, %flatCoord%, 1, 0
                        MouseMove,  1800, 175, 100

                        status = 0
                        statusWord = Flat

                        sleep delayTime * 100
                        delayFunction(exitDelay, "Next Entry is Delayed")        
            }

            ImageSearch, FoundX, FoundY, 150, 205, 1200, 235, *w30 *h20 Images\ASellFlat.tiff
            if (ErrorLevel = 0 and status = 2)  { ;Short Close
                        ;Click Flatten Button
                        MouseClick, Left, %buttonsHorizontal%, %flatCoord%, 1, 0          
                        MouseMove,  1800, 175, 100

                        status = 0
                        statusWord = Flat

                        sleep delayTime * 1000
                        delayFunction(exitDelay, "Next Entry is Delayed")
            }

    timeLeft := clearCounterPeriod - b
    entryTime := FormatSeconds(a)
    countdownTime := FormatSeconds(timeLeft)
    FormatTime, TimeString,, Time
 
    tooltip  Algo is LIVE | Status: %statusWord% | Entry: %entryTime% | Trades: %trades% of %tradeLimit% | Count: %countDownTime% | Time: %TimeString%, %statusCoord%, %statusHorizontal%

    if (trades >= tradeLimit) {
        trades = 0
        ;Click Flatten Button
        MouseClick, Left, %buttonsHorizontal%, %flatCoord%, 1, 0
        sleep resetPeriod * 100
        j++
     
        if (j == 2 ) {
            tooltip Reset Count: %j% Time: %TimeString%, %statusCoord%, %statusHorizontal%
            exit
        }
    }
    if (b >= clearCounterPeriod) {
        b = 0
        trades = 0
    }

}return


FormatSeconds(NumberOfSeconds)  ; Convert the specified number of seconds to hh:mm:ss format.
{
    time := 19990101  ; *Midnight* of an arbitrary date.
    time += NumberOfSeconds, seconds
    FormatTime, mmss, %time%, mm:ss
    return NumberOfSeconds//3600 ":" mmss
    /*
    ; Unlike the method used above, this would not support more than 24 hours worth of seconds:
    FormatTime, hmmss, %time%, h:mm:ss
    return hmmss
    */
}

delayFunction(SecondsToWait, Message )
{
    k := SecondsToWait
    global stopTimer = 1
    global statusCoord
    global statusHorizontal
    while (k > 0)
    {
        if (stopTimer != 1) {
            break
        }
        timeLeft:= FormatSeconds(k)
        tooltip %Message%: %timeLeft%, %statusCoord%, %statusHorizontal%
        sleep 1000
        k--
    }
    stopTimer = 0
}
 
Auto Trade with AHK
Hello. I’m new here. I was wondering if anyone can write me a code for auto trading. I do have a specific indicator I would like to use. I noticed some people being able to automate their trading. Please send me a script to do so. Thanks in advance!!!
 
Last edited by a moderator:
Auto Trade with AHK
Hello. I’m new here. I was wondering if anyone can write me a code for auto trading. I do have a specific indicator I would like to use. I noticed some people being able to automate their trading. Please send me a script to do so. Thanks in advance!!!
I would start by reading the whole thread. You will find basic scripts and even an indicator to get you started in your understanding. Someone could make, but unless you understand how it works you will fail. Above is a AHK script that does all you would need and more. But you first should study, learn a little how ahk works. Then give it a spin on papertrading..

Thank you very much SilverWolf. I will give it a whirl very soon. I’ll let you know how it works out. :)
If you need help or have questions Im happy to assist.
 
So I loaded the script under strategies but something went wrong. A bunch of invalid statements showed up and it doesn’t do anything while paper trading. Did I do something wrong?
 
So I loaded the script under strategies but something went wrong. A bunch of invalid statements showed up and it doesn’t do anything while paper trading. Did I do something wrong?
  1. Code found in this thread is NOT for use within the confines of the ToS app. ToS does not provide automated trading.
  2. Codes found in this thread are using the TDI API interface or as a AHK routine.
  3. Strategies in the ToS app ONLY apply to backtesting. You cannot save code as a strategy and apply to live trading.
Sounds like you did not follow @SilverWolf instructions. Start with page 1 and read through this thread.
If you have not already registered for API, be aware that new API registrations are not being accepted. Schwab is in the process of switching the TDA API over to Schwab
https://developer.tdameritrade.com/
 
Last edited:
@SilverWolf @Kevin N thought you guys might be able to use this use script, I’m using to place a limit order.
(I’m still work in progress with this trying to finalize it, if not triggers in next 2 candles to cancel the limit order )
1st select show studies from chart on you active trader
2nd looks for that image on the active trader and move over to the buy or sell and mouse click for a limit my buy is x + 85 and sell is x +130

Code:
^9::
ImageSearch, FoundX, FoundY, 485,199,598,994,  C:\Users\.png

   mousemove, FoundX +85 , FoundY


}
 
Last edited:
Let me give a couple more tips...

1. Virtual Machines and VPS - I run my setups on virtual machines, right now I'm using the one by Oracle, it's free. You can download evaluation copies of windows server that are good for 6 months. In addition to that, I run two on a VPS from CheapWindowsVPS, search for coupon codes for them, I'm running a windows 10 pro VPS for $8.50 per month, also a windows 2016 server. From there, I use Chrome Remote Desktop to remote in, and it's like I have another computer running with a reliable internet connection. With the virtual machine from Oracle that you run on your local PC, you can minimize it once it's up and running, then no issues with other work you want to do on your computer.

2. Less is more - Try to find a good strategy that does not trade a gazillion times a day. With this setup in a fast moving market, slippage is a real thing. When I'm trading /MNQ I can easily loose 5 - 10 pts to slippage. So remember, less is more when using AHK with TOS. The less your system trades the more realistic your backtests will be. I'm currently running systems based on the Opening Range Break, this trades 1 - 3x a day on avg. Also, keep up with market news, there is no way your algo will keep up when things like Fed Rate Announcements come out.
Hey @Kevin N Im looking into trying out a VPS solution. Is the lower ram size an issue? To get 16gb ram its $28 a month. Just curious if you had any issues
 
@SilverWolf @Kevin N thought you guys might be able to use this use script, I’m using to place a limit order.
(I’m still work in progress with this trying to finalize it, if not triggers in next 2 candles to cancel the limit order )
1st select show studies from chart on you active trader
2nd looks for that image on the active trader and move over to the buy or sell and mouse click for a limit my buy is x + 85 and sell is x +130

Code:
^9::
high = C:\Users\.png
img1 := imgSize(high)
CoordMode, Pixel
CoordMode, Mouse

^F2::
ImageSearch, x, y, 0, 0, A_ScreenWidth, A_ScreenHeight, %high%
 MouseClick, Left, x + img1.w / 2+ 85 , y + img1.h / 2
Return

imgSize(img1) { ; https://www.autohotkey.com/boards/viewtopic.php?f=76&t=81665
 ; Returns an array indicating the image's width (w) and height (h), obtained from the file's properties
 SplitPath, img1, fn, dir
 objShell  := ComObjCreate("Shell.Application")
 objFolder := objShell.NameSpace(dir), objFolderItem := objFolder.ParseName(fn)
 scale     := StrSplit(RegExReplace(objFolder.GetDetailsOf(objFolderItem, 31), ".(.+).", "$1"), " x ")
 Return {w: scale.1, h: scale.2}

}
Is this the script you were intending?
 
the script original script for the offset was way to complicated, its actually simple its just an image search and and offset click i updated the original script and here it is again

1st select show studies from chart on you active trader
2nd looks for that image on the active trader and move over to the buy or sell and mouse click for a limit my buy is x + 85 and sell is x +130

ImageSearch, FoundX, FoundY, 485,199,598,994, C:\Users\.png
mousemove, FoundX +85 , FoundY
 
Wanted to share a quick script I made to show P/L minus commissions and fees. To run you will need a library script called Vis2 which allows AHK to interpret (read) text. This is a quick script to show a pop up. My setup is different then yours so you will most definitely need adjust where Vis2 looks. I made notes in the script to assist.

CSS:
;https://usethinkscript.com/threads/auto-trade-algo-in-tos.7546/
#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]

#include <Vis2>


; CTRL - P to start
^p::
GetPL()


GetPL()
{

;To setup uncomment the msg box. You only want the numbers no letters no symbols or the math wont work.

; P/L coordinates
x := 1605
y := 413
w := 55
h := 22
;MsgBox % OCR([x, y, w, h])

; B/S ? by ? coordinates
x1 := 1605
y1 := 360
w1 := 25
h1 := 25
;MsgBox % OCR([x1, y1, w1, h1])

        ;Get P/L Day
        PLDay := OCR([x, y, w, h])

        ;Get B/S for the day
        BSDay := OCR([x1, y1, w1, h1])

        ;Fees
        CommissionsNFees = 6.2

        ;Math to get day Total of fees
        BSTotal := BSDay * CommissionsNFees

                ;msgbox, %BSTotal%

        ;Math to get Net Profits
        PLTotal := PLDay - BSTotal

        ;Trim zeros
        StringTrimRight, PLTotal, PLTotal, 4

                    ;msgbox, %PLTotal%


    MsgBox, 48, Net P/L Total:, Net Profit and Loss for the day: $%PLTotal%

}Return
 
Last edited:

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