The full algorithm code that is ready to run is on GitHub.

***Warning: The following code needs access to Polygon tick data therefore if you do not have a funded live trading account through Alpaca you will receive a Warning Code 1000 followed by an error message of “Invalid Polygon Credentials”.***

alpacahq/example-hftish
Example Order Book Imbalance Algorithm. Contribute to alpacahq/example-hftish development by creating an account on GitHub.

Commission Free API Trading Can Open Up Many Possibilities

Alpaca provides commission-free stock trading API for individual algo traders and developers, and now almost 1,000 people hang around in our community Slack talking about many different use cases. Among other things, like automated long-term value investing and Google Spreadsheet trading, high-frequency trading (“HFT”) often came up as a discussion topic among our users.

Is High-Frequency Trading (“HFT”) That Special?

Maybe because I don’t come from a finance background, I’ve wondered what’s so special about hedge funds and HFTs that those “Wallstreet” guys talk about. Since I am a developer who always looks for ways to make things work, I decided to do research and to figure out myself on how I could build similar things to what HFTs do.

I am fortunate to work with colleagues who used to build strategies and trade at HFTs, so I learned some basic know-how from them and went ahead to code a working example that trades somewhat like an HFT style (please note that my example does not act like the ultra-high speed professional trading algorithms that collocate with exchanges and fight for nanoseconds latency). Also, because this working example uses real-time data streaming, it can act as a good starting point for users who want to understand how to use real-time data streaming.

The code of this HFT-ish example algorithm is here, and you can immediately run it with your favorite stock symbol. Just clone the repository from GitHub, set the API key, and go!

$ git clone https://github.com/alpacahq/example-hftish.git  && cd example-hftish
$ export APCA_API_KEY_ID=<your key ID>
$ export APCA_API_SECRET_KEY=<your secret key>
$ python tick_taker.py — symbol=MU
alpacahq/example-hftish
Example Order Book Imbalance Algorithm. Contribute to alpacahq/example-hftish development by creating an account on GitHub.

What It Does

The algorithm watches a “quote level” that is constructed with bid and ask. In liquid stocks, this quote level changes frequently, and there are some studies that the trades tend to break into the direction of the first trade made in a quote level. If you have watched order books with eyeballs, you may have recognized something like it before. Even if you can tell which way the trades would go for a short period of time, it’s hard to act on it with a mouse/mobile interface. But if you are an algorithm, maybe you can get on the direction quicker.

I’ll defer to this academic paper (see below) about the accuracy and predictability of signals as it’s beyond the scope of this post. It can also depend on what stocks you trade as well, so it probably makes sense to check it yourself by running it in live, since the data latency and order filling may matter too.

“Order Imbalance Based Strategy in High Frequency Trading”

Although this example algorithm is named like “HFTish”, it does not act like the ultra-high speed professional trading algorithms that collocate with exchanges and fight for nanoseconds latency. Still, the behavior of this algorithm should be much faster than average manual day traders.

Code Structure

The script consists of less than 300 lines of code and is relatively simple to follow. It uses both REST and streaming interface, one for submitting/canceling orders and one for getting stock quotes/trades update as well as order status changes. The pseudocode is as follows.

def run():
  # setup
  api = REST()
  conn = StreamConn()  @conn.on('Q.' + symbol)
  async defon_quote(conn, channel, data):
    # update quote level
    quote.update(data)  @conn.on('T.' + symbol)
  async def on_trade(conn, channel, data):
    # act on new trade data
    if trade_happens_on_current_bid_or_ask_first_time_on_this_level:
      order = api.submit_order(symbol, side="buy or sell")
      # simulate IOC
      api.cancel_order(order.id)  @conn.on('trade_updates')
  async def on_trade_updates(conn, channel, data):
    # manage inventory
    if order_is_filled:
      position.add() or .remove()

As you can see, by calling @conn.on() decorator on async function, you can set an event handler. In this case, we set separate different event handlers for quote, trade and order updates that do each job upon the event. Easy enough, ha?

The Power of Machine Trading with a Commission Free Broker

The algorithm buys and sells the same stock MANY times in a short period of time. I mean, MANY (I have tested for the last couple of days, and for example, the algorithm traded more than 500 times today!). If you are to pay even $1 commission for each trade, it would deteriorate the total performance when simply calculating the daily commissions you would have to pay. And like I said above, if it was manual trading, you would probably not be able to act up to speed on the trade signals.

Important: There is an industry rule called “Pattern Day Trader” that requires you to maintain a balance of $25k in your account at all times in order to day trade. If your account falls below the $25k requirement, you are not be permitted to day trade until you deposit cash in the account to restore the account to the $25k minimum equity level.

The bottom line is that this is a complete Python trading system with less than 300 lines of code with asyncio introduced as late as Python 3.5, so it is a good baseline for you to learn how to code this type of algorithm. You can fork and customize the algorithm for your own real-time needs, not just running it as-is.

We are always happy to hear your feedback for our trading API and open source code we provide. Feel free to join our community Slack and ask questions!

Alpaca | Algo Trading Commission Free with REST API
Lower your cost, Maximize your profits. Algo trading commission free.

Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC (alpaca.markets), member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

You can find us @AlpacaHQ, if you use twitter.