Auto Trade (ALGO) in TOS

@Jonessw1 Late to answer, but I've been running a few different strategies live over the past year mainly to confirm back testing results.
As far as the auto trade setup I am using with AHK, it has worked flawlessly.
As far as profit goes, it has been moderate. I did expect this though as I trade futures and purposely start each run with as little as possible in micro markets, this leads to the commission cost of the trades eating up much of the profit.
I can say I make enough to keep the account I use funded.
As I identify strong strategies, I will eventually move into larger markets where commissions won't be an issue.

I have recently moved up to larger time frames to offset the commission costs.
I am in a run now that I am dubbing the "Long Haul" using a 30 min bar and getting signals to reverse my position an average of every 10 to 12 days.
I plan on running this strat uninterrupted for 1 year, hence the name.

I'm using a strategy in /MES based on a combination of the following:
-Mobius's Super Trend for TOS w/plot edits that I have posted in the thread for that indicator and with settings of Multiplier: 5, Period: 20
-Built in CCI study for TOS with setting of 10 for the length.
-A study posted in this forum that I was heavily involved with.

The backtest of the last 180 days with 30 min bars returned a win rate of 77%.
If it performs as well as the backtest suggests, I will clean up the code and post it here and probably ask for help with adjusting it for smaller time frames.

The only real issue I have had is the PC I was using as a dedicated autotrader crapped out, so I'm using my main PC for right now which has led to me not being as active on this forum. I have to let it run all week since a signal could happen at any time and I may be at work or asleep.

In order to track total profit, you have to track it in your study. Here is mine as example, I use it to calculate how many contracts to run, it should help you get started.


J8lRYFs.png

Ruby:
input tolerance = 0;
def PL;
def PLT;
def profit;
def size;

if TradeCount <= 0
then {
    PL = -2.52;
    PLT = 0;
    profit = startamt + PL;
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;

} else if State[1] == 0 and State == 1 {
    PL = (RoundDown(((((TP[1] - tolerance) - (TP[0] + tolerance)) / TickSize()) * TickValue()) * size[1], 2)) - (5.45 * size[1]);
    PLT = (RoundDown(((((TP[1] - tolerance) - (TP[0] + tolerance)) / TickSize()) * TickValue()) * size[1], 2));
    profit = profit[1] + PL;
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;
   
} else if State[1] == 1 and State == 0 {
    PL = (RoundDown(((((TP[0] + tolerance) - (TP[1] - tolerance)) / TickSize()) * TickValue()) * size[1], 2)) - (5.45 * size[1]);
    PLT = (RoundDown(((((TP[0] + tolerance) - (TP[1] - tolerance)) / TickSize()) * TickValue()) * size[1], 2));
    profit = profit[1] + PL;
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;
   
} else {
    PL = PL[1];
    PLT = PLT[1];
    profit = profit[1];
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;
   
}
def TotalGain = if TradeCount < 0 then 0 else if PL[1] != PL and PL >= 0 then TotalGain[1] + PL else TotalGain[1];
def TotalLoss = if TradeCount < 0 then 0 else if PL[1] != PL and PL <= 0 then TotalLoss[1] + PL else TotalLoss[1];

def WinCount = if TradeCount <= 0 then 0
else if (TradeCount[1] + 1) == TradeCount and PL >= 0 then WinCount[1] + 1
else WinCount[1];

def LossCount = if TradeCount <= 0 then 0
else if (TradeCount[1] + 1) == TradeCount and PL <= 0 then LossCount[1] + 1
else LossCount[1];

AddChartBubble(show_bubbles and !IsNaN(GU[0]) and IsNaN(GU[1]) and State == 1 and TradeCount >=0, if PL>=0 then high else low, "#"+TradeCount+" Buy:" + size[1] + "| P/L:" + profit + " |Buy:" + size, If TradeCount==0 then Color.GRAY else If PL>0 then Color.LIGHT_GREEN else If PL<0 then Color.PINK else Color.LIGHT_GRAY, no);

AddChartBubble(show_bubbles and IsNaN(GX[1]) and !IsNaN(GX[0]) and State == 0 and TradeCount >=0, if PL<0 then low else high, "#"+TradeCount+" Sell:" + size[1] + "| P/L:" + profit + " |Sell:" + size, If Tradecount==0 then Color.GRAY else If PL>0 then Color.LIGHT_GREEN else If PL<0 then Color.PINK else Color.LIGHT_GRAY, yes);
there is an eror
 

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

