GithubHelp home page GithubHelp logo

alpacahq / example-hftish Goto Github PK

View Code? Open in Web Editor NEW
719.0 36.0 234.0 62 KB

Example Order Book Imbalance Algorithm

Python 100.00%
finance trading trading-algorithms alpaca python nats-streaming python3 numpy orderbook real-time

example-hftish's Introduction

Example HFT-ish Algorithm for Alpaca Trading API

The aim of this algorithm is to capture slight moves in the bid/ask spread as they happen. It is only intended to work for high-volume stocks where there are frequent moves of 1 cent exactly. It is one of the trading strategies based on order book imbalance. For more details about it, please refer to Darryl Shen, 2015 or other online articles.

This algorithm will make many trades on the same security each day, so any account running it will quickly encounter PDT rules. Please make sure your account balance is well above $25,000 before running this script in a live environment.

This script also presents a basic framework for streaming-based algorithms. You can learn how to write your algorithm based on the real-time price updates.

Setup

This algorithm runs with Python 3.6 or above. It uses Alpaca Python SDK so make sure install it beforehand, or if you have pipenv, you can install it by

$ pipenv install

in this directory.

API Key

In order to run this algorithm, you have to have Alpaca Trading API key. Please obtain it from the dashboard and set it in enviroment variables.

export APCA_API_KEY_ID=<your key id>
export APCA_API_SECRET_KEY=<your secret key>

Run

$ python ./tick_taker.py

The parameters are following.

  • --symbol: the stock to trade (defaults to "SNAP")
  • --quantity: the maximum number of shares to hold at once. Note that this does not account for any existing position; the algorithm only tracks what is bought as part of its execution. (Default 500, minimum 100.)
  • --key-id: your API key ID. (Can also be set via the APCA_API_KEY_ID environment variable.)
  • --secret-key: your API key secret. (Can also be set via the APCA_API_SECRET_KEY environment variable.)
  • --base-url: the URL to connect to. (Can also be set via the APCA_API_BASE_URL environment variable. Defaults to "https://paper-api.alpaca.markets" if using a paper account key, "https://api.alpaca.markets" otherwise.)

The algorithm can be stopped at any time by sending a keyboard interrupt CTRL+C to the console. (You may need to send two CTRL+C commands to kill the process depending where in the execution you catch it.)

Note

Please also note that this algorithm uses the Polygon streaming API with Alpaca API key, so you have to have a live trading account setup. For more details about the data requirements, please see Alpaca documentation.

example-hftish's People

Contributors

dependabot[bot] avatar ttt733 avatar umitanuki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

example-hftish's Issues

Authorization Issue

Could be something silly, but I keep receiving an authorization issue when running tick_taker.py.

Traceback (most recent call last): File "/root/anaconda3/lib/python3.6/site-packages/nats/aio/client.py", line 285, in connect yield from self._process_connect_init() File "/root/anaconda3/lib/python3.6/site-packages/nats/aio/client.py", line 1556, in _process_connect_init raise NatsError("nats: " + err_msg.rstrip('\r\n')) nats.aio.errors.NatsError: nats: 'Authorization Violation'

I've tried entering my key and secret on both the commandline as arguments to the python script, and setting them as environment variables. The key and secret exactly match what I see in the web interface.

Any ideas?

Trade Updates

Question on this part of the algorithm:

        if event == 'fill':
            if data.order['side'] == 'buy':
                position.update_total_shares(
                    int(data.order['filled_qty'])
                )
            else:
                position.update_total_shares(
                    -1 * int(data.order['filled_qty'])
                )
            position.remove_pending_order(
                data.order['id'], data.order['side']
            )

I'm wondering if it should really be:

        if event == 'fill':
            if data.order['side'] == 'buy':
                position.update_filled_amount(
                   data.order['id'], int(data.order['filled_qty']),
                   data.order['side']
                )
            else:
                position.update_filled_amount(
                   data.order['id'], int(data.order['filled_qty']),
                   data.order['side']
                )
            position.remove_pending_order(
                data.order['id'], data.order['side']
            )

Because, I believe, a PARTIALLY_FILLED order can then become FILL order once it is fully filled. Any thoughts or do I have that incorrect?

Updated for API v2?

Could this please be updated to work with the new API. I am a novice and have addressed the errors that initially came up, but now when I run the script, it does nothing.

The program is running, but no actions are taking place. I have left it running for several hours and nothing happens. I eventually terminated with a keyboard interrupt.

TIA

Authorization Violation

Hi,

I keep getting this error when I run it:

Traceback (most recent call last):
File "/home/alpaca/.alpaca/lib/python3.7/site-packages/nats/aio/client.py", line 244, in connect
yield from self._process_connect_init()
File "/home/alpaca/.alpaca/lib/python3.7/site-packages/nats/aio/client.py", line 1325, in _process_connect_init
raise NatsError("nats: " + err_msg.rstrip('\r\n'))
nats.aio.errors.NatsError: nats: 'Authorization Violation'

This happens even after generating fresh credentials.

Interrupt script

Hi,

I haven't tried to run this yet, but just something I noticed in the README:

It mentions stopping the script with a CTRL-Z interrupt, but wouldn't that just continue the process in the background? Did you mean CTRL-C?

Again, haven't even tried to run it, just an observation that could be very dangerous if correct in this context.

Thanks,
Ryan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.