How I Created a Forex, Crypto, Stocks and Options trading Bot
Updated: Jun 24, 2020
Here I'll try to write a post that explains my latest project, giving enough detail for those interested, and not lose readers due to boredom. Making a bot that does all the work of looking through charts, attempting best entry/exit points, and making plays that match my investment plan and risk tolerance was a really exciting project... at least for me.
Read More: The Magic of Selling Options Premiums
What does the bot do?
Gathers Data: Gets charts data of all currency pairs and stocks I follow. Right now the bot watches everything in the S&P 500, along with a few others I'm interested in with particularly high Options trading volume.
Analysis: Runs indicator analysis on every chart. For example, 50-day and 200-day moving averages, trend slopes, etc.
Training: I mark historical points on each chart where I would have bought or sold a stock to train the bot on my preferences and risk tolerance.
Alerts: As the bot learns my patterns, it suggests buy/sell signals every day for all stocks in my watchlist.
Trades: Setting the bot in AutoTrade mode automatically buys and sells based on the training it has learned in point 3. It also has stop loss and trailing stop loss mechanisms built in.
Scours: The entire Options market is interrogated in real-time to report back only Options plays which meet my criteria. I particularly focus in covered calls; you can read more about my Options strategy here.
How I got started
A couple courses I took from the online MBA program from Quantic got me thinking more about statistical analysis of the "random walk" (meaning totally random zig-zagging) that is the stock market. Around the same time I was experiencing some substantial re-valuations of various currency accounts while very frequently using the currency exchange app Revolut.
I thought I might be able to take advantage of all these tools along with my app development experience to automate forex and stock trades. I wasn't thinking about Crypto at the time, and generally consider it a highly-speculative gamble rather than an investment, but eventually Crypto came along for the ride too.
For me, Statistics was the most challenging course in the Quantic MBA and there is a lot to unpack there, but the main statistics elements in this project are Time Series Analysis, Two-Variable Statistical Analysis and Multiple-Regression Analysis.
Time Series Analysis: Used for standard chart trends such as moving averages.
Two-Variable Statistical Analysis: Useful for predictions based on two arrays of data, such as all x and y points on a chart, including an assessment of the model's accuracy/error.
Multiple-Regression Analysis: This boils down to throwing a large dataset with many inputs and a single output into a model, then scoring any new input data within that model to predict an output. Multiple-Regression Analysis is key to Machine Learning, which is one of many elements of AI.
There are a handful of APIs available to get historical Currency Pair and Stock charts.
Currency Pairs: I used CurrencyConverterApi.com and 1Forge. Both were simple, easy-to-use, and at the time were free. There is still a free version at CurrencyConverterApi.com, but 1Forge has since gone to a paid subscription. There are many others out there.
Stocks: BarChart.com has a free API for historical charts, and for "real-time" quotes I use Robinhood.com API, which is also what the bot uses to execute Stock and Options trades.
Once I gather the historical chart data, I run time series and two-variable analysis on the charts to return moving averages and other trend lines, slopes of those, and slopes of the slopes (a different kind of derivative...), etc. The analysis data is stored in an Azure SQL server so we don't need to repeatedly gather and re-compute. For hundreds of charts and thousands of data points and calculations for each, a lot of compute power is required, so let's just do all that once, store it, and move on.
Building a training model is the next step in Machine Learning.
For every point on every chart, there are a handful of analyses done, which are stored in a dataset as mentioned above. As they say, hindsight is 20/20, and if you're like me, you often look at a chart and can easily determine points in the past where you would have either entered or exited a position. Those hindsight entry/exit points are what you're training the bot to learn and later determine for real-time data.
It is not the point on the chart, or even other points around it, but rather the technical analysis dataset at your entry/exit training points that is scored and recorded in the training model. In this bot's case, the score is what is statistically considered a categorical or dummy variable - either Strong Buy, Weak Buy, Strong Sell, Weak Sell, or Hold.
Essentially, you're training the bot on your behavior, your intentions, ideal trades, and your risk tolerance based on the history that is played out on any given chart.
For the developers reading this post, Microsoft has a Machine Learning library called ML.NET that makes all of this analysis not only possible, but very easy. Again, ML is just a fancy wrapper for statistical analysis, so I'd recommend at least having a basic statistics background before jumping into ML.
Now that you have a "trained" dataset, here's where the Multiple-Regression Analysis comes in. Using the Forex APIs and the RobinHood API, real-time quotes are retrieved by the bot.
Technical analysis is done again on each respective chart, which now include the latest data points.
That latest data point's technical analysis for each of your charts is dropped into the trained model. Then Machine Learning (Multiple-Regression Analysis) scores all the new input data, ranking it by how close the technical analysis of the new input data fits within your categorical outcomes from the trained data of either Strong Buy, Weak Buy, Strong Sell, Weak Sell, or Hold.
I have found that it is not enough to simply train the bot on when to buy and sell. You must also give the bot some affirmative data points indicating that you might have bought or sold at certain point (indicating some degree of uncertainty), and you would Hold at other data points, as opposed to just not training the bot on a point you would hold.
Once your new input data is tested against the trained model, it is ranked in terms of strongest Buy and Sell indicators. At this point, you need to tell the app how much cash you want the bot to auto-trade with, or to not do any auto-trading at all, and just alert you of its predictions.
For auto-trading stocks, Robinhood's API makes it relatively easy to execute trades through your own account. In my case, at the beginning of each day, I execute the top three Buy predictions and the top three Sell predictions, if the prediction is in fact scored above a confidence level, which can be set by the user.
I had also set this up to work 24 hours a day on Cyrpto symbols, so theoretically if I were a Crypto trader, it could be doing micro-trades very rapidly as it makes predictions against the technical analysis in real-time.
For trading currencies, I use Revolut, which does not have a public API. So this means I had to set up a virtual instance of a mobile device running the Revolut app, then program a sequence of mouse clicks and keyboard strokes to execute trades through the app as though it were a human sitting at a computer doing it manually. It's an ugly solution in our modern world, but it works, and of course only breaks when Revolut rolls out an app update that changes the layouts and workflows of the app. :)
Here's my favorite part, and where Options trading starts happening. Admittedly, there's nothing too fancy in terms of ML or AI happening here.
The app grabs the entire set of options chains for all stocks on my watch list, and runs risk/reward analysis on every single option, then returns the results sorted by highest ROI and filtered by my risk vs. reward thresholds.
This saves hours of poking through a trading platform, researching one symbol at a time, one options chain at a time, and doing a handful of risk/reward calculations of my own outside of the platform. Within seconds, the app completes many hours worth of research, and doesn't miss anything I might have missed if researching manually.
If you'd like to learn more about my options trading strategy, it's here.
Just like above in the "Trade" section of the post, the bot can automatically pick the best results of the analysis and execute the trades through the Robinhood API.
Note: I currently have auto-trading Options disabled. I'd like to build some more rules into the app based on my Options trading strategy i.e. Underlying stock price thresholds, diversification rules, volatility limits, probability of profit thresholds, selling Covered Calls only on up-days and selling Naked Puts only on down-days, increasing/limiting the position in the underlying stock equity, etc.
A Fun Project
A lot of passion went into this project, and naturally I'm excited to share what I've learned through it all. Along the way, quite a few people have asked if they could use it, if I was planning to make it commercially available, and even have gone so far as to say they would give me a chunk of their own cash to throw at it.
I'm not there yet... this was a personal project born out of my interest in the financial markets, statistics, machine learning and AI. It was a great learning experience.
That said, I'd love to share more about it to anyone who is interested, has more questions about the details, or wants to try building a bot of their own! Get in touch with me any time!
This bot is now a very active part of my FIRE (Financial Independence / Retire Early) toolkit. It's not just a concept... it's actually working, and I'm loving the results.
Trading in general, and specifically Options trading invites a lot of risk. At this point, my earnings goal is 1.215% per week (can anyone guess why?), which substantially beats out almost any other "consistent" investment ROI I have found. So far, the bot is exceeding that goal, but to be fair it has not weathered a bear market yet.
In a few years, I hope to write another blog post entitled "The Bot that helped me to FIRE" to discuss the results while I'm enjoying a very, very early retirement.
Read More: FIRE Through Crisis