@Jonessw1 Late to answer, but I've been running a few different strategies live over the past year mainly to confirm back testing results.
As far as the auto trade setup I am using with AHK, it has worked flawlessly.
As far as profit goes, it has been moderate. I did expect this though as I trade futures and purposely start each run with as little as possible in micro markets, this leads to the commission cost of the trades eating up much of the profit.
I can say I make enough to keep the account I use funded.
As I identify strong strategies, I will eventually move into larger markets where commissions won't be an issue.

I have recently moved up to larger time frames to offset the commission costs.
I am in a run now that I am dubbing the "Long Haul" using a 30 min bar and getting signals to reverse my position an average of every 10 to 12 days.
I plan on running this strat uninterrupted for 1 year, hence the name.

I'm using a strategy in /MES based on a combination of the following:
-Mobius's Super Trend for TOS w/plot edits that I have posted in the thread for that indicator and with settings of Multiplier: 5, Period: 20
-Built in CCI study for TOS with setting of 10 for the length.
-A study posted in this forum that I was heavily involved with.

The backtest of the last 180 days with 30 min bars returned a win rate of 77%.
If it performs as well as the backtest suggests, I will clean up the code and post it here and probably ask for help with adjusting it for smaller time frames.

The only real issue I have had is the PC I was using as a dedicated autotrader crapped out, so I'm using my main PC for right now which has led to me not being as active on this forum. I have to let it run all week since a signal could happen at any time and I may be at work or asleep.

In order to track total profit, you have to track it in your study. Here is mine as example, I use it to calculate how many contracts to run, it should help you get started.


J8lRYFs.png

Ruby:
input tolerance = 0;
def PL;
def PLT;
def profit;
def size;

if TradeCount <= 0
then {
    PL = -2.52;
    PLT = 0;
    profit = startamt + PL;
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;

} else if State[1] == 0 and State == 1 {
    PL = (RoundDown(((((TP[1] - tolerance) - (TP[0] + tolerance)) / TickSize()) * TickValue()) * size[1], 2)) - (5.45 * size[1]);
    PLT = (RoundDown(((((TP[1] - tolerance) - (TP[0] + tolerance)) / TickSize()) * TickValue()) * size[1], 2));
    profit = profit[1] + PL;
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;
   
} else if State[1] == 1 and State == 0 {
    PL = (RoundDown(((((TP[0] + tolerance) - (TP[1] - tolerance)) / TickSize()) * TickValue()) * size[1], 2)) - (5.45 * size[1]);
    PLT = (RoundDown(((((TP[0] + tolerance) - (TP[1] - tolerance)) / TickSize()) * TickValue()) * size[1], 2));
    profit = profit[1] + PL;
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;
   
} else {
    PL = PL[1];
    PLT = PLT[1];
    profit = profit[1];
    size = if RoundDown(profit / contractprice, 0) - 1 <= 0 then 1 else RoundDown(profit / contractprice, 0) - 1;
   
}
def TotalGain = if TradeCount < 0 then 0 else if PL[1] != PL and PL >= 0 then TotalGain[1] + PL else TotalGain[1];
def TotalLoss = if TradeCount < 0 then 0 else if PL[1] != PL and PL <= 0 then TotalLoss[1] + PL else TotalLoss[1];

def WinCount = if TradeCount <= 0 then 0
else if (TradeCount[1] + 1) == TradeCount and PL >= 0 then WinCount[1] + 1
else WinCount[1];

def LossCount = if TradeCount <= 0 then 0
else if (TradeCount[1] + 1) == TradeCount and PL <= 0 then LossCount[1] + 1
else LossCount[1];

AddChartBubble(show_bubbles and !IsNaN(GU[0]) and IsNaN(GU[1]) and State == 1 and TradeCount >=0, if PL>=0 then high else low, "#"+TradeCount+" Buy:" + size[1] + "| P/L:" + profit + " |Buy:" + size, If TradeCount==0 then Color.GRAY else If PL>0 then Color.LIGHT_GREEN else If PL<0 then Color.PINK else Color.LIGHT_GRAY, no);

