All Projects → alpacahq → Example Scalping

alpacahq / Example Scalping

A working example algorithm for scalping strategy trading multiple stocks concurrently using python asyncio

Programming Languages

python
139335 projects - #7 most used programming language
python3
1442 projects

Projects that are alternatives of or similar to Example Scalping

roq-samples
How to use the Roq C++20 API for Live Cryptocurrency Algorithmic and High-Frequency Trading as well as for Back-Testing and Historical Simulation
Stars: ✭ 119 (-55.43%)
Mutual labels:  trading-bot, market-data, algorithmic-trading
Zvt
modular quant framework.
Stars: ✭ 1,801 (+574.53%)
Mutual labels:  trading-bot, algorithmic-trading, fintech
Finta
Common financial technical indicators implemented in Pandas.
Stars: ✭ 901 (+237.45%)
Mutual labels:  algorithmic-trading, fintech, algotrading
Quantdom
Python-based framework for backtesting trading strategies & analyzing financial markets [GUI ]
Stars: ✭ 449 (+68.16%)
Mutual labels:  algorithmic-trading, fintech, algotrading
Iex Api
The IEX API provides any individual or academic, public or private institution looking to develop applications that require stock market data to access near real-time quote and trade data for all stocks trading on IEX.
Stars: ✭ 683 (+155.81%)
Mutual labels:  api, fintech, market-data
Peregrine
Detects arbitrage opportunities across 131 cryptocurrency exchanges in 50 countries
Stars: ✭ 638 (+138.95%)
Mutual labels:  trading-bot, algorithmic-trading, algotrading
Tai
A composable, real time, market data and trade execution toolkit. Built with Elixir, runs on the Erlang virtual machine
Stars: ✭ 264 (-1.12%)
Mutual labels:  trading-bot, algorithmic-trading, fintech
Roq Api
API for algorithmic and high-frequency trading
Stars: ✭ 132 (-50.56%)
Mutual labels:  trading-bot, algorithmic-trading, market-data
Algotrading
Algorithmic trading framework for cryptocurrencies.
Stars: ✭ 249 (-6.74%)
Mutual labels:  trading-bot, algorithmic-trading, algotrading
Lstm Crypto Price Prediction
Predicting price trends in cryptomarkets using an lstm-RNN for the use of a trading bot
Stars: ✭ 136 (-49.06%)
Mutual labels:  trading-bot, algorithmic-trading, algotrading
Fastapi Crudrouter
A dynamic FastAPI router that automatically creates CRUD routes for your models
Stars: ✭ 159 (-40.45%)
Mutual labels:  api, async, asyncio
Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+14726.97%)
Mutual labels:  api, async, asyncio
Fastapi Gino Arq Uvicorn
High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (w/ Redis and PostgreSQL).
Stars: ✭ 204 (-23.6%)
Mutual labels:  api, async, asyncio
TradeBot
Crypto trading bot using Binance API (Java)
Stars: ✭ 292 (+9.36%)
Mutual labels:  trading-bot, market-data
py-investment
Extensible Algo-Trading Python Package.
Stars: ✭ 19 (-92.88%)
Mutual labels:  fintech, algorithmic-trading
futu algo
Futu Algorithmic Trading Solution (Python) 基於富途OpenAPI所開發量化交易程序
Stars: ✭ 143 (-46.44%)
Mutual labels:  trading-bot, fintech
intrinio-realtime-python-sdk
Intrinio Python SDK for Real-Time Stock Prices
Stars: ✭ 79 (-70.41%)
Mutual labels:  fintech, market-data
quick trade
convenient script for trading with python.
Stars: ✭ 63 (-76.4%)
Mutual labels:  trading-bot, algorithmic-trading
Twitchio
TwitchIO - An Async Bot/API wrapper for Twitch made in Python.
Stars: ✭ 268 (+0.37%)
Mutual labels:  api, async
TraderBot
No description or website provided.
Stars: ✭ 39 (-85.39%)
Mutual labels:  trading-bot, market-data

Concurrent Scalping Algo

This python script is a working example to execute scalping trading algorithm for Alpaca API. This algorithm uses real time order updates as well as minute level bar streaming from Polygon via Websockets (see the document for Polygon data access). One of the contributions of this example is to demonstrate how to handle multiple stocks concurrently as independent routine using Python's asyncio.

