Michael Brown
9 min readJul 5, 2018

Using Python and TradingView.com to create a functional tradebot

I would like to preface this post by thanking tradingview.com for providing such a robust platform. While they have their own scripting language and Partnerships with various brokers, the method I used to trade is not supported by their platform which forced me to find a way to interface their website with a third party platform, in this case I utilized metatrader as it’s the most widely supported brokerage interface however it should be noted that this technique could be utilized for just about anyting.

The why

I’m a day trader. Everyday I set up tradingview alerts so that I can actively watch a basket of currencies and indexes, I use a custom set of both purchased and finely-tuned widely available indicators. Rather than this post being about the indicators and strategies I utilize for my Trading I would rather focus on the reasoning behind automating it.

I don’t have a day job currently, so I have a large amount of free time to sit around and stare at charts and focus on potential opportunities. However as every trader knows the biggest disadvantage to trading is one’s own emotions. Even the most professional Traders have trouble determining entry and exit levels without programmatic assistance, in addition it’s very easy to gain bias on a trade and putting your emotions aside from this bias can be the biggest aspect as to whether a Trader is successful.

I’ve been writing trading applications for many years, and one of my favorite pastimes is optimizing trading strategies and then unleashing them for forward testing. I’ve had mixed results in the past but I’m not going to sit here and claim that my trading robots have made me a millionaire, on the contrary I’ll go on a limb to say that the majority of the code I’ve produced has lost money rather than gained money. The conclusion I’ve come to regarding this fact is not that I have ineffective trading strategies or that I’ve coded or optimized the application incorrectly, but rather hinges on the simple fact that Market conditions are too dynamic for any single optimization model to succeed.

In my journey here I’ve used everything from machine learning, purchased trading Bots and even worked directly with mathematicians to develop quantitative analysis strategies in an effort to adapt to evolving market conditions. Suffice it to say the conclusion I came to was that without a team of active researchers no amount of pre position programming can guarantee high-level results. To that end I went back to the drawing board and began studying fundamental analysis so that I may begin understanding how to programmatically incorporate it into my algorithmic Trading.

Tradingview as a programtic interface

I’ve been using tradingview.com for many years, it has presented itself as the best interface for the average person to proceed with learning indicators and fundamental analysis through a web-based platform. It should be noted that my primary strength lies in the technical analysis area, while I understand other types of analysis it’s always made more sense to me to look at technical analysis and make a decision. To that end nothing presents more effective in technical analysis then the optimization of particular indicators. Without delving too deep into what indicators are or why they’re used I will suffice it to say that an indicator allows for At a Glance readings or signals for a price action to be determined programmatically.

Platforms such as metatrader, ninjatrader and jigsaw, and others allow for the custom inclusion of indicators both programmed and free provided. Indicators alone do not make a good Trader but they are certainly the first step to providing a mathematical or programmatic model for trade set ups to your average user. Optimization of indicator parameters can often be the first step toward algorithmic or quantitative Trading.

Tradingview.com offers a selection of both free and paid indicators and to be honest their selection of free indicators are extremely powerful. If a person knows what they’re doing it’s entirely possible to create a programmatic interface using nothing other than free indicators provided by tradingview.com.

Tradingview Alets

Tradingview.com offers a plethora of free and paid indicators not to mention the ones you can opt into via third-party. It’s important to understand that the fundamental nature of creating a trading bot the way I have relies on your ability to pick and choose a basket of currencies and to set up the proper alerts for each currency

Tradingview alerts are not perfect. Like any visual programmatic indicator they allow you to set a plethora of conditions to determine when you want to be notified. Unfortunately there are deep limitations in terms of setting up an indicator for simple parameters such as cross up or cross down. Applications such as metatrader and ninjatrader allow you to allow you to customize the parameters of your programmatic indicators. However the difficulty in a bot around indicator which you otherwise understand visual appearance of, is that you need to understand the mathematical implications and effects of the indicator on the given price action.

The very first step in the creation of my application was the decision to rely on the visual application and optimization of indicators on a given currency pair. this differs from the fundamental approach that I and others have taken up until this point, at least to my knowledge. The reason this method is so different is because instead of understanding the quantitative analysis presented to me by the web interface of tradingview.com, I’m instead relying on my personal ability to read visual indicators, be it Trend oscillation or volume indicators. There’s a few specific indicators that I’ve grown very comfortable with over my time Trading and it’s very easy for me to decide via alert what type of price action is happening.

On normal day I receive something about 20 to 40 separate alerts across my basket of currencies and to act quickly to take advantage of the change of trend and momentum I have to be peeled to a computer and ready to initiate a trade. After years of doing it it’s obvious that I would grow tired, in addition to my weariness regarding this method of trading I’ve also found myself costing precious opportunities by playing in to trade setups with my emotions, be it closing too early or allowing a trade to go on too long.