AddChartBubble(show_bubbles and IsNaN(GX[1]) and !IsNaN(GX[0]) and State == 0 and TradeCount >=0, if PL<0 then low else high, "#"+TradeCount+" Sell:" + size[1] + "| P/L:" + profit + " |Sell:" + size, If Tradecount==0 then Color.GRAY else If PL>0 then Color.LIGHT_GREEN else If PL<0 then Color.PINK else Color.LIGHT_GRAY, yes);
hello team.. getting an error when creating this scripts. please help!
 
@Kevin N, here is the layout I'm using for a run I started just a few days ago with 1 contract while I'm trying out and developing a couple new strategies.

Box labeled "1" will be green for a buy signal, box labeled "2" will be red for a sell signal, box labeled "3" will be yellow for an open position, and box labeled "4" is something new. It works as a "heartbeat", switching between black and purple every time a new bar starts. This allows me to synchronize my script with the chart by sending a signal every time a new bar starts and will help with what is called 'fuzzy logic' that I am working on in my script. The lower left is the binary display for contracts.. Actually I probably should go ahead and move all the label displays to the lower chart. May do that on a future run, but this works for now.

With this layout, I have 2 areas of the screen defined in my script to "watch". The first encompasses the upper four labels and the second encompasses all the lower binary labels.

Layout.jpg


Make the images you are using as reference in your ImageSearch a couple pixels smaller than what is displayed on screen, you can do this by taking a snip of the label on screen and cropping it down to be a couple pixels narrower and shorter. This helps with recognition of the label by removing the border pixels that may be a gradient of the color you are looking for and can cause AutoHotKey to not recognize it.

Note the pixel size of your cropped image to define the ImageSearch.

crop.jpg



I believe someone already mention that you can change the order template to submit a trailing stop at the same time you submit a order incase something happens and you lose contact with the platform.

Decided to switch strategies to one I have been running in my paper trade account on another computer after seeing the thread about SQN theory. I had been using the Thinkscript Strategy Report and Monte Carlo Analysis from http://readtheprospectus.wordpress.com. After reading up on SQN I applied it to the strategy I was paper trading and got a rating of 9.34 which I attribute to it being a high frequency trading strategy that could trade up to 800 times per year. (The strategy in the screenshot above got a rating of 5.04, it will trade between 350 and 400 times a year). So now I am confirming entries and exits and win/loss percentages live.
@Kevin N, here is the layout I'm using for a run I started just a few days ago with 1 contract while I'm trying out and developing a couple new strategies.

Box labeled "1" will be green for a buy signal, box labeled "2" will be red for a sell signal, box labeled "3" will be yellow for an open position, and box labeled "4" is something new. It works as a "heartbeat", switching between black and purple every time a new bar starts. This allows me to synchronize my script with the chart by sending a signal every time a new bar starts and will help with what is called 'fuzzy logic' that I am working on in my script. The lower left is the binary display for contracts.. Actually I probably should go ahead and move all the label displays to the lower chart. May do that on a future run, but this works for now.

With this layout, I have 2 areas of the screen defined in my script to "watch". The first encompasses the upper four labels and the second encompasses all the lower binary labels.

Layout.jpg


Make the images you are using as reference in your ImageSearch a couple pixels smaller than what is displayed on screen, you can do this by taking a snip of the label on screen and cropping it down to be a couple pixels narrower and shorter. This helps with recognition of the label by removing the border pixels that may be a gradient of the color you are looking for and can cause AutoHotKey to not recognize it.

Note the pixel size of your cropped image to define the ImageSearch.

crop.jpg



I believe someone already mention that you can change the order template to submit a trailing stop at the same time you submit a order incase something happens and you lose contact with the platform.

Decided to switch strategies to one I have been running in my paper trade account on another computer after seeing the thread about SQN theory. I had been using the Thinkscript Strategy Report and Monte Carlo Analysis from http://readtheprospectus.wordpress.com. After reading up on SQN I applied it to the strategy I was paper trading and got a rating of 9.34 which I attribute to it being a high frequency trading strategy that could trade up to 800 times per year. (The strategy in the screenshot above got a rating of 5.04, it will trade between 350 and 400 times a year). So now I am confirming entries and exits and win/loss percentages live.
Hy, what program are you using to select a color and autoclick…? my machine is Mac Ox... what do you recommend?, thank
 
@ChristianS I'm using AutoHotKey, but it's not available for Mac. I've read UI.Vision RPA is a comparable alternative for Mac. I have not used it myself though.
thank you very much, I'll investigate it, thank you for your help I'm not good at programming and I'm a rookie but I'll try to investigate this
 
