Giter VIP home page Giter VIP logo

futu_algo's Introduction

FutuAlgo Logo

billpwchan/futu-algo API Reference Documentation

Buy Me A Coffee

Codacy Badge

Issues License LastCommit CommitActivity WorkflowStatus RepoSize Languages

Highlights

  • Supported Platforms and Markets

    Futu_algo is a algorithmic trading solution developed based on FutuOpenD and FutuOpenAPI. Fully support FutuNiuNiu and FutuMooMoo users in Hong Kong stock market. (More market support is coming soon)

  • Historical K-Line Data

    Allow users to automatically downloading historical data for your interested stocks into CSV and storing to SQLite database for backtesting. (up to 1M level for max. 2 years, or 1D level for max. 10 years)

  • Backtesting Trading Strategies (BETA)

    Backtest your own trading strategies on historical data with a summarized reports and visualizations using Pyfolio. For more demanding users, feel free to other commercial solutions such as Amibroker for backtesting.

  • Algorithmic Trading

    Real-time low-latency trading features that allows applying your own basket of trading strategies on your stock pool. User can specify the trading strategy to be used for each stock based on their preference.

    EXAMPLE: 0.01s/STOCK TO DECIDE BUY/SELL ORDER WITH A 3-TECHNICAL INDICATORS STRATEGY (MACD, KDJ AND CLOSE PRICE)

  • Advanced Stock Screener

    Screens high-quality stocks using your own stock screening strategies, and notify your friends using the email subscription feature. Feel free to subscribe by submitting this Google Form! https://forms.gle/C9y4kyYUArKmFzu86

  • Trading Strategy Editor

    Write your own trading strategy following a simple template (buy, sell, calculate technical indicators). Common strategies such as MACD and KDJ-based trading rules are provided as guidelines.

  • GUI Support (Upcoming)

    Easy-to-use GUI for users to adjust their configurations, trading, downloading data and filtering stocks within one application. No longer need to type any command for trading!

Version Guidance

FutuAlgo Release Futu OpenAPI Specification
1.0 6.1

Deployment

Pre-Requisite: Configuration File (Config.ini)

[FutuOpenD.Config]
Host = <OpenD Host>
Port = <OpenD Port>
WebSocketPort = <OpenD WebSocketPort>
WebSocketKey = <OpenD WebSocketKey>
TrdEnv = <SIMULATE or REAL>

[FutuOpenD.Credential]
Username = <Futu Login Username>
Password_md5 = <Futu Login Password Md5 Value>

[FutuOpenD.DataFormat]
HistoryDataFormat = ["code","time_key","open","close","high","low","pe_ratio","turnover_rate","volume","turnover","change_rate","last_close"]
SubscribedDataFormat = None

[TradePreference]
LotSizeMultiplier = <# of Stocks to Buy per Signal>
MaxPercPerAsset = <Maximum % of Capital Allocated per Asset>
StockList = <Subscribed Stocks in List Format>

[Backtesting.Commission.HK]
FixedCharge = <Fixed Transaction Fee and Tax in HKD - 15.5>
PercCharge = <Percentage Transaction Fee in % - 0.1097>

[Email]
Port = <Server SMTP Setting>
SmtpServer = <Server SMTP Setting>
Sender = <Sender Email Address - [email protected]>
Login = <Sender Email Address - [email protected]>
Password = <Sender Email Password>
SubscriptionList = ["[email protected]", "[email protected]"]

[TuShare.Credential]
token = 2134342ABC2D03780772038A7816

IMPORTANT NOTE: The format may be changed in later commits. Please refer to this README if exception is raised.

1. Install Dependencies

Install using conda:

conda env create -f environment.yml

To export current environment, use the following command

conda env export > environment.yml

To update current environment with the latest dependencies, use the following command

conda env update --name futu_trade --file environment.yml --prune

For GitHub Actions - with pip dependencies, use the following command

pip list --format=freeze > requirements.txt

2. Install FutuOpenD

For Windows/MacOS/CentOS/Ubuntu:

https://www.futunn.com/download/OpenAPI

Please do make sure that you have at least a LV1 subscription level on your interested quotes. For details, please refer to https://openapi.futunn.com/futu-api-doc/qa/quote.html

MAKE SURE YOU LOGIN TO FUTU OPEND FIRST BEFORE STARTING FUTU_ALGO!

4. Download Data (e.g. 1M Data for max. 2 Years)

For Windows:

python main_backend.py --force_update

For MacOS/Linux:

python3 main_backend.py --force_update

4. Enjoy 😄

Command-line Interface Usages

Historical Data Download & Processing

Update all K_1M and K_DAY interval historical K-line data

python main_backend.py -u   /   python main_backend.py --update

IMPORTANT NOTE: This will not override existing historical data if the file exists. It will automatically detect the latest stock data you have downloaded in the folder and resume from there.