Removing the human factor

It began is a simple idea. I realized that tradingview alerts allow a person to email and SMS notify themselves with a custom description message. It got me thinking maybe it’s possible to create an application which monitors the email inbox said alerts are being sent to, and take some kind of action based on the descriptive text. Now I’m not the best programmer in the world, I would describe myself as intermediate level when it comes to python and this is due to many years of web development and a bit of dabbling in machine learning. All the same I cracked open pycharm and got to work on creating an IMAP wrapper to read my Gmail account for a specific set of instructions from a specific source:

https://gist.github.com/slapglif/c86e3639173831f7395320af2a29bc6d

As you can see the goal here is to watch the email server every 1.5 seconds, read the email subject for a specific phrase in this case tradingview, then parse the contents. The actual email contents contain the description set up in tradingview.com and should read something along the lines of

EURUSD Sell

Upon receiving those instructions the read mail function then calls our trade function, which was previously initialized with a connection to the metatrader interface. I’m actually skipping over my method of connecting metatrader which was to say the library zmq because I want to stress that this method could interface with literally any application that runs zmq or a similar communication Library allowing it interface with python.

In metatrader we had to write a small server which can communicate with python, and it requires a specific format for the trade signal. Below you can see how we handled communicating to the metatrader trade server with this simple function:

https://gist.github.com/slapglif/b84ce24d4dfe5002b0b2d30b655b60a1

After the trade starts

Anyone who’s programmatically traded understands that this is not the end-all in creating an application to trade for you. It’s obvious that this pot could be considered dumb. The reason behind this is that it does not utilize any form of advanced features to determine support and resistance levels, it doesn’t use an adjustable lot size which in my opinion should pretty much always be based on the average true range, and it obviously Lacks programmatic stop loss and take profit functions. I could lie to you and say that I plan to develop those things in the future and add them to this python interface but the fact is I utilize metatrader and what they call Expert advisors to programmatically determine all of those things on the application layer rather than inside of my python tradebot. why? Because there’s a limited amount of interface available when it comes to communicating via and external library with a program like metatrader as there is no official API beyond the language mql which they have designed.

During forward testing I found that I actually don’t need a lot of bells and whistles, the only application that I ended up using for the past 30 days of successfully trading with this application is a trailing stop mechanism. I’ve found that as long as you know what you’re doing when you optimize the parameters of your indicators on tradingview.com it’s pretty easy to create a scalp trade, swing trade or even momentum trade application depending on how fine-tune optimized a trailing stop is.

Results thus far

Honestly they have been mixed. I’m trading with an extremely low lot size and I’m not doing demo Trading (crazy right?)

Also I happen to be a margin Trader, I trade with 100x Leverage on a basket of currencies and indexes. A lot of my friends have considered me insane for being so risky but the truth of the matter is this particular account I consider somewhat Monopoly money and therefore I don’t mind utilizing an automatic trading robot to either gain or lose all of the money on it, and let’s be real the ideal circumstances that I’m a good enough developer to turn it into millions right?

Here’s a small excerpt of some of my results, bear in mind that you shouldn’t trust everything you see on the internet and these are just some screenshot Snip-Its from my email so don’t take what I have to say is Gospel, but rather I hope that these results encourage you to do better than I have.

Note collateral value is in Bitcoin trading on a broker called simplefx:

As you can see there’s a few lost trades and some floating profit / loss because no portfolio in the entire history of man traded without drawdown, also keep in mind that this is just one snippet from one day and I chose this particular one because it looks great. I’ll be the first one to admit that my drawdown is somewhere around 60 to 70% and I’m looking forward to creating a statistical model to display on my follow-up article. Suffice it to say this application has a lot of potential for both profit and loss.

Going forward

In my next post I plan to detail the alterations I’ve made to improve this application, these improvements include the possible application of machine learning in the optimization of my indicator parameters, as well as adding more Dynamic features to the python end of the trading application to allow for dynamic stop loss and take profit rather than allowing myself to rely on the outdated metatrader interface. Last but not least I plan on releasing a small plug-in for the top three major trading platforms so that anybody can get started with this stuff.

I had posted the first version of this to get help for posterity and anybody here is free to use or improve upon the code I simply asked you don’t judge my amateur programming skills as this is literally just the proof-of-concept and I will be adding to it as time goes on.

https://github.com/slapglif/tv-mt4

(edited to include the new version, with logging and error catching)

And to those of you who do end up finding some sort of used with this application the only thing I ask is that you either comment here or on the GitHub itself so that I have an idea where people might want me to go with this application in the future, if anyone at all.

Michael Brown

Software Architect, SRE, and technologist (maybe a robot from the future also)