I have revisited using Vis2 OCR for AHK to read my watch list with a 'P/L Day' column, and have experienced success in setting a profit limit by using an 'if is float' block before my main trading loop. In a given trading day I will call on the OCR thousands of times and have not received any irregular characters/misidentified numbers thus far. In the past I think I was attempting to read characters off of a non-activated window, which I assume was problematic.

@Kevin N I know you have worked tirelessly on your program and have chosen an MACD strategy, but check out this thread and let me know if you see any glaring deficiencies for which this could be used for our purposes.

https://usethinkscript.com/threads/money-maker-script-non-repainting-for-thinkorswim.10067/
 
I have revisited using Vis2 OCR for AHK to read my watch list with a 'P/L Day' column, and have experienced success in setting a profit limit by using an 'if is float' block before my main trading loop. In a given trading day I will call on the OCR thousands of times and have not received any irregular characters/misidentified numbers thus far. In the past I think I was attempting to read characters off of a non-activated window, which I assume was problematic.

@Kevin N I know you have worked tirelessly on your program and have chosen an MACD strategy, but check out this thread and let me know if you see any glaring deficiencies for which this could be used for our purposes.

https://usethinkscript.com/threads/money-maker-script-non-repainting-for-thinkorswim.10067/

@Jonessw1 It looks fine to me, I also have a moving avg strategy, DarvasBox, Heiken Ashi, etc... all built into my script so I can select different strategies on different instruments to see which works best. One of the key things I do to insure there is no repainting is to have all my criteria met on the previous candle... for example, if I simply do something like this....

Code:
switch (strategy) {
case MACD:
    buyCondition       = MACD().Value[offset] crosses above MACD().Avg[offset];
    sellCondition      = MACD().Value[offset] crosses below MACD().Avg[offset];
    buyPriceLong       = open[0];
    buyPriceShort      = open[0];
    stopConditionLong  = low  < stopLossLong;
    stopConditionShort = high > stopLossShort;
    stopPriceLong      = stopLossLong;
    stopPriceShort     = stopLossShort;

With my offset being 1, then the MACD cross took place on the last candle and I'm going long on the current candle open. When you're evaluating the MACD above on the current candle, it may give you a signal to go long/short if the candle is rising/falling, but by the time that candle closes, the cross did not happen. Doing your tests on the previous candle may not make your backtesting as impressive, but it will be far more accurate.

Other things I think are important that affect the profitability of a strategy is the time of day trades are taken/not taken, eg: I go flat before the morning bell and don't allow the strategy to take trades again until, say 10AM. Managing stops are also very important. I have an initial stop when I enter a trade, but once we get to a certain level of profit, my initial stop turns into a trailing stop, and it's based on price action, not necessarily a MACD cross down. I have built in options so I can do things like "don't take a trade unless the current signal is above the last strategy entrance price" if I'm long, or "don't take an entry unless the MACD cross happens and the last bar is above the highest of the previous 10 bars, etc..."

There are lots of things to factor in. I would say start with something basic and build on it... test, test, test.... I tested first with the backtesting built into toss, then I did some paper trading for 3 months to make sure my actual results were matching the backtesting results. I'm now (starting this month) am live with real money but only using 1 MES contract.
 
@Jonessw1 , my thoughts on trading via TOS: "REPAINT". Biggest issue and false backtest results, that look so good but never pan out in real live trading. So I have two different ways I auto-trade: Ninjatrader strategies and a Tradingview to python app that posts trades to Ninjatrader. Since Ninjatrader has autotrading built-in its the most efficient and brutally accurate. Brutal because "you don't always get what you want". the real value in auto-trading is not to let it run full time. Set profit targets or Session PnL to grab x dollars and be done with it. If it continues to run it most likely will evaporate some really nice profit.
 
Thankyou so much @Svanoy
A few weeks ago I came across this thread where you mentioned that you had a way to auto trade with autohotkey and it has got me really excited. I have a full time job so trying to follow my strategy is impossible when I can only trade certain times at work.
 
@Svanoy Hey could you show me how to get started with autohotkey. I've been watching videos but im still really confused about how to even start. My idea is pretty simple, I want the script on a loop, and when ImageSearch sees a buysignal it will press my flatten keybind and then the buy keybind. Then when it sees a sellsignal it will press the flatten keybind and then the sell keybind. Basically just want that in a loop.
Then I have also seen how you added that label that changes colors when the bar changes. How would I add that to my script to make it run smoother? I added it to my tos strategy but dont know how i would add it to autohotkey?
 
@aCuddlyTurtle
Here is the AHK script I currently run. I've tried to go through and comment what each part is for.

The basic logic loop is this:

Upon starting script check current trade signal and record,
Script can also be started if already in long or short trade by starting script with different key combination

-Upon signal change check current trade long or short
-If no position open and sell signal, check number of contracts to run, enter amt, click sell, confirm position open.
-If long position and sell signal then flatten position, confirm no positions open, check number of contracts to run, enter amt, click sell, confirm position open.
-If no position open and buy signal, check number of contracts to run, enter amt, click buy, confirm position open.
-If short position and buy signal then flatten position, confirm no positions open, check number of contracts to run, enter amt, click buy, confirm position open.

Repeat.



Ruby:
#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

;Declaration of variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Delay = 0

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

Clock = 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;windows key + p to pause/unpause
#P::Pause

;windows key + z to start with no positions open
#Z::


;Main subroutine

;Determine current trade signal as to not enter a trade in progress/wait until trade signal changes

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
        }

