HFT-like Trading Algorithm in 300 Lines of Code You Can Run Now

Hitoshi Harada
Jan 28, 2019 · 5 min read
Image for post
Image for post
Photo by @andreuuuw

Commission Free API Trading Can Open Up Many Possibilities

Image for post
Image for post

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

$ 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

What It Does

Image for post
Image for post
“Order Imbalance Based Strategy in High Frequency Trading”

Code Structure

def run():
# setup
api = REST()
conn = StreamConn()
@conn.on('Q.' + symbol)
async def on_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()

The Power of Machine Trading with a Commission Free Broker


Image for post
Image for post

Automation Generation

News and thought leadership on the changing landscape of…

Hitoshi Harada

Written by

CTO/CoFounder @AlpacaHQ (YC W19) the API-first brokerage for algorithmic trading and developers (https://alpaca.markets)

Automation Generation

News and thought leadership on the changing landscape of automated investing. Changing the market one algorithm at a time.

Hitoshi Harada

Written by

CTO/CoFounder @AlpacaHQ (YC W19) the API-first brokerage for algorithmic trading and developers (https://alpaca.markets)

Automation Generation

News and thought leadership on the changing landscape of automated investing. Changing the market one algorithm at a time.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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