Reflections of a Day Trading Bot Developer

Ary Sharifian
Jun 20, 2020 · 8 min read

Using Python and a Robinhood API to automate day trading

Image for post
Image for post
Photo by Ishant Mishra on Unsplash

This project is ongoing, but I wanted to take a moment and share the lessons learned. Hopefully any future developer would find this useful before trying to create their own algorithm for automating day trading.

Full disclaimer: this is not meant to represent any financial advice. Any investments you make using the algorithm, strategy, or ideas below is at your own risk. I am not liable for any consequences related to or caused by the information contained in this article.

I created a list of challenges when I was building this algorithm, and I can classify these challenges based on the following categories: technical, financial, and domain knowledge. I will go through each category and the corresponding challenges.

Technical Challenges:

  1. API Latency
  2. Select Stocks
  3. Buy_limit_orders
  4. Sell_limit_orders
  5. Scaling Challenges
  6. Performance Tracking
  7. Recent News
  8. Evolving Robinhood API
  9. Daily Authentication
  10. Outages

API Latency

The performance of your algorithm will necessarily depend on the responsive time of the Robinhood API among other factors including your code. The Robinhood isn’t particularly fast especially certain requests like getting recent news. One complete cycle of my algorithm takes about 30 minutes. Most of 30 minutes is spent filtering for stocks with recent news. Before this, I have to get a list of tradeable stocks on Robinhood. This list is constantly changing.

Besides getting information from the API, it takes time for information on Robinhood to update. This became apparent when I set a limit for purchasing stocks based on the amount of money I had in my account but my algorithm spent more money than I allowed. How? When I purchase a stock, it takes time for Robinhood to process that I’ve purchased a stock and update my account balance. Before my account was properly updated, my algorithm was already considering another stock to purchase. At this time, my algorithm saw that it still has enough money to purchase the stock, but in fact it didn’t. Robinhood didn’t update my account quickly enough. So latency works in both ways not just the request but also the post.

The solution I executed was to include a speed bump before considering another stock for purchase. This isn’t a great solution, but it works for now.

Buy_limit_orders

Just because you entered an order to buy stocks does not mean you have purchased said stocks. In fact, its unlikely that your order is executed immediately. When my algorithm ran it failed to set a sell limit order because this script came directly after my buy limit order. For example, I told Robinhood that I was stock ABC at $10 a share and that this order is “good until canceled” (gtc). GTC means that this order is valid until I cancel the order. Robinhood processes the request but it takes some time before the trade executes. This might be because there aren’t enough shares available at this price or other reasons (read Flash Boys by Michael Lewis).

One solution is to try and set a sell limit order to validate that the stock is purchased. Here, I ran a script that tried to set a sell limit order. If successful, I know the stock is purchased and I set the sell limit order. Otherwise, I would wait until I could set the sell limit order before purchasing other stocks on my list. If you fail this step, you have a bunch of buy limit orders without a sell limit order. As a result, I would have to manually enter the sell limit order for these stocks which defeats the purpose of the algorithm.

Sell_limit_orders

You can only set one limit order on a stock share. Lets say you buy stock ABC for $10, and you want to sell the stock at $10.07. Obviously your expectation is that the stock price increases. But what happens if the stock price goes down? That is why it is a good idea to have a sell strategy baked into your algorithm. I haven’t yet implemented this, but I am going to sell stocks after 1 hour. In other words, if my stock hasn’t reached my target price for profit within the hour, I am going to sell the stock.

This requires you to call an API that cancels your sell limit order and either create a new sell limit order at a lower price or just sell the stock at whatever price. Basically you need to use the API but its more involved than what you may initially think. Honestly, I didn’t really think about a sell strategy until after a couple bad trades.

Scaling Challenges

Okay so my strategy might work with $50 but how about $5,000? Depending on the number of stocks you want to buy or sell, there could be issues filling these orders. I’ve had issues filling orders for 1 share of a stock because the stock was skyrocketing. This is a result of Robinhood and the broker they are using to fill orders as well as the natural volatility of the stock market. In other words, even if your algorithm works well when testing on small amounts of money and shares, you will likely have issues scaling this algorithm. If you found a great stock to trade, its likely that someone else has found this stock too. This, in turn, creates a demand and supply issues which impacts scaling your algorithm.

Performance Tracking

Tracking your algorithm’s performance is tricky given the information available through the API. Currently I am entering my algorithms trades manually into an excel sheet to track performance. You can track the buying power for the account, but this value includes any dividends from stocks owned. Since I already had a portfolio consisting of other stocks, its hard to distinguish these stocks from day trading. It might be useful to think about the different KPIs for your algorithm before writing any code. This way you can write useful helper functions not just for your day trading algorithm but also for any KPIs that you would like to track.