;Determine the amount of contracts to run(read from label code on screen lower chart)
Goto, ContractCalc

;Loop to check for change in trade signal

Check:

Loop{   

;Check for TeamViewer logout screen and remove (Only needed if using TeamViewer to remote in)
    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)
        {
        }
;Check for Buy Signal
    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
            }
        }
;Check for Sell Signal       
    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
            }
        }     
;ignore   
;If DoubleCheck = 1
;    {
;    Sleep, Delay
;    DoubleCheck = 0
;    Goto, Check
;    }

;Logic to determine what to do upon signal change   

;If currently not in trade and trade signal is Sell
If (UpArrow = 0 and DownArrow = 1)
    {
    If (Buy = 0 and Sell = 0)
        {
;Click Sell Button
;Keybind (currently disabled)
        ;Send +S
;Physical mouse click
        MouseClick, Left, 1580, 125, 1, 0
        MouseClick, Left, 875, 30, 1, 0
        
;track current trade state
        Buy = 0
        Sell = 1       
        ;Sleep, Delay
;confirm trade
        Goto, Confirm
        }
;If in long position and trade signal is Sell   
    Else If (Buy = 1 and Sell = 0)
        {
;Click Flatten Button
        MouseClick, Left, 1818, 125, 1, 0
        MouseClick, Left, 875, 30, 1, 0
                
;track current trade state
        Buy = 0
        Sell = 0
;wait for position to close
        Goto, Wait
        }
    
    }
;If currently not in trade and trade signal is Buy
Else If (UpArrow = 1 and DownArrow = 0)
    {
    if (Buy = 0 and Sell = 0)
        {
;Click Buy Button (disabled)
        ;Send +B
;physical mouse click
        MouseClick, Left, 1495, 125, 1, 0
        MouseClick, Left, 875, 30, 1, 0
;track current trade state
        Buy = 1
        Sell = 0       
        ;Sleep, Delay
;confirm trade
        Goto,Confirm
        }
;If in short position and trade signal is Buy
    Else If (Buy = 0 and Sell = 1)
        {
;Click Flatten Button
        MouseClick, Left, 1818, 125, 1, 0
        MouseClick, Left, 875, 30, 1, 0
;track current trade state       
        Buy = 0
        Sell = 0
;wait for position to close
        Goto, Wait
        }
    
    }

;The rest of this module currently does nothing
;would be used to flatten all positions
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, Wait
        }
    
    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, Wait
        }
    }
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 for label indicating an open position to turn off
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
            }

;#########################################################################################
;Timer module
Clock:

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

Loop{
ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w14 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\Clock.tiff
        If (ErrorLevel = 0 and Clock = 0)
            {
            Goto, Check
            }
        Else If (ErrorLevel = 1 and Clock = 1)
            {
            Goto, Check
            }
}Return
;#########################################################################################
;Confirmation module to check position is open after clicking Buy/Sell
Confirm:

Sleep, 3000

