Auto Trade (ALGO) in TOS

When approaching "auto trading" I too thought of using the api and a third party to place the orders, but then i thought why over complicate things.
My setup isn't complicated, I have a cheap laptop used only to run TOS and the bot, layout of TOS screen can be permanently saved within the platform (save workspace). All I have to do is have TOS open and click run on the bot and it works just fine, I go about my day
Hi Gilgameash,

Do you happen to have any instructions on how to build bot like yours?
 
I was able to convert this code into python auto trading strategy over the weekend. I will test this week and will report back how good the results are. Even if they are half of what they are on TOS should be a profitable stragety.
Can you share any additional information How to do auto trading with TOS API and python,as it's not possible in TOS?.
 
This is a pretty simple "dumb" smart bot its a python based program.
the "bot" works perfectly as i envisioned it.

the only variable is the strategy being used to generate the signals(if you have a good strategy script that doesn't repaint, help a brother out).

how it works is pretty simple, see image on basics works and proof that it does.

daOZ7Zj.png


dNFMCk3.jpg
Looking at the logic I think, that that code can be something like the code below:
Can someone more knowledgeable improve it and make a simple, but working solution?

import pyautogui
from PIL import Image
import pytesseract

# define the position of the buy and flatten buttons
buy_button_position = (x, y)
flatten_button_position = (x, y)

while True:
# take a screenshot of the price chart
im = pyautogui.screenshot()

# use OCR to read the label of the price chart
label = pytesseract.image_to_string(im)
if label == 'BUY':
# move mouse to the buy button and click
pyautogui.moveTo(buy_button_position[0], buy_button_position[1])
pyautogui.click()
elif label == 'Close':
# move mouse to the flatten button and click
pyautogui.moveTo(flatten_button_position[0], flatten_button_position[1])
pyautogui.click()
 
Hi Gilgameash,

Do you happen to have any instructions on how to build bot like yours?
I might just post it here out of boredom... original post explained basic everything. And @NellyN is on the right track (though I'm not sure if the "flatten" option works on 'paper money' or 'OnDemand' for testing)

This is a pretty simple "dumb" smart bot its a python based program.
the "bot" works perfectly as i envisioned it.

the only variable is the strategy being used to generate the signals(if you have a good strategy script that doesn't repaint, help a brother out).

how it works is pretty simple, see image on basics works and proof that it does.

daOZ7Zj.png


dNFMCk3.jpg




pointless update, running the bot on live account for this year trading 500 shares or AAPL with a 80% win rate (100k starting balance) and (116k this weeks closing balance with a Short position open),
might be posing strategy used in correct Forum later.
 
I might just post it here out of boredom... original post explained basic everything. And @NellyN is on the right track (though I'm not sure if the "flatten" option works on 'paper money' or 'OnDemand' for testing)






pointless update, running the bot on live account for this year trading 500 shares or AAPL with a 80% win rate (100k starting balance) and (116k this weeks closing balance with a Short position open),
might be posing strategy used in correct Forum later.

@Gilgameash I can see how you can help community by sharing your bot.
You would get help with testing and further feedback for making improvements.
It is your chance before someone else will come through.
I checked the pyautogui library. There is also a post on YouTube by some who had created similar bot.
Good luck. And thank you for sharing.
 
@Gilgameash I can see how you can help community by sharing your bot.
You would get help with testing and further feedback for making improvements.
It is your chance before someone else will come through.
I checked the pyautogui library. There is also a post on YouTube by some who had created similar bot.
Good luck. And thank you for sharing.
I have already posted a simple code for the task. It needs improvement, of course, but is a good starting point.
Code:
import pyautogui

# define the position of the buy and flatten buttons
buy_button_position = (x, y)
flatten_button_position = (x, y)

while True:
    # check the label of the price chart
    label = pyautogui.locateOnScreen('label.png')
    if label == 'BUY':
        # move mouse to the buy button and click
        pyautogui.moveTo(buy_button_position[0], buy_button_position[1])
        pyautogui.click()
    elif label == 'Close':
        # move mouse to the flatten button and click
        pyautogui.moveTo(flatten_button_position[0], flatten_button_position[1])
        pyautogui.click()


import pyautogui
from PIL import Image
import pytesseract

# define the position of the buy and flatten buttons
buy_button_position = (x, y)
flatten_button_position = (x, y)

while True:
    # take a screenshot of the price chart
    im = pyautogui.screenshot()

    # use OCR to read the label of the price chart
    label = pytesseract.image_to_string(im)
    if label == 'BUY':
        # move mouse to the buy button and click
        pyautogui.moveTo(buy_button_position[0], buy_button_position[1])
        pyautogui.click()
    elif label == 'Close':
        # move mouse to the flatten button and click
        pyautogui.moveTo(flatten_button_position[0], flatten_button_position[1])
        pyautogui.click()
 
Last edited:
I'm taking a different approach but its a work in progress. I'm using the real time account to monitor the strategy. The main issue with TOS is now you see it now you don't until it goes to a solid visual signal. Using higher timeframes help. Using only the "AddOrder" arrows not "buy" signals or other painted arrows helps, I am using an image recognition python app just on the arrows. Friday there wasn't a lot of trades on the 15 min NQ but it did fairly good. I'm also sending the trades to Ninjatrader, they have what is called OIF Order Instruction File that as the trade activates it sends a txt file to a certain folder. NT is watching that folder and activates your order. It all happens in milliseconds. Since using python I could also send the order to TDA-api but the api only allows real trading. Also you can use Interactive Broker TWS api they do allow paper trading. So there are a bunch of ways to do this.
@Gilgameash nice setup, it's some what similar to what @Svanoy is doing with his autohotkey, still it requires a lot of setup on the TOS screen to isolate the text. On my app I need to have TOS visually present but don't need to configure the screen other than in the strategy, to set the arrow colors of the buy and sell and close orders.
Kudos to the auto-traders !!!
EXTREMELY good Idea keep us posted U just may have the work around .
 
@kilowatt39
Post what you've got and I'll take a look.
I changed from using the HullMA ,am now using the RSI with the center line also for entry,problem is when the price keep breaking below and above in a short time its giving me too much signals.Anyway see if you can fix it for me,thanks in advance, The script is a mess but i am using it

Code:
#rsi
input longEntries = yes;
input ShortEntries = yes;
input price = close;
input tradesize = 1;
input StartTrading = 930;
input StopTrading = 1600;
input ShowTodayOnly = {"No", default "Yes"};

def s=ShowTodayOnly;
def today=if s==0 OR getday()==getlastday() AND secondsfromtime(StartTrading)>=0 then 1 else 0;
def t2trade = today and secondsFromTime(StartTrading) > 0 and secondsFromTime(StopTrading)<0  ;


## ema stoploss ##############
input emaStopLoss = yes;
input emaStopLenght = 9;
input emaLongDisplace = 0;
input emaShortDisplace = 0;
def emaX = MovingAverage(AverageType.EXPONENTIAL, close, emaStopLenght);

input rsiStopLoss = yes;
input rsiEntryOffset = 0;
input rsiStopOffset = 0 ;

input length = 14;
input OB = 70;
input OS = 30;
input neutral= 50;
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 VALUE,percent, tick};
input longTarget = 50;
input shortTarget = 50;
input longStop = 50;
input shortStop = 50;
def entryPrice = open;#EntryPrice();
def mult;
switch (offsetType) {
case percent:
    mult =entryPrice / 100;
case value:
    mult = 1;
case tick:
    mult = TickSize();
}

def longstopPrice;
def shortstopPrice;
def longTargetPrice;
def shortTargetPrice;

if high[1] >= shortStopPrice[1]{
    longstopPrice = Double.NaN;
    shortstopPrice = Double.NaN;
    longTargetPrice = Double.NaN;
    shortTargetPrice = Double.NaN;
}else if low[1] <= shortTargetPrice[1]{
    longstopPrice = Double.NaN;
    shortstopPrice = Double.NaN;
    longTargetPrice = Double.NaN;
    shortTargetPrice = Double.NaN;
}else if high[1] >= longTargetPrice[1]{
    longstopPrice = Double.NaN;
    shortstopPrice = Double.NaN;
    longTargetPrice = Double.NaN;
    shortTargetPrice = Double.NaN;
}else if low[1] <= longstopPrice[1]{
    longstopPrice = Double.NaN;
    shortstopPrice = Double.NaN;
    longTargetPrice = Double.NaN;
    shortTargetPrice = Double.NaN;
}else if rsi[1] crosses above over_bought[1] and IsNaN(longstopPrice[1]) {        
    longstopPrice = entryPrice - longstop * mult;
    shortstopPrice = Double.NaN;
    longTargetPrice = entryPrice + longtarget * mult;
    shortTargetPrice = Double.NaN;
}else if rsi[1] crosses below over_sold[1]and IsNaN(shortstopPrice[1]) {  
    longstopPrice = Double.NaN;
    shortstopPrice = entryPrice + shortstop * mult;
    longTargetPrice = Double.NaN;
    shortTargetPrice = entryPrice - shorttarget * mult;
}else{
    longstopPrice = longstopPrice[1];
    shortstopPrice = shortstopPrice[1];
    longTargetPrice = longTargetPrice[1];
    shortTargetPrice = shortTargetPrice[1];}

def long =  rsi[0] crosses above over_bought[0];
def long2 = rsi[0] crosses above neutral ;     
def longStopT = !isnan(longstopprice) and low <= longstopprice;
def longProfit = !isnan(longTargetPrice) and high >= longTargetPrice;

def short =  rsi[0] crosses below over_sold[0] ;
def short2 = rsi[0] crosses below neutral ;
def shortStopT = !isnan(shortstopprice) and high >= shortstopprice;
def shortProfit = !isnan(shortTargetprice) and low <= shortTargetprice;

def OpenOrders = GetQuantity();
def ordfill = OpenOrders > 0 ;
def ordempty = OpenOrders < 1 ;
def orderx; if ordfill {orderx = 1;} else if ordempty {orderx = 0;} else {orderx = orderx[1];}

## Ema Stoploss ######
def emaLongStopT = close crosses below emaX[emaLongDisplace] ;
def emaShortStopT = close crosses above emaX[emaShortDisplace] ;
def emaBelow = emaLongStopT;
def emaAbove = emaShortStopT;
def emaLongStopTrigger = if emaBelow[1] then 1 else 0;
def emaShortStopTrigger = if emaAbove[1] then 1 else 0;

## Rsi Stoploss #######
def rsiLongStopT = rsi crosses below over_bought[rsiStopOffset] ;
def rsiShortStopT = rsi crosses above over_sold[rsiStopOffset];
def rsiBelow = rsiLongStopT;
def rsiAbove = rsiShortStopT;
def rsiLongStopTrigger = if rsiBelow[1] then 1 else 0;
def rsiShortStopTrigger = if rsiAbove[1] then 1 else 0;



#### Orders ####
AddOrder(OrderType.BUY_AUTO, (longEntries) and t2trade and long[-1], price = open[-2], tickcolor = GetColor(6), arrowcolor = GetColor(6), name = "Long Entry", tradeSize= tradesize);
AddOrder(OrderType.BUY_AUTO, (longEntries) and t2trade and long2[-1] , price = open[-2], tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "nLong Entry", tradeSize= tradesize);
AddOrder(OrderType.SELL_TO_CLOSE, t2trade and longStopT[-1], price = longstopPrice[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "Long Stop", tradeSize= tradesize);
AddOrder(OrderType.SELL_TO_CLOSE, t2trade and longProfit[-1], price = longTargetPrice[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "Long Profit", tradeSize= tradesize);
AddOrder(OrderType.SELL_TO_CLOSE, (longEntries)  and t2trade and rsiLongStopT[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "rLong Stop", tradeSize= tradesize);
AddOrder(OrderType.SELL_TO_CLOSE, (longEntries) and (emaStopLoss) and t2trade  and emaLongStopT[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "eLong Stop", tradeSize= tradesize);


AddOrder(OrderType.SELL_AUTO,(ShortEntries) and t2trade and short[-1], price = open[-2], tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "Short Entry", tradeSize= tradesize);
AddOrder(OrderType.SELL_AUTO, (ShortEntries) and t2trade and short2[-1]   , price = open[-2], tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "nShort Entry", tradeSize= tradesize);
AddOrder(OrderType.BUY_TO_CLOSE, t2trade and shortStopT[-1], price = shortstopPrice[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "Short Stop", tradeSize= tradesize);
AddOrder(OrderType.BUY_TO_CLOSE, t2trade and shortProfit[-1], price = shortTargetPrice[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "Short Profit", tradeSize= tradesize);
AddOrder(OrderType.BUY_TO_CLOSE,  (ShortEntries) and t2trade and rsiShortStopT[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "rShort Stop", tradeSize= tradesize);
AddOrder(OrderType.BUY_TO_CLOSE, (ShortEntries) and (emaStopLoss) and t2trade and emaShortStopT[-1], tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "eShort Stop", tradeSize= tradesize);


def LongStopTrigger = t2trade and (!IsNaN(longStopPrice) and IsNaN(longStopPrice[-1]) and IsNaN(shortStopPrice[-1]) and low <= longStopPrice);
def LongTargetTrigger = t2trade and (!IsNaN(longStopPrice) and IsNaN(longStopPrice[-1]) and IsNaN(shortStopPrice[-1]) and high >= longTargetPrice);
def ShortStopTrigger = t2trade and (!IsNaN(shortStopPrice) and IsNaN(shortStopPrice[-1]) and IsNaN(longStopPrice[-1]) and high >= shortStopPrice);
def ShortTargetTrigger = t2trade and (!IsNaN(shortStopPrice) and IsNaN(shortStopPrice[-1]) and IsNaN(longStopPrice[-1]) and low <= shortTargetPrice);


#### Labels ####
AddLabel(yes, "        ", if (longEntries) and t2trade and long[1] or (longEntries) and t2trade and long2[1]  then CreateColor(153, 255, 153) else Color.GRAY);
AddLabel(yes, "        ", if (ShortEntries) and t2trade and short[1] or (ShortEntries) and t2trade and short2[1] then CreateColor(255, 102, 102) else Color.DARK_GRAY);
AddLabel(IsNaN(LongStopTrigger) and !ShortStopTrigger and !ShortTargetTrigger,"        ",Color.WHITE);
AddLabel(!LongStopTrigger and IsNaN(ShortStopTrigger) and !LongTargetTrigger, "        ",Color.WHITE);
AddLabel(IsNaN(LongStopTrigger) and IsNaN(ShortStopTrigger), "        ",Color.WHITE);
AddLabel(LongStopTrigger, "        ", Color.YELLOW);
AddLabel(LongTargetTrigger, "        ", Color.YELLOW);
AddLabel(ShortStopTrigger, "        ",Color.YELLOW);
AddLabel(ShortTargetTrigger, "        ",Color.YELLOW);

AddLabel(yes, "        ", if  emaLongStopTrigger ==1 or rsiLongStopTrigger == 1 then Color.PLUM else if emaShortStopTrigger ==1 or rsiShortStopTrigger == 1 then Color.DARK_ORANGE else Color.PINK);
AddLabel(yes, if orderx == 1 then "        " else "        ", if orderx == 1 then Color.Blue else Color.Magenta);
 
@kilowatt39
Been looking thorough this and it looks like you are basing some of your signals on current bar price movement instead of previous bar.
EX:
Ruby:
def long =  rsi[0] crosses above over_bought[0];
def long2 = rsi[0] crosses above neutral ;     

def short =  rsi[0] crosses below over_sold[0] ;
def short2 = rsi[0] crosses below neutral ;

The snippet above from your code is able to signal multiple times over the course of a bar.
I suggest going through and make sure you are referencing the previous bar when generating signals.
 
Hello @irishgold thank you for the encouragement. Sorry, it is a study from the premium indicator forum so I cannot share the code here. I veered off on a tangent in my previous post anyways. the script utility is AutoHotKey. It allows the ability to define certain parts of the screen to monitor and using a label to indicate buy or sell by color displayed means I only have to monitor a small static section instead of the entire screen. It also works with the computer monitor, mouse, and keyboard disconnected from the computer. It has not missed a single signal.

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

In regards to NT, part of this live run I started back in May, is to see if I can start with the bare minimum cost and investment, build capital, and eventually move up to /ES. Also, since not all trades are winning trades, the less it costs the less it concerns me to lose. Actually lost $180.00 dollars today, but it was money I didn't have a week ago. Low cost and a positive Win/Loss ratio allows me to worry about keeping the program running, and not what it is actually doing at the moment.


Hi, will you share the name of premium indicator forum so that others can go purchase should they desire?
 
Hello everyone,
Just curious if you found a way to automate your TOS trading?
Micro Recorder, AHK, python or other?
Are you paper trading or using solution to trade with real money (day- or swing-trading)?
Thank you
 
I'm using a tool called SAT-daddy. I've been doing both paper and live trading with it; but am currently concentrating on my ThinkScript strategy code to perfect the strategy.
 
Last edited by a moderator:
I'm using a tool called SAT-daddy. I've been doing both paper and live trading with it; but am currently concentrating on my ThinkScript strategy code to perfect the strategy.

Many thanks for your reply,

I went to SAT-daddy website, trying to learn more about that product.

The developer is asking for over $1200 for annual subscription, with listed comment:
Due to the nature of how we implement our proprietary system, there are no refunds or evaluation periods.

Also, what caught my eye, another comment :
By simply adding a few lines of ThinkScript code to your existing strategy, you can make it “SAT-daddy aware“.
We provide complete instructions and even include a sample strategy that is SAT-daddy compatible.


If it is not too much trouble, could you please share some light: :unsure:
  • is the SAT-daddy system monitors and trades only one instrument and/or strategy ?
  • how the SAT-daddy systems integrates with strategy, what script changes are required, given earlier comment?
  • if the SAT-daddy system supports Advanced Orders Trading templates (e.g., OCO, TRG w/bracket,etc)
( where the Advanced Orders are configured?)

Sorry for soo many questions, just trying to understand the SAT-daddy benefits.
Thanks
 
Best to contact the developer directly with these questions. I think there's a contact form on the web site.
 
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
579 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