Evolving API

The API I used is called robin_stocks which is a wrapper for the Robinhood API. Basically, robin_stocks makes it easier to use Robinhood. It handles the payload request and json returns. In any case, Robinhood and subsequently robin_stocks is constantly evolving and changing. This could mean that your API requests fail, or you have to update your module to allow your algorithm to execute. Or Robinhood changes their API to require a different payload for execution. This means that robin_stocks needs to update their package to account for this chain. Then there is you, the programmer, that has to recognize this change and update your algorithm. Technical debt and maintenance is something that many don’t think about when embarking on this journey but its important.

Daily Authentication

The Robinhood API authenticates users for 24 hour periods which means that you need to manually update your authentication or find some clever workaround. This is for your protection, but it prevents your algorithm from running longer than a day without intervention. There is a slack community for the Robinhood API wrapper called Robin-Stocks where there is a channel called #login-trouble dedicated to this issue. This is the documentation for the login wrapper. Notice that the “expiresin” parameter is in seconds and lasts 24 hours when converted to hours.

Outages

How will your algorithm respond to API outages? This happens rarely. I can remember 2 instances when Robinhood had outages. Robinhood API availability really isn’t in your control, but how your algorithm responds is. I don’t have a good answer to this problem besides checking other platforms and API offerings. If you are planning to use a significant amount of money in your trades, API availability is paramount.

Financial Considerations

  1. Day Trading Legal Requirements
  2. Generating Real Profit
  3. Taxes on Profit

Day Trading Legal Requirements

If you are considering day trading on Robinhood or any other platform, you are required to have $25K in your account. You can read the exact legal definition here in the Robinhood FAQ. I learned this when my algorithm simply didn’t place a sell limit order on a stock. I realized that Robinhood API stops you from placing the order unless you’ve manually disabled the day-trading protection on Robinhood. This protection is meant to prevent the government from flagging you as a day trader. You can bypass these requirements by holding stocks longer but that defeats the intention behind day trading.

Generating Real Profit

Generating real profit can mean something different to each person. If we defined “real profit” as being able to live comfortably off earnings, then I am skeptical. If “real profit” means paying for groceries, then maybe. I recently calculated that I need to risk $650 to earn about $100 a month. This assumes I am able to generate a %1.007 return each trading day using my entire $650 allocated for day trading. This is not likely. Nevertheless, I will try and likely have a follow-up to this and other articles.

Taxes on Profit

Finally, there is a pretty step tax rate on day trading. This depends on your tax bracket, but the tax rate for day trading is much higher than long term investments. Again, if you are trying to earn a certain amount per month or each day, account for the taxes you owe on the earning. You can find more information here.

Domain Knowledge

  1. Select Stocks
  2. Trading Platforms and Brokers

Select Stocks

Which stocks should you select for purchase? I have no idea. There are different indicators that traders use for buying and selling stocks. From my research it seems that everyone has their own ideas on which are best. I decided to use a simply 20 minute moving average, and filter based on recent news. From a technical standpoint, it really isn’t that difficult to calculate these metrics. What is challenging is determining what might be considered a good strategy. I recommend researching those strategies on your own and writing some pseudocode before beginning.

Trading Platforms and Brokers

Which trading platform and brokers are best for creating a day trading algorithm? I have no idea. This question is really asking who can fill my order quickly and provide me the best information. Free services like Robinhood are criticized for behind last in line to fill an order. Also the metrics might have some lag. In other words, the latest price for stock ABC is 25 seconds behind which might mean you might not make an informed decision about the stock. This could mean it takes longer to fill your order at a specific price point.

There are other API platforms like Alpaca and other brokers like ETrade, but I am not familiar enough or experienced enough to distinguish them. My gut feeling is that Alpaca API faces the same challenges as Robinhood and that unless your are paying for your service, its likely to have the same limitations. For this reason many who use Robinhood are simply buying for the long term and aren’t day trading. This article recommends not day trading on Robinhood.

Conclusion

If there is something I missed, please let me know. I am always changing this article to include the latest major hurdles I faced to build this bot.

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Ary Sharifian

Written by

Oracle DevOps Engineer. The views expressed here are my own and do not necessarily reflect the views of Oracle. https://www.linkedin.com/in/arshya-sharifian/

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Ary Sharifian

Written by

Oracle DevOps Engineer. The views expressed here are my own and do not necessarily reflect the views of Oracle. https://www.linkedin.com/in/arshya-sharifian/

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store