ImageSearch, FoundX, FoundY, 700, 0, 800, 200, *w8 *h17 *TransBlack C:\Users\Home\Desktop\AutoHotKey Images\PositionOpen.tiff
        If (ErrorLevel = 0)
            {
            Goto, Clock
            }
        Else If (ErrorLevel = 1)
            {
            ;Click Cancel Button
            MouseClick, Left, 1660, 125, 1, 0
            MouseClick, Left, 875, 30, 1, 0
            Buy = 0
            Sell = 0
            Goto, Check           
            }

;#########################################################################################
;Calculate number of contracts to run (from onscreen label display)
#C::
ContractCalc:

Sleep,10

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
;move cursor to qty textbox
MouseClick, Left, 1510, 168, 1, 0
;delete current text in textbox
    count = 0
    Loop{
    Send {Delete}
    count := count + 1
    sleep, 10
    } Until count = 5
;input number of contracts to run
    SendInput, %Contracts%
    MouseClick, Left, 750, 250, 1, 0
    MouseClick, Left, 875, 30, 1, 0
    Goto, Check

;################################################################################################
;windows key + b if starting script while already in long trade
#B::
Buy = 1
;OpenBuyOrder = 1
Sell = 0
;OpenSellOrder = 0

Goto, ContractCalc

;#################################################################################################
;windows key + s if starting script while already in short trade
#S::
Buy = 0
;OpenBuyOrder = 0
Sell = 1
;OpenSellOrder = 1

Goto, ContractCalc
 
@Svanoy I appreciate you taking the time to explain your code. could you give me a example of the ImageSearch where it recognizes a buy signal then I would like to move my mouse cursor to a random spot on the screen and click then hit control+b to buy. So what im asking is how to setup a mouse movement click and then a key press.

what is a good program to find mouse cords?
 
Last edited:
@aCuddlyTurtle
Code:
;Key Combo to start script
;windows + s key
#S::

Loop{

;Watch for Buy Signal
ImageSearch, FoundX, FoundY, 0, 0, 1900, 1050, *w23 *h23 C:\Users\Home\Desktop\AutoHotKey Images\BuySignal.tiff

;If found click mouse on random screen location, send ctrl + b key combo.
    If (ErrorLevel = 0)
        {
        MouseClick, Left, 1580, 125, 1, 0
        Send ^{b}
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }

}Return

AHK has coordinate finder built in, listed as Window Spy in Start menu under AHK.

RM0F0rx.png
 
Last edited:
@Svanoy Thats awesome, just what im looking for. So i will need basically 2 ImageSearch and I want to add like a 10ms delay in between the mouse movements and key presses to maybe elimate any errors.
 
@Svanoy How does this look so far? see anything that may cause a error? maybe line 11 "#s"?
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

;Key Combo to start script
;windows + s key
#S

#P :: Pause