If you want to refresh all data, use the following command instead (WITH CAUTION!)

python main_backend.py -fu   /   python main_backend.py --force_update

Algorithmic Trading

Execute Algorithmic Trading with a Pre-defined Strategy (By default use 1M data)

python main_backend.py -s MACD_Cross   /   python main_backend.py --strategy MACD_Cross

If you would like to use another time interval based date (e.g., Day data), use the following command

python main_backend.py -s MACD_Cross --time_interval K_DAY

If you do not have a pre-defined stock list in config.ini, then you can just trade the Top 30 HSI stocks

python main_backend.py -s MACD_Cross --include_hsi --time_interval K_DAY

IMPORTANT NOTE: The supported time intervals are: K_1M, K_30M, K_5M, K_15M, K_30M, K_60M, K_DAY, K_WEEK, K_MON, K_YEAR.

Stock Filtering and Email Subscription

Execute Stock Filtering with Pre-defined Filtering Strategies with Email Title "MACD_Cross_Technique" in HK and China (Shanghai and Shenzhen) Stock Market

python main_backend.py -f Volume_Threshold Price_Threshold -en MACD_Cross_Technique -m HK CHINA

GUI Usages

Start the GUI with main.py (NOT FINISHED YET)

python main.py

Future Plans


Contributor

Bill Chan -- Main Developer

Disclaimer

Futures, stocks and options trading involves substantial risk of loss and is not suitable for every investor. The valuation of futures, stocks and options may fluctuate, and, as a result, clients may lose more than their original investment. The impact of seasonal and geopolitical events is already factored into market prices. The highly leveraged nature of futures trading means that small market movements will have a great impact on your trading account and this can work against you, leading to large losses or can work for you, leading to large gains.

If the market moves against you, you may sustain a total loss greater than the amount you deposited into your account. You are responsible for all the risks and financial resources you use and for the chosen trading system. You should not engage in trading unless you fully understand the nature of the transactions you are entering into and the extent of your exposure to loss. If you do not fully understand these risks you must seek independent advice from your financial advisor.

All trading strategies are used at your own risk.

Any content in this repository should not be relied upon as advice or construed as providing recommendations of any kind. It is your responsibility to confirm and decide which trades to make. Trade only with risk capital; that is, trade with money that, if lost, will not adversely impact your lifestyle and your ability to meet your financial obligations. Past results are no indication of future performance. In no event should the content of this correspondence be construed as an express or implied promise or guarantee.

This repository and its author are not responsible for any losses incurred as a result of using any of our trading strategies. Loss-limiting strategies such as stop loss orders may not be effective because market conditions or technological issues may make it impossible to execute such orders. Likewise, strategies using combinations of options and/or futures positions such as “spread” or “straddle” trades may be just as risky as simple long and short positions. Information provided in this correspondence is intended solely for informational purposes and is obtained from sources believed to be reliable. Information is in no way guaranteed. No guarantee of any kind is implied or possible where projections of future conditions are attempted.

futu_algo's People

Contributors

billpwchan avatar codacy-badger avatar timontr 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

futu_algo's Issues

Use GitHub Actions to send daily filtered stock list to subscribers

Hi,

Would be nice to have a feature that sets up a cron job in Github Actions to process all stocks using a pre-defined strategy and send out the daily selected stocks to subscribers. The subscribers can simply include their name in a list or comment them in GitHub and you can setup a workflow to automatically update that list on a daily basis.

Let me know what's your thought! 😊

Create a new thread for placing buy/sell orders

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
After receiving the data, use another thread with timeout to place buy/sell orders.

Describe alternatives you've considered
N/A

Additional context
N/A

Support for Options Trading Strategies

Is your feature request related to a problem? Please describe.
N/A

Describe the solution you'd like
It would be better if futu_algo can support Options Trading Strategies such as bull call spread in addition to the existing spot trading

Describe alternatives you've considered
Interactive Brokers might have a more mature solution for US market, but for HK stock market, it would be easier to just develop a simple options trading engine from scratch.

FileNotFoundError

Describe the bug
FileNotFoundError: [Errno 2] No such file or directory: 'D:\Users\admin\Documents\Python\futu_algo-master\data\Stock_Pool\ListOfSecurities.csv'

How to execute main_backend.py or setup.py files? and how to configure

Describe the bug
When execute the main_backend.py file,it return:

usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help

error: no commands supplied

the setup.py --help does not work

what is the cmds, may i have the example of the parameters

if possible, we can use Chinese to communicate

ERROR — Cannot subscribe to K-Line: No right to subscribe

Hi there. I'm trying to run the main_backend.py but I keep getting an error:

ERROR — Cannot subscribe to K-Line: No right to subscribe 00001

I have a subscription quota of 300 according to OpenD and subscription status query also shows 300:

INFO — Query Subscription Quota: {'total_used': 0, 'remain': 300, 'own_used': 0, 'sub_list': {}}