The strategy holds positions for very short period and exits positions quickly, so you have to have more than $25k equity in your account due to the Pattern Day Trader rule, to run this example. For more information about PDT rule, please read the document.

Dependency

This script needs latest Alpaca Python SDK. Please install it using pip

$ pip3 install alpaca-trade-api

or use pipenv using Pipfile in this directory.

$ pipenv install

Usage

$ python main.py --lot=2000 TSLA FB AAPL

You can specify as many symbols as you want. The script is designed to kick off while market is open. Nothing would happen until 21 minutes from the market open as it relies on the simple moving average as the buy signal.

Strategy

The algorithm idea is to buy the stock upon the buy signal (20 minute moving average crossover) as much as lot amount of dollar, then immediately sell the position at or above the entry price. The assumption is that the market is bouncing upward when this signal occurs in a short period of time. The buy signal is extremely simple, but what this strategy achieves is the quick reaction to exit the position as soon as the buy order fills. There are reasonable probabilities that you can sell the positions at the better prices than or the same price as your entry within the small window. We send limit order at the last trade or position entry price whichever the higher to avoid unnecessary slippage.

The buy order is canceled after 2 minutes if it does not fill, assuming the signal is not effective anymore. This could happen in a fast-moving market situation. The sell order is left indifinitely until it fills, but this may cause loss more than the accumulated profit depending on the market situation. This is where you can improve the risk control beyond this example.

The buy signal is calculated as soon as a minute bar arrives, which typically happen about 4 seconds after the top of every minute (this is Polygon's behavior for minute bar streaming).

This example liquidates all watching positions with market order at the end of market hours (03:55pm ET).

Implementation

This example heavily relies on Python's asyncio. Although the thread is single, we handle multiple symbols concurrently using this async loop.

We keep track of each symbol state in a separate ScalpAlgo class instance. That way, everything stays simple without complex data structure and easy to read. The main() function creates the algo instance for each symbol and creates streaming object to listen the bar events. As soon as we receive a minute bar, we invoke event handler for each symbol.

The main routine also starts a period check routine to do some work in background every 30 seconds. In this background task, we check market state with the clock API and liquidate positions before the market closes.

Algo Instance and State Management

Each algo instance initializes its state by fetching day's bar data so far and position/order from Alpaca API to synchronize, in case the script restarts after some trades. There are four internal states and transitions as events happen.

  • TO_BUY: no position, no order. Can transition to BUY_SUBMITTED
  • BUY_SUBMITTED: buy order has been submitted. Can transition to TO_BUY or TO_SELL
  • TO_SELL: buy is filled and holding position. Can transition to SELL_SUBMITTED
  • SELL_SUBMITTED: sell order has been submitted. Can transition to TO_SELL or TO_BUY

Event Handlers

on_bar() is an event handler for the bar data. Here we calculate signal that triggers a buy order in the TO_BUY state. Once order is submitted, it goes to the BUY_SUBMITTED state.

If order is filled, on_order_update() handler is called with event=fill. The state transitions to TO_SELL and immediately submits a sell order, to transition to the SELL_SUBMITTED state.

Orders may be canceled or rejected (caused by this script or you manually cancel them from the dashboard). In these cases, the state transitions to TO_BUY (if not holding a position) or TO_SELL (if holding a position) and wait for the next events.

checkup() method is the background periodic job to check several conditions, where we cancel open orders and sends market sell order if there is an open position.

It exits once the market closes.

Note

Each algo instance owns its child logger, prefixed by the symbol name. The console log is also emitted to a file console.log under the same directory for your later review.

Again, the beautify of this code is that there is no multithread code but each algo instance can focus on the bar/order/position data only for its own. It still handles multiple symbols concurrently plus runs background periodic job in the same async loop.

The trick to run additional async routine is as follows.

    loop = stream.loop
    loop.run_until_complete(asyncio.gather(
        stream.subscribe(channels),
        periodic(),
    ))
    loop.close()

We use asyncio.gather() to run all bar handler, order update handler and periodic job in one async loop indifinitely. You can kill it by Ctrl+C.

Customization

Instead of using this buy signal of 20 minute simple moving average cross over, you can use your own buy signal. To do so, extend the ScalpAlgo class and write your own _calc_buy_signal() method.

    class MyScalpAlgo(ScalpAlgo):
        def _calculate_buy_signal(self):
            '''self._bars has all minute bars in the session so far. Return True to
            trigger buy order'''
            pass

And use it instead of the original class.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].