Loop{

;Watch for Buy Signal
ImageSearch, FoundX, FoundY, 34, 237, 234, 263, *w24 *h24 C:\Users\Home\Desktop\AutoHotKey Images\BuyLabel.png

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + b key combo.
    If (ErrorLevel = 0)
        {
        MouseClick, Left, 1747, 248, 1, 0
        delay = 10
        Send ^{f}
        delay = 10
        Send ^{b}
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
;Watch for Sell Signal
ImageSearch, FoundX, FoundY, 34, 237, 234, 263, *w24 *h24 C:\Users\Home\Desktop\AutoHotKey Images\SellLabel.png

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + s key combo.
    If (ErrorLevel = 0)
        {
        MouseClick, Left, 1747, 248, 1, 0
        delay = 10
        Send ^{f}
        delay = 10
        Send ^{s}
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }

}Return
 
Need two colons after the #s.
I forgot that in my prior example.
Should be '#s::'.
Also the second image search should not be inside the else statement of the first image search.
 
Last edited:
@Svanoy Hey could you show me how to get started with autohotkey. I've been watching videos but im still really confused about how to even start. My idea is pretty simple, I want the script on a loop, and when ImageSearch sees a buysignal it will press my flatten keybind and then the buy keybind. Then when it sees a sellsignal it will press the flatten keybind and then the sell keybind. Basically just want that in a loop.
Then I have also seen how you added that label that changes colors when the bar changes. How would I add that to my script to make it run smoother? I added it to my tos strategy but dont know how i would add it to autohotkey?

Here's mine, maybe it will give you some ideas. I have a few things like a status bar to tell me if I'm in a trade or not, the amount of trades taken in a given time period and if that is exceeded, set out for x amount of time. Additionally, the feature I found most handy is the one to clear any errors TOS throws up in the middle of the night (eg: performance issues, etc), it will look for those and clear them so the script can keep working.

Code:
; Version Beta .07 - Last Modified: 4/10/2022 12PM.  Added error clearing feature.
; ver .062 .062Added 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

; User Defineable variables
; Use the following to set the vertical and horizontal coordinates for each.
buttonsHorizontal     = 125     ; 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             = 245     ; Vertical Coordinates, middle of button
statusHorizontal     = 120     ; The horizontal setting for the status bar
statusCoord          = 300     ; The vertical setting for the status bar
labelSearchX         = 275     ; How far to the right
labelSearchY         = 275     ; How far down

tradeLimit             = 4     ; 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     = 3600     ; In Seconds, if tradeLimit is reached in this amount of time, sit out resetPeriod
entryDelay             = 120     ; In Seconds, the amount of time that must pass before another entry is allowed
delayTime             = 30     ; In Seconds, the amount of time to wait sleep after buy, short, or flat.
entryPause            = 30    ; In Seconds, the amount of seconds to pause before pressing the buy/sell button.

; 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(60,"Waiting")
^F1:: delayFunction(3600,"Pausing for 1 hour")
^F2:: delayFunction(7200,"Pausing for 2 hours")
^F4:: delayFunction(14400,"Pausing for 4 hours")


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

loop {
    sleep 1000
    a++
    b++
    ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w50 *h15 *10 images\plum.png
    if (ErrorLevel = 0) {
        ;Check to see if we're in a trade.
        status = 1
    }
    if (ErrorLevel = 1) {
        ; if no image found, set status to 0.
        status = 0
    }       
    if (status == 0 and a >= entryDelay) {
        ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w50 *h15 *10 images\white.png
        if (ErrorLevel = 0) {
            ;Click Buy Button if green status and we're not already in a trade
            MouseClick, Left, %buyCoord%, %buttonsHorizontal%, 1, 0
            status = 1
            a = 0
            trades++
            tooltip Status: Buy Image Cords: %FoundX% x %FoundY%, %statusCoord%, %buttonsHorizontal%
            sleep delayTime * 1000
            checkForErrors()
        }
    }   
    if (status == 1) {
        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
            status = 0
            tooltip Status: Flat Image Cords: %FoundX% x %FoundY%, %statusCoord%, %statusHorizontal%
            sleep delayTime * 1000
            checkForErrors()
        }
    }
    if (status == 0 and a > entryDelay) {
        ImageSearch, FoundX, FoundY, 0, 0, %labelSearchX%, %labelSearchY%, *w50 *h15 *10 images\dark_orange.png
        if (ErrorLevel = 0) {           
            ;Click Sell (short)
            MouseClick, Left, %sellCoord%, %buttonsHorizontal%, 1, 0
            status = 1
            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%
    
    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%
    }
    return   
}
 
@Svanoy @Kevin N I'm not sure what is wrong. when I start the script nothing happens. I have one of my labels green to signal a buy but it does nothing. no mouse movement or key strokes.. I have tried to mess with a few things but still no luck. i am using SciTE for my autohotkey. I tried changing my image files to .tiff, i tried to run SciTE and autohotkey in admin mode, removed the delays, etc
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

;Key Combo to start script
;windows + s key
^9::

^0:: Pause


Loop{

;Watch for Buy Signal
ImageSearch, FoundX, FoundY, 25, 226, 239, 272, *w24 *h24 C:\Users\Home\Desktop\AutoHotKey Images\BuyLabel.png

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + b key combo.
    If (ErrorLevel = 0)
        {
        MouseClick, Left, 1747, 248, 1, 0
        delay = 10
        Send ^{f}
        delay = 10
        Send ^{b}
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }
;Watch for Sell Signal
ImageSearch, FoundX, FoundY, 25, 226, 239, 272, *w24 *h24 C:\Users\Home\Desktop\AutoHotKey Images\SellLabel.png

;If found click mouse on random screen location, send ctrl + f key combo, send ctrl + s key combo.
    If (ErrorLevel = 0)
        {
        MouseClick, Left, 1747, 248, 1, 0
        delay = 10
        Send ^{f}
        delay = 10
        Send ^{s}
        }
;If not found do nothing
    Else If (ErrorLevel = 1)
        {
        }

}Return
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
364 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