Does anyone know why this might be the case?

Any advice appreciated. Thanks.

  • Futu version 7.1.3308

Support LV2 / LV1 Data Subscription Plan in HK Stock Market

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
Currently, the script only works if the user buys Lv2 data subscription card with 318HKD / Month. However, if the IP address is from Mainland China, FuTu automatically grant Lv1 data subscription without extra cost. However, we don't have Orderbook and some other features comparing with Lv2.

Need to update the solution and another configuration field in Config.ini to indicate which data subscription plan is used.

Describe alternatives you've considered
No

Additional context
No

Calculate Close Price Slope

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Stock Data Custom Interval

When converting 1M stock data to any time interval greater than 60M, it creates discrepancy between the generated file & actual file due to the non-trading hours.

For instance, for 1H interval, the suggested key timestamps are

  1. 9:30
  2. 10:30
  3. 11:30
  4. 12:00 -> Creating issue because the difference is only 30M between this one as the previous timestamp

Need to update the logic to support this types of conversion using 1M-based stock data.

Data Processing API + Pathlib Refactor

  1. Remove all dependencies in trading_engine.py, and move all data processing scripts into data_engine.py
  2. Use Pathlib instead of file path string for cross-platform support.

Use Parquet instead of CSV for better performance

  1. Refactor the code so all the I/O related operations are encapsulated in data_engine
  2. Convert CSV to Parquet with 2X saving in file size...Amazing
  3. Create a utility function for ppl who've already downloaded historical data in CSV format, and they can easily use the utility function to convert all CSV to Parquet ease.

Stock Selector based on Technical Indicators

Is your feature request related to a problem? Please describe.
Nah

Describe the solution you'd like
Update HFT Stock Pool based on a separate stock selector (using primarily Yahoo Finance data).

Describe alternatives you've considered
Support other data sources such as Google Finance or other paid subscribed data source.

Additional context

ADX & RSI Trading Strategy

ADX & RSI Strategy based on the following specification

ADXdays=Optimize("ADXdays",10,5,25,5);
ADXlimit=Optimize("ADXlimit",25,10,50,5);
RSI_threshold = Optimize("RSILimit",20,5,100,5);

Buy= RSI(2) < RSI_threshold AND ADX(ADXdays)>ADXlimit ;
buyPrice=Close;

Sell= C>Ref(H,-1);

futu algo error occurred

deployment futu_algo step by step , but when execute , exception occured. how to fix? thanks
(base) /home/xiaoming/anaconda3/bin/python3 main.py
Please rename stock_strategy_map_template.yml to stock_strategy_map.yml and update it.
Traceback (most recent call last):
File "/home/xiaoming/develop/futu_algo/main.py", line 31, in
from engines import *
File "/home/xiaoming/develop/futu_algo/engines/init.py", line 22, in
from .order_engine import *
File "/home/xiaoming/develop/futu_algo/engines/order_engine.py", line 21, in
from futu import ModifyOrderOp, OpenHKTradeContext, OpenQuoteContext, OrderStatus, OrderType, RET_OK,
ImportError: cannot import name 'ModifyOrderOp' from 'futu' (/home/xiaoming/anaconda3/lib/python3.9/site-packages/futu/init.py)

Support for Email / SMS / WhatsApp

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
When we have a buy/sell signal, send an Email / SMS/ WhatsApp Message to clients

Describe alternatives you've considered
Nah

Additional context
Nah

Paper trading?

Hello

Great project you've got here! I believe Futu provides support for paper trading, Does this support paper trading though?

Filter Stocks based on Fundamental Stats

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
So currently, the strategy might lead to incorrect buy decisions for some stocks with tiny transaction volumes (e.g., a sudden large buy from funds will cause the technical indicators to suddenly satisfy the condition of the buy strategy). It is better to filter out these less healthy stocks in our stocks pool before starting the high-frequency trading

Describe alternatives you've considered
May be implemented before the trading starts or after the trading starts.

Additional context
Nah

Data Inconsistency

It seems some stock's data aren't correct when I downloaded them. For instance, for stock HK.01997, the 1M data I downloaded isn't consistent with the one I observed in the Futu client. Gotta use data validator to ensure all data are correct before backtesting.

Switch from StockQuoteHandlerBase to RTDataHandlerBase

StockQuote Handler Base will push a message to subscriber everytime the price is changed.
RTData Handler Base will push a message every 1 minute.

To use strategies like MACD crossover, it is better to use RTDat than StockQuote which is less sensitive in real-time.

Per-Stock Strategy Subscription

For each stock, use a different strategy defined in a mapping file. This is based on the observation that no single strategy can be suitable for all different types of stocks. This mapping file should be built based on backtesting results.

Data Validator

Create a data validator to ensure all downloaded data are correct. Use futu openAPI to retrieve trading days and trading day type, then validate the number of entry

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.