├── .github └── workflows │ ├── build-and-deploy-docs.yml │ └── test.yml ├── .gitignore ├── .gitmodules ├── Makefile ├── README.md ├── environment.yml ├── poetry.lock ├── pyproject.toml ├── scraper ├── README.md ├── config.json └── secrect.env ├── scripts └── update-deps.sh ├── source ├── _static │ ├── custom.css │ ├── custom.js │ ├── how-to-create-algorithmic-trading-strategy.png │ ├── how-to-invest.png │ ├── logo-dark.svg │ ├── logo-light.svg │ ├── logos │ │ ├── binder.png │ │ ├── colab.png │ │ ├── ethereum.png │ │ ├── pandas.png │ │ ├── plotly.png │ │ ├── pyarrow.png │ │ └── python.png │ ├── plotly-shim-test.html │ ├── require.min.js │ ├── styles │ │ └── README.txt │ └── trading-strategy-fee-structures.png ├── _templates │ ├── autosummary │ │ ├── README.md │ │ ├── base.rst │ │ ├── class.rst │ │ └── module.rst │ ├── base.html │ ├── module-ta.rst │ ├── page.html │ └── sidebar │ │ ├── brand.html │ │ └── search.html ├── api │ ├── client │ │ └── index.rst │ ├── execution │ │ └── index.rst │ ├── index.rst │ ├── technical-analysis │ │ ├── candles │ │ │ └── index.rst │ │ ├── cycles │ │ │ └── index.rst │ │ ├── index.rst │ │ ├── momentum │ │ │ └── index.rst │ │ ├── overlap │ │ │ └── index.rst │ │ ├── performance │ │ │ └── index.rst │ │ ├── statistics │ │ │ └── index.rst │ │ ├── trend │ │ │ └── index.rst │ │ ├── volatility │ │ │ └── index.rst │ │ └── volume │ │ │ └── index.rst │ └── web3.rst ├── architecture │ ├── architecture.rst │ ├── cli.rst │ ├── deployment-overview.drawio.svg │ ├── index.rst │ ├── serialisation.rst │ ├── strategy-types.rst │ ├── unit-testing.rst │ └── webhook.rst ├── conf.py ├── deployment │ ├── backtest-vs-live-execution.rst │ ├── docker-image.drawio.svg │ ├── docker-images.rst │ ├── hot-wallet-deployment.rst │ ├── index.rst │ ├── lagoon-vault.rst │ ├── live-trading.rst │ ├── metadata.rst │ ├── monitoring.rst │ ├── repair.rst │ ├── trade-executor.rst │ ├── troubleshooting.rst │ ├── vault-deployment.rst │ ├── velvet-portfolio.rst │ └── wallet-operations.rst ├── getting-started.rst ├── glossary.rst ├── home.rst ├── index.rst ├── landing-page-splash.png ├── learn.html ├── learn │ ├── additional-resources.rst │ ├── ai-and-machine-learning.rst │ ├── algorithmic-trading-frameworks.rst │ ├── books.rst │ ├── charting-solutions.rst │ ├── communities.rst │ ├── conference-presentations.rst │ ├── courses.rst │ ├── index.rst │ ├── influencers.rst │ ├── jupyter-notebook.rst │ ├── liquidity-provision.rst │ ├── papers.rst │ ├── posts │ │ └── portfolio-construction │ │ │ ├── Portfolio construction - Rebalance(1).svg │ │ │ ├── equity-curve.png │ │ │ ├── portfolio-construction-model.rst │ │ │ ├── portfolio-construction-strategy.svg │ │ │ ├── position-table.png │ │ │ ├── rebalance.svg │ │ │ ├── state.svg │ │ │ └── summary-stats-example.png │ ├── python.rst │ └── tutorials.rst ├── notes.txt ├── overview │ ├── about.rst │ ├── index.rst │ ├── market-data-feeds.rst │ ├── oracles.rst │ ├── supported-markets.rst │ └── tooling.rst └── programming │ ├── code-examples │ ├── candle-chart-example.ipynb │ ├── dataset-download.rst │ ├── getting-started.ipynb │ ├── index.rst │ ├── interactive-charts.ipynb │ ├── lending-market-summary.ipynb │ ├── liquidity-analysis.ipynb │ ├── low-fee-pairs.ipynb │ ├── pairs.ipynb │ ├── plotting-old.ipynb │ ├── pool-liquidity.ipynb │ ├── price-impact.ipynb │ ├── technical-analysis.ipynb │ ├── uniswap-v3-data.ipynb │ └── xsgd-json-lines.ipynb │ ├── development.rst │ ├── example-trading-strategies.rst │ ├── index.rst │ ├── market-data │ ├── candle-format.rst │ ├── client.rst │ ├── good-trading-pairs.rst │ ├── index.rst │ ├── internal-id.rst │ ├── profitability.rst │ ├── reference-price.rst │ ├── token-tax.rst │ ├── tracking.rst │ ├── trading-pairs.rst │ └── wrapped-tokens.rst │ ├── setting-up-development-environment │ ├── binder-example.png │ ├── binder │ │ ├── binder-api-key.png │ │ ├── binder-development.rst │ │ ├── binder-download.png │ │ └── binder-run.png │ ├── codespaces │ │ └── index.rst │ ├── dev-container │ │ ├── backtesting-period.png │ │ ├── cloning-examples.png │ │ ├── command-line-python.png │ │ ├── dev-container-building.png │ │ ├── git-clone.png │ │ ├── new-termianl.png │ │ ├── open-folder.png │ │ ├── open-in-dev-container.png │ │ ├── project-tree.png │ │ ├── run-all-results.png │ │ ├── run-all.png │ │ ├── visual-studio-code-docker-dev-container-for-jupyter-notebooks.rst │ │ └── vscode-splash.png │ ├── docker-development-image │ │ ├── add-new-interpreter.png │ │ ├── docker-development-image.rst │ │ ├── docker-image.png │ │ ├── jupyter-configuration.png │ │ ├── jupyter-selector.png │ │ ├── pycharm-result.png │ │ ├── remote-interpreter.png │ │ └── run-all.png │ ├── google-colab.rst │ ├── index.rst │ ├── local-python.rst │ ├── pycharm │ │ ├── add-existing-interpreter.png │ │ ├── api-key.png │ │ ├── configure-python.png │ │ ├── index.rst │ │ ├── interpreter.png │ │ ├── managed-server.png │ │ ├── open.png │ │ ├── poetry-interpreter.png │ │ ├── poetry.png │ │ ├── project-interpreter.png │ │ ├── restart-jupyter.png │ │ ├── result.png │ │ ├── run.png │ │ ├── running.png │ │ ├── search-python.png │ │ ├── trust.png │ │ ├── trusted.png │ │ └── which.png │ └── vscode.png │ └── troubleshooting.rst └── trading_strategy_docs ├── __init__.py ├── sphinx_render_patch.py └── sphinx_sitemap_patch.py /.github/workflows/build-and-deploy-docs.yml: -------------------------------------------------------------------------------- 1 | # Publish the static Sphinx build on Trading Strategy server using rsync 2 | name: Docs build 3 | 4 | on: 5 | push: 6 | branches: [ master ] 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build-and-deploy-docs: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v3 15 | - name: Fetch git submodules 16 | run: make update-git-submodules 17 | - name: Install poetry 18 | run: pipx install poetry==1.8.3 19 | - name: Set up Python 3.11 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.11' 23 | - name: Install dependencies 24 | run: | 25 | sudo apt update 26 | sudo apt install -y pandoc 27 | poetry env use '3.11' 28 | poetry install -vv 29 | 30 | # TODO: Hack fix if this is the cause for problems in doc builds 31 | - name: Build documentation 32 | run: | 33 | poetry env use '3.11' 34 | python -V 35 | which python 36 | echo $PATH 37 | VENV_BIN=`poetry env info -p`/bin 38 | PYTHON=`poetry env info -p`/bin/python 39 | PIP=`poetry env info -p`/bin/pip 40 | SPHINX=`poetry env info -p`/bin/sphinx-build 41 | PATH=$VENV_BIN:$PATH 42 | make pip-force-install-deps 43 | make install-furo 44 | make rebuild-furo 45 | make clean-autosummary 46 | make html 47 | 48 | # https://zellwk.com/blog/github-actions-deploy/ 49 | # https://github.com/webfactory/ssh-agent 50 | - name: Install SSH Key 51 | uses: webfactory/ssh-agent@v0.5.4 52 | with: 53 | # PK key pair generated locally and 54 | # public SSH key copied to the server 55 | ssh-private-key: ${{ secrets.RSYNC_KEY }} 56 | - name: Publish docs via rsync 57 | run: | 58 | echo "Running $RSYNC_COMMAND" 59 | $RSYNC_COMMAND 60 | env: 61 | # RSYNC_COMMAND="scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -r docs/build/html docs@poly:." 62 | RSYNC_COMMAND: ${{ secrets.RSYNC_COMMAND }} 63 | - name: Run Docsearch Scraper 64 | uses: celsiusnarhwal/typesense-scraper@v2 65 | with: 66 | # The secret containing your Typesense API key. Required. 67 | api-key: ${{ secrets.TYPESENSE_API_KEY }} 68 | 69 | # The hostname or IP address of your Typesense server. Required. 70 | host: ${{ secrets.TYPESENSE_HOST }} 71 | 72 | # The port on which your Typesense server is listening. Optional. Default: 8108. 73 | port: 443 74 | 75 | # The protocol to use when connecting to your Typesense server. Optional. Default: http. 76 | protocol: https 77 | 78 | # The path to your DocSearch config file. Optional. Default: docsearch.config.json. 79 | config: ./scraper/config.json 80 | 81 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test docs build 2 | 3 | on: 4 | push: 5 | branches: [ dev* ] 6 | 7 | jobs: 8 | test-docs-build: 9 | # Use paid faster Github Actions runner 10 | runs-on: 11 | group: Beefy runners 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v3 15 | - name: Fetch submodules 16 | run: make install-deps 17 | - name: Install poetry 18 | run: pipx install poetry 19 | - name: Set up Python 3.9 20 | uses: actions/setup-python@v3 21 | # If caches were enabled, it was caching Python 3.8 interpreter 22 | # causing the docs build to fails 23 | with: 24 | python-version: 3.9 25 | - name: Install dependencies 26 | run: | 27 | sudo apt update 28 | sudo apt install -y pandoc 29 | poetry env use '3.9' 30 | poetry install -vv 31 | - name: Build documentation 32 | run: | 33 | poetry env use '3.9' 34 | python -V 35 | which python 36 | echo $PATH 37 | PYTHON=`poetry env info -p`/bin/python 38 | SPHINX=`poetry env info -p`/bin/sphinx-build 39 | make install-furo 40 | make rebuild-furo html 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .DS_Store 3 | .ipynb_checkpoints 4 | build/** 5 | .vscode 6 | .pytest_cache 7 | .cache 8 | 9 | # Old autosummary 10 | _autosummary 11 | 12 | # All autosummary API documentation is put under folder named help 13 | help/ 14 | 15 | # Must be build from deps/furo 16 | source/_static/styles/furo.css 17 | 18 | # Pycharm 19 | .idea 20 | 21 | # Generated by reredirect plugin 22 | source/**.html 23 | 24 | _tags 25 | dist -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/furo"] 2 | path = deps/furo 3 | url = https://github.com/tradingstrategy-ai/furo.git 4 | ignore = dirty 5 | 6 | [submodule "deps/trade-executor"] 7 | path = deps/trade-executor 8 | url = https://github.com/tradingstrategy-ai/trade-executor.git 9 | ignore = dirty -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Make Trading Strategy docs 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= -j auto 7 | 8 | # # Full tracebacks 9 | # SPHINXOPTS ?= -T -j 1 10 | 11 | SPHINXBUILD ?= poetry run sphinx-build 12 | SOURCEDIR = source 13 | BUILDDIR = build 14 | 15 | # Put it first so that "make" without argument is like "make help". 16 | help: 17 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 18 | 19 | # Open locally build docs in a web browser 20 | browser-docs-macos: 21 | open build/html/index.html 22 | 23 | # Fetch submodules 24 | install-deps: 25 | git submodule update --init --recursive 26 | 27 | # Fetch submodules and check out trade-executor master 28 | update-git-submodules: 29 | git submodule set-url deps/furo https://github.com/tradingstrategy-ai/furo.git 30 | git submodule set-url deps/trade-executor https://github.com/tradingstrategy-ai/trade-executor.git 31 | git submodule update --init --recursive 32 | # git clone --recursive https://github.com/tradingstrategy-ai/trade-executor.git deps/trade-executor 33 | 34 | poetry-install: 35 | poetry install 36 | 37 | # TODO: Some hacks here because Poetry does not pick up right 38 | # packages always so that docs would get correctly built 39 | pip-force-install-deps: 40 | # pip install -e "deps/trade-executor/deps/trading-strategy[direct-feed]" 41 | # pip install -e "deps/trade-executor/deps/web3-ethereum-defi[data]" 42 | #pip install -e "deps/trade-executor[qstrader,execution,web-server]" 43 | #pip install backtrader 44 | echo "X" 45 | 46 | 47 | # Get Webpack tool chain to build Furo theme 48 | install-furo: 49 | (cd deps/furo && npm install) 50 | 51 | 52 | # Makefile hack, Sphinx build does something weird 53 | build-html: 54 | $(SPHINXBUILD) -M html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) 55 | 56 | # Rebuild furo.css 57 | rebuild-furo: 58 | (cd deps/furo && npm run build) 59 | cp deps/furo/src/furo/theme/furo/static/styles/furo.css source/_static/styles/ 60 | 61 | # Recreate environment, update all to the latest, clean any generated files and rebuild HTML docs 62 | clean-install-and-build-local-docs: update-git-submodules poetry-install pip-force-install-deps install-furo rebuild-furo clean-autosummary clean build-html 63 | 64 | # Clean problematic autosummary leftovers from local tree. 65 | # We use folder "help" as the slug for API docs 66 | # TODO: maybe change this 67 | clean-autosummary: 68 | -find source -iname "help" -exec rm -rf {} \; 2>/dev/null 69 | 70 | .PHONY: help Makefile 71 | 72 | # Catch-all target: route all unknown targets to Sphinx using the new 73 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 74 | %: Makefile 75 | $(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Docs build](https://github.com/tradingstrategy-ai/docs/actions/workflows/build-and-deploy-dcos.yml/badge.svg)](https://github.com/tradingstrategy-ai/docs/actions/workflows/build-and-deploy-dcos.yml) 2 | 3 | # Trading strategy documentation 4 | 5 | Documentation for [Trading Strategy algorithmic trading framework and protocol](https://tradingstrategy.ai/). 6 | View [the documentation here](https://tradingstrategy.ai/docs). 7 | 8 | # About documentation internals 9 | 10 | - The documentation is built on the top of [Sphinx documentation toolchain](https://www.sphinx-doc.org/en/master/) 11 | - [Furo based theme is used](https://github.com/tradingstrategy-ai/furo) (the theme has been modified) 12 | - [API documentation is generated with sphinx-autodoc-typehints](https://github.com/tox-dev/sphinx-autodoc-typehints) 13 | - [Interactive Jupyter notebook examples are generated with nbsphinx](https://nbsphinx.readthedocs.io/) 14 | - [The documentation is self-hosted using Caddy](github.com/tradingstrategy-ai/proxy-server/) 15 | 16 | # Building locally 17 | 18 | [pyproject.toml](./pyproject.toml) is automatically pulling the master version of the packages. 19 | 20 | To build everything from the scratch: 21 | 22 | ```shell 23 | poetry shell 24 | 25 | # If needed 26 | brew install pandoc 27 | 28 | # This is a very long duration command. 29 | # For the subsequent documenation updates, 30 | # it is enough to run 31 | # make html 32 | make clean-install-and-build-local-docs 33 | ``` 34 | 35 | Then you can open `build/html/index.html` in your local web browser: 36 | 37 | ```shell 38 | open build/html/index.html 39 | ``` 40 | 41 | See [Makefile](./Makefile) for more recipes. 42 | 43 | # Updating theme 44 | 45 | [See theme README](https://github.com/tradingstrategy-ai/furo). 46 | 47 | To update Furo SCSS changes: 48 | 49 | ```shell 50 | 51 | make rebuild-furo clean html 52 | ``` 53 | 54 | # Community 55 | 56 | * [Trading Strategy website](https://tradingstrategy.ai) 57 | 58 | * [Blog](https://tradingstrategy.ai/blog) 59 | 60 | * [Twitter](https://twitter.com/TradingProtocol) 61 | 62 | * [Discord](https://tradingstrategy.ai/community#discord) 63 | 64 | * [Telegram channel](https://t.me/trading_protocol) -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | # MyBinder integration 2 | name: trading-strategy-docs 3 | dependencies: 4 | - python=3.9 5 | - pip 6 | - pip: 7 | - . -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "trading-strategy-docs" 3 | version = "0.1.0" 4 | description = "Trading strategy documentation" 5 | authors = ["Mikko Ohtamaa "] 6 | license = "APGL" 7 | 8 | [tool.poetry.dependencies] 9 | # Scipy compatibility 10 | # https://stackoverflow.com/questions/71764027/numpy-installation-fails-when-installing-through-poetry-on-m1-and-macos/71764028#71764028 11 | python = ">=3.11,<=3.12" 12 | 13 | furo = {version = "2022.6.4.1"} 14 | Sphinx = {version = "5.0.2"} 15 | sphinx-rtd-theme = {version = "^1.0.0"} 16 | sphinx-sitemap = {version = "^2.5.0"} 17 | sphinx-autodoc-typehints = {version = "^1.16.0"} 18 | nbsphinx = "0.8.6" 19 | sphinx-tags = {git = "https://github.com/tradingstrategy-ai/sphinx-tags"} 20 | notebook = "^6.4.12" 21 | sphinx-reredirects = "^0.1.1" 22 | zope-dottedname = "^6.0" 23 | 24 | trade-executor = {path = "deps/trade-executor", develop = true, extras=["qstrader", "execution", "web-server"]} 25 | 26 | [tool.poetry.group.dev.dependencies] 27 | ipdb = "^0.13.9" 28 | 29 | [build-system] 30 | requires = ["poetry-core>=1.0.0"] 31 | build-backend = "poetry.core.masonry.api" 32 | 33 | -------------------------------------------------------------------------------- /scraper/README.md: -------------------------------------------------------------------------------- 1 | # Typesense Search for Documentation Sites 2 | This article will show you how to use a customized version of DocSearch that works with Typesense. In fact, the search bar you see on Typesense's own documentation site is built with this customized version of DocSearch. 3 | 4 | Typesense's customized version of DocSearch is made up of two components: 5 | 6 | 1. [Typesense-docsearch-scraper](https://github.com/typesense/typesense-docsearch-scraper): A web-scraper that scans your documentation site and indexes the content in Typesense. 7 | 8 | 2. [Typesense-docsearch.js](https://github.com/typesense/typesense-docsearch.js): A JavaScript library that adds a search bar to your documentation site. When end-users start typing into the search bar, it queries the content index built by the DocSearch scraper. 9 | 10 | 11 | 12 | ## 1. Setup DocSearch Scraper 13 | We need to set up the scraper to point to your documentation site. Running the scraper will generate an index for each word on your website, and then upload it to your Typesense server 14 | 15 | ### DockSearch Scaper Config file 16 | Follow as [Typsense Scraper document](https://typesense.org/docs/guide/docsearch.html#create-a-docsearch-scraper-config-file). I created Scaper `config.json` 17 | 18 | ```json 19 | { 20 | "index_name": "sphinx", 21 | "start_urls": [ 22 | "https://tradingstrategy.ai/" 23 | ], 24 | "sitemap_urls": [ 25 | "https://tradingstrategy.ai/sitemap-docs.xml" 26 | ], 27 | "stop_urls": [], 28 | "selectors": { 29 | "lvl0": { 30 | "selector": "", 31 | "global": true, 32 | "default_value": "Documentation" 33 | }, 34 | "lvl1": "article h1", 35 | "lvl2": "article h2", 36 | "lvl3": "article h3", 37 | "lvl4": "article h4", 38 | "lvl5": "article h5", 39 | "text": "article p, article li" 40 | }, 41 | "conversation_id": [ 42 | "1654845501" 43 | ], 44 | "nb_hits": 636 45 | } 46 | ``` 47 | 48 | ### Run the scaper 49 | 1. [Install Docker](https://docs.docker.com/get-docker/) 50 | 2. [Install jq](https://jqlang.github.io/jq/download/) 51 | 3. [Make sure your Typesense server is operational](https://typesense.org/docs/guide/install-typesense.html#option-1-typesense-cloud) 52 | 4. Create a `secrect.env` file with the following contents, replacing them with the correct values for your particular situation: 53 | ``` 54 | TYPESENSE_API_KEY=xyz 55 | TYPESENSE_HOST=xxx.a1.typesense.net 56 | TYPESENSE_PORT=443 57 | TYPESENSE_PROTOCOL=https 58 | ``` 59 | 60 | 5. Run the scraper 61 | ```bash 62 | docker run -it -e --env-file=./secrect.env -e "CONFIG=$(cat config.json | jq -r tostring)" typesense/docsearch-scraper:0.9.1 63 | ``` 64 | 65 | ## 2. Add a Search Bar to document 66 | Follow as [guide from Typesense docsearch](https://typesense.org/docs/guide/docsearch.html#integrate-with-ci-deploy-it-to-a-server). We create a `search.html` in `source/_template/sidebar` 67 | 68 | ```html 69 | 70 | 92 | ``` 93 | 94 | ### Rebuid docs web 95 | ```shell 96 | poetry shell 97 | # This is a very long duration command. 98 | # For the subsequent documenation updates, 99 | # it is enough to run 100 | # make html 101 | make clean-install-and-build-local-docs 102 | ``` 103 | 104 | ## 3. Local test 105 | If you want to test `typesense docsearch` in your local machine 106 | You have to do: 107 | - Build your old `typesense server`. You can do as follow of this [guide](https://github.com/tradingstrategy-ai/search) 108 | - Config and run scraper from [`Step 1`](#1-setup-docsearch-scraper) 109 | 110 | Update domain/ip in Scaper `config.json` 111 | 112 | ```json 113 | "index_name": "sphinx", 114 | "start_urls": [ 115 | # Update your test domain or IP here 116 | "https://tradingstrategy.ai/" 117 | ], 118 | "sitemap_urls": [ 119 | # Update path of your sitemap 120 | "https://tradingstrategy.ai/sitemap-docs.xml" 121 | ], 122 | ``` 123 | Update `secrect.env` with your `typesense server` info 124 | 125 | 126 | - Update `search.html` as [`Step 2`](#2-add-a-search-bar-to-document) 127 | 128 | ### Add scraper to Github Action 129 | Before add step to run scraper in Github action. You need add `secrect env` 130 | ``` 131 | TYPESENSE_API_KEY 132 | TYPESENSE_HOST 133 | ``` 134 | 135 | Add step to run scraper after deploy docs 136 | 137 | ```yml 138 | - name: Run Docsearch Scraper 139 | uses: celsiusnarhwal/typesense-scraper@v2 140 | with: 141 | # The secret containing your Typesense API key. Required. 142 | api-key: ${{ secrets.TYPESENSE_API_KEY }} 143 | 144 | # The hostname or IP address of your Typesense server. Required. 145 | host: ${{ secrets.TYPESENSE_HOST }} 146 | 147 | # The port on which your Typesense server is listening. Optional. Default: 8108. 148 | port: 443 149 | 150 | # The protocol to use when connecting to your Typesense server. Optional. Default: http. 151 | protocol: https 152 | 153 | # The path to your DocSearch config file. Optional. Default: docsearch.config.json. 154 | config: ./scraper/config.json 155 | 156 | ``` -------------------------------------------------------------------------------- /scraper/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "index_name": "docs", 3 | 4 | "start_urls": [ 5 | { "url": "https://tradingstrategy.ai/docs/guides/", "page_rank": 10 }, 6 | { "url": "https://tradingstrategy.ai/docs/api/", "page_rank": 2 }, 7 | "https://tradingstrategy.ai/docs" 8 | ], 9 | 10 | "sitemap_urls": [ 11 | "https://tradingstrategy.ai/docs/sitemap-docs.xml" 12 | ], 13 | 14 | "stop_urls": [ 15 | "https://tradingstrategy.ai/docs/genindex.html", 16 | "https://tradingstrategy.ai/docs/search.html", 17 | "https://tradingstrategy.ai/docs/py-modindex.html", 18 | "https://tradingstrategy.ai/docs/modindex.html" 19 | ], 20 | 21 | "selectors": { 22 | "lvl0": { 23 | "selector": "", 24 | "global": true, 25 | "default_value": "Documentation" 26 | }, 27 | "lvl1": "article h1, dt.sig.sig-object > span.sig-name", 28 | "lvl2": "article h2", 29 | "lvl3": "article h3", 30 | "lvl4": "article h4", 31 | "lvl5": "article h5", 32 | "text": "article p, article li, dd", 33 | "page_rank": "section[data-page*='/api/']" 34 | }, 35 | 36 | "selectors_exclude": [ 37 | ".headerlink", 38 | ".toc-backref", 39 | "nav", 40 | "footer" 41 | ], 42 | 43 | "strip_chars": "#¶›", 44 | "min_indexed_level": 2, 45 | 46 | "custom_ranking": [ 47 | "desc(page_rank)", 48 | "asc(level)", 49 | "asc(position)" 50 | ], 51 | 52 | "render_js": false 53 | } -------------------------------------------------------------------------------- /scraper/secrect.env: -------------------------------------------------------------------------------- 1 | TYPESENSE_API_KEY= 2 | TYPESENSE_HOST= 3 | TYPESENSE_PORT= 4 | TYPESENSE_PROTOCOL= 5 | -------------------------------------------------------------------------------- /scripts/update-deps.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Update all git submodule dependenecies 4 | # 5 | 6 | set -e 7 | 8 | (cd deps/furo && git pull origin main) 9 | (cd deps/trade-executor && git checkout master && git pull origin master) 10 | (cd deps/trade-executor/deps/trading-strategy && git checkout master && git pull origin master) 11 | (cd deps/trade-executor/deps/web3-ethereum-defi && git checkout master && git pull origin master) -------------------------------------------------------------------------------- /source/_static/custom.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --sidebar-expander-width: 2px; 3 | --sidebar-item-font-size: 75%; 4 | } 5 | 6 | /* Fonts injected in base.html */ 7 | .h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6 { 8 | font-family: Neue Haas Grotesk Display,Helvetica Neue,Helvetica,Arial,sans-serif; 9 | font-weight: 600; 10 | } 11 | 12 | /* Increase readability */ 13 | article h1 { 14 | } 15 | 16 | /* Increase readability */ 17 | article h2 { 18 | margin-top: 2em; 19 | } 20 | 21 | /* Increase readability */ 22 | article h3 { 23 | margin-top: 1.25em; 24 | } 25 | 26 | ol li, p, ul li { 27 | font-family: Source Serif Pro, sans-serif; 28 | /*font-size: 1rem; 29 | font-weight: 300; 30 | line-height: 1.6;*/ 31 | } 32 | 33 | /* Article text bullet points */ 34 | .simple li { 35 | margin-bottom: 1em; 36 | } 37 | 38 | /* Fix note box text size */ 39 | .admonition, 40 | p.admonition-title { 41 | font-size: inherit; 42 | } 43 | 44 | .toctree-wrapper.compound .caption { 45 | text-transform: none; 46 | font-family: Neue Haas Grotesk Display,Helvetica Neue,Helvetica,Arial,sans-serif; 47 | font-weight: 600; 48 | font-size: 1rem; 49 | } 50 | 51 | /* Increase readability */ 52 | .toctree-l1 { 53 | margin-bottom: 0.75em; 54 | } 55 | 56 | /* Footer text size */ 57 | .bottom-of-page .left-details { 58 | font-size: var(--font-size--small); 59 | } 60 | 61 | /* Footer warning text */ 62 | .text-warning { 63 | color: #F62F2F; 64 | } 65 | 66 | /* Large intro images */ 67 | .img-architecture { 68 | margin-bottom: 1rem; 69 | } 70 | 71 | /* Color fix for the dark theme in notebooks */ 72 | .nboutput .rendered_html thead tr, 73 | .nboutput .rendered_html tbody tr:nth-child(even) { 74 | background: #fff; 75 | } 76 | 77 | .nboutput .rendered_html tbody tr:hover { 78 | background: #ADD8E6; 79 | } 80 | 81 | /* Increase sidebar with, so our long module names do not get chopped up */ 82 | .sidebar-container { 83 | width: 20em; 84 | } 85 | 86 | .sidebar-logo { 87 | max-width: 200px; 88 | margin-left: 0; 89 | } 90 | 91 | /* Pygment color fixes */ 92 | .highlight { 93 | background: #FBEEDB; 94 | } 95 | 96 | /* Fix autosummary tables with long function signatures */ 97 | 98 | table.autosummary tr td:first-child { 99 | width:60%; 100 | } 101 | 102 | table.autosummary { 103 | width: 100%; 104 | font-size: 90%; 105 | } 106 | 107 | /* Fix function name links in autosummary table */ 108 | .content table.autosummary a { 109 | border-bottom: 0; 110 | } 111 | 112 | /* Fix next and previous nav at the bottom of the page */ 113 | .related-pages { 114 | display: none; 115 | } 116 | 117 | 118 | /* Fix right hand navigation on API pages. 119 | 120 | Make sure there is enough space to fit long Class.function() names in the sidebar 121 | on a single line. 122 | */ 123 | @media (min-width: 82em) { 124 | .toc-drawer { 125 | width: 26em; 126 | } 127 | } 128 | 129 | body { 130 | /* bg of search button in nav bar */ 131 | --docsearch-searchbox-background: var(--color-input-background); 132 | /* bg of search input field when focused (e.g., in modal) */ 133 | --docsearch-searchbox-focus-background: var(--color-input-background-focus); 134 | /* text color for search input in modal */ 135 | --docsearch-text-color: var(--color-foreground-primary); 136 | /* text color for placeholder text; original */ 137 | --docsearch-muted-color: var(--color-foreground-muted); 138 | 139 | /* bg color of active search hit / color of magnifying glass icon in modal search field */ 140 | --docsearch-highlight-color: var(--color-highlighted-background); 141 | /* outline of search fields when focused */ 142 | --docsearch-searchbox-shadow: inset 0 0 0 2px var(--color-foreground-border); 143 | 144 | /* overlay of document behind modal */ 145 | --docsearch-container-background: var(--color-modal-overlay); 146 | /* main bg of modal dialog */ 147 | --docsearch-modal-background: var(--color-background-primary); 148 | /* box shadow on modal dialog box */ 149 | --docsearch-modal-shadow: 0 3px 8px 0 #00000080; 150 | 151 | /* modal dialog footer */ 152 | --docsearch-footer-background: var(--color-background-secondary); 153 | /* drop shadow to separate footer from rest of modal bg */ 154 | --docsearch-footer-shadow: 0 -1px 0 0 var(--color-background-border),0 -3px 6px 0 #00000010; 155 | /* color of typesense logo */ 156 | --docsearch-logo-color: var(--color-brand-primary); 157 | 158 | /* text color of search hit (not active) */ 159 | --docsearch-hit-color: var(--color-foreground-secondary); 160 | /* text color of active search hit */ 161 | --docsearch-hit-active-color: var(--color-foreground-primary); 162 | /* bg color of search hit (not active) */ 163 | --docsearch-hit-background: var(--color-background-secondary); 164 | /* box shadow around each search hit row */ 165 | --docsearch-hit-shadow: 0 1px 3px 0 var(--color-foreground-border); 166 | 167 | /* gradient background for search key hints */ 168 | --docsearch-key-gradient: linear-gradient(-225deg,var(--color-keyboard-2),var(--color-keyboard-1)); 169 | /* shadow outline for search key hints */ 170 | --docsearch-key-shadow: inset 0 -2px 0 0 var(--color-keyboard-3),inset 0 0 1px 1px var(--color-keyboard-1),0 1px 2px 1px var(--color-keyboard-4); 171 | } 172 | 173 | /* search button should span full navbar width (minus padding) */ 174 | .DocSearch-Button { 175 | width: calc(100% - 2rem); 176 | } 177 | 178 | /* fix highlighted style of matching text in search hit */ 179 | .DocSearch-Hits mark { 180 | background: var(--color-highlighted-background); 181 | color: var(--color-highlighted-text); 182 | } 183 | 184 | /* Neet to override some things here b/c of conflicting style sheet */ 185 | kbd.DocSearch-Button-Key, 186 | kbd.DocSearch-Commands-Key { 187 | align-items: center; 188 | background: var(--docsearch-key-gradient); 189 | box-shadow: var(--docsearch-key-shadow); 190 | color: var(--docsearch-secondary-color); 191 | display: flex; 192 | height: 18px; 193 | justify-content: center; 194 | margin-right: 0.4em; 195 | position: relative; 196 | border: 0; 197 | top: -1px; 198 | width: 20px; 199 | } 200 | 201 | kbd.DocSearch-Button-Key { 202 | border-radius: 3px; 203 | padding: 0 0 2px; 204 | } 205 | 206 | kbd.DocSearch-Commands-Key { 207 | border-radius: 2px; 208 | padding: 0 0 1px; 209 | } 210 | -------------------------------------------------------------------------------- /source/_static/custom.js: -------------------------------------------------------------------------------- 1 | /* Fix Plotly.js loading */ 2 | requirejs.config({ 3 | paths: { 4 | base: '/static/base', 5 | plotly: 'https://cdn.plot.ly/plotly-2.12.1.min.js?noext', 6 | }, 7 | }); 8 | 9 | // Plotly complains about this when loading interactive notebooks. 10 | // Probably version conflict. 11 | // We do not use MathJax, so we just disable it. 12 | delete window.MathJax; -------------------------------------------------------------------------------- /source/_static/how-to-create-algorithmic-trading-strategy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/how-to-create-algorithmic-trading-strategy.png -------------------------------------------------------------------------------- /source/_static/how-to-invest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/how-to-invest.png -------------------------------------------------------------------------------- /source/_static/logos/binder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/binder.png -------------------------------------------------------------------------------- /source/_static/logos/colab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/colab.png -------------------------------------------------------------------------------- /source/_static/logos/ethereum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/ethereum.png -------------------------------------------------------------------------------- /source/_static/logos/pandas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/pandas.png -------------------------------------------------------------------------------- /source/_static/logos/plotly.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/plotly.png -------------------------------------------------------------------------------- /source/_static/logos/pyarrow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/pyarrow.png -------------------------------------------------------------------------------- /source/_static/logos/python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/logos/python.png -------------------------------------------------------------------------------- /source/_static/plotly-shim-test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /source/_static/styles/README.txt: -------------------------------------------------------------------------------- 1 | A `furo.css` will be place here when built from SCSS. -------------------------------------------------------------------------------- /source/_static/trading-strategy-fee-structures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/_static/trading-strategy-fee-structures.png -------------------------------------------------------------------------------- /source/_templates/autosummary/README.md: -------------------------------------------------------------------------------- 1 | # Autosummary fixes 2 | 3 | [See this StackOverflow answer](https://stackoverflow.com/a/62613202/315168). -------------------------------------------------------------------------------- /source/_templates/autosummary/base.rst: -------------------------------------------------------------------------------- 1 | .. 2 | We use short name as title, because it's part of TOC tree on the left hand nav. 3 | Then we fix the HTML title in the templating. 4 | 5 | {{ name | escape | underline}} 6 | 7 | .. currentmodule:: {{ module }} 8 | 9 | .. meta:: 10 | :description: {{ fullname|extract_object_docstring }} 11 | :title: {{ name }} {{ objtype }} in {{ fullname|extract_mod_path }} 12 | 13 | {% if objtype == "class" %} 14 | 15 | Documentation for `{{ fullname }}` Python class. 16 | 17 | .. autoclass:: {{ objname }} 18 | :members: 19 | 20 | {% block attributes %} 21 | {% if attributes %} 22 | .. rubric:: {{ _('Attributes summary') }} 23 | 24 | .. autosummary:: 25 | {% for item in attributes %} 26 | ~{{ name }}.{{ item }} 27 | {%- endfor %} 28 | {% endif %} 29 | {% endblock %} 30 | 31 | {% block methods %} 32 | {% if methods %} 33 | .. rubric:: {{ _('Methods summary') }} 34 | 35 | .. autosummary:: 36 | {% for item in methods %} 37 | ~{{ name }}.{{ item }} 38 | {%- endfor %} 39 | {% endif %} 40 | {% endblock %} 41 | 42 | {% else %} 43 | 44 | API documentation for `{{ fullname }}` Python {{ objtype }}. 45 | 46 | .. auto{{ objtype }}:: {{ objname }} 47 | {% endif %} 48 | 49 | 50 | -------------------------------------------------------------------------------- /source/_templates/autosummary/class.rst: -------------------------------------------------------------------------------- 1 | {{ name | escape | underline }} 2 | 3 | .. currentmodule:: {{ module }} 4 | 5 | .. meta:: 6 | :description: {{ fullname|extract_object_docstring }} 7 | :title: {{ name }} {{ objtype }} in {{ fullname|extract_mod_path }} 8 | 9 | API documentation for `{{ fullname }}` Python class in Trading Strategy framework. 10 | 11 | .. currentmodule:: {{ module }} 12 | 13 | .. autoclass:: {{ objname }} 14 | :members: 15 | :show-inheritance: 16 | 17 | {% block methods %} 18 | .. automethod:: __init__ 19 | 20 | {% if methods %} 21 | .. rubric:: Methods 22 | 23 | .. autosummary:: 24 | {% for item in methods %} 25 | ~{{ name }}.{{ item }} 26 | {%- endfor %} 27 | {% endif %} 28 | {% endblock %} 29 | 30 | {% block attributes %} 31 | {% if attributes %} 32 | .. rubric:: Attributes 33 | 34 | .. autosummary:: 35 | {% for item in attributes %} 36 | ~{{ name }}.{{ item }} 37 | {%- endfor %} 38 | {% endif %} 39 | {% endblock %} 40 | 41 | 42 | -------------------------------------------------------------------------------- /source/_templates/autosummary/module.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | partial_name | escape | underline}} 2 | 3 | API documentation for `{{ fullname }}` Python module in Trading Strategy. 4 | 5 | .. meta:: 6 | :description: {{ fullname|extract_module_docstring }} 7 | :title: {{ name }} {{ objtype }} in {{ fullname|extract_mod_path }} 8 | 9 | 10 | Module description 11 | ------------------ 12 | 13 | .. automodule:: {{ fullname }} 14 | 15 | .. currentmodule:: {{ fullname }} 16 | 17 | {% if classes %} 18 | Classes 19 | ------- 20 | 21 | .. autosummary:: 22 | :toctree: . 23 | {% for class in classes %} 24 | {{ class }} 25 | {% endfor %} 26 | 27 | {% endif %} 28 | 29 | {% if functions %} 30 | Functions 31 | --------- 32 | 33 | .. autosummary:: 34 | :toctree: . 35 | {% for function in functions %} 36 | {{ function }} 37 | {% endfor %} 38 | {% endif %} 39 | 40 | {% if modules %} 41 | Submodules 42 | ---------- 43 | 44 | .. autosummary:: 45 | :toctree: 46 | :recursive: 47 | {% for item in modules %} 48 | {{ item }} 49 | {%- endfor %} 50 | {% endif %} -------------------------------------------------------------------------------- /source/_templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {%- block site_meta -%} 5 | 6 | 7 | 8 | 9 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | {%- if metatags %} 41 | {{ metatags }} 42 | {% endif -%} 43 | 44 | {# Make sure all pages have a description or Bing does not like us #} 45 | {% if 'name="description"' not in metatags %} 46 | 47 | {% endif %} 48 | 49 | 50 | {%- block linktags %} 51 | {%- if hasdoc('about') -%} 52 | 53 | {%- endif -%} 54 | {%- if hasdoc('genindex') -%} 55 | 56 | {%- endif -%} 57 | {%- if hasdoc('search') -%} 58 | 59 | {%- endif -%} 60 | {%- if hasdoc('copyright') -%} 61 | 62 | {%- endif -%} 63 | {%- if next -%} 64 | 65 | {%- endif -%} 66 | {%- if prev -%} 67 | 68 | {%- endif -%} 69 | {#- rel="canonical" (set by html_baseurl) -#} 70 | {%- if pageurl %} 71 | 72 | {%- endif %} 73 | {%- endblock linktags %} 74 | 75 | {# Favicon #} 76 | {%- if favicon_url -%} 77 | 78 | {%- endif -%} 79 | 80 | {#- Generator banner -#} 81 | 82 | 83 | {%- endblock site_meta -%} 84 | 85 | {#- Site title -#} 86 | {%- block htmltitle -%} 87 | {# See Sphinx monkey patch in conf.py #} 88 | {% if 'title' in metas %} 89 | {{ metas.title }} 90 | {% elif not docstitle %} 91 | {{ title|striptags|e }} 92 | {% elif pagename == master_doc %} 93 | {{ docstitle|striptags|e }} 94 | {% else %} 95 | {{ title|striptags|e }} - {{ docstitle|striptags|e }} 96 | {% endif %} 97 | {%- endblock -%} 98 | 99 | {%- block styles -%} 100 | 101 | {# Custom stylesheets #} 102 | {%- block regular_styles -%} 103 | {%- for css in css_files -%} 104 | {% if css|attr("filename") -%} 105 | {{ css_tag(css) }} 106 | {%- else -%} 107 | 108 | {%- endif %} 109 | {% endfor -%} 110 | {%- endblock regular_styles -%} 111 | 112 | {#- Theme-related stylesheets -#} 113 | {%- block theme_styles %} 114 | {% include "partials/_head_css_variables.html" with context %} 115 | {%- endblock -%} 116 | 117 | {%- block extra_styles %} 118 | {%- endblock -%} 119 | 120 | {%- endblock styles -%} 121 | 122 | {#- Custom front matter #} 123 | {%- block extrahead -%}{%- endblock -%} 124 | 125 | {%- block scripts -%} 126 | 127 | {# Custom JS #} 128 | {%- block regular_scripts -%} 129 | {% for path in script_files -%} 130 | {{ js_tag(path) }} 131 | {% endfor -%} 132 | {%- endblock regular_scripts -%} 133 | 134 | {# Theme-related JavaScript code #} 135 | {%- block theme_scripts -%} 136 | {%- endblock -%} 137 | 138 | {%- endblock scripts -%} 139 | 140 | 141 | {% block body %} 142 | 145 | {% endblock %} 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /source/_templates/module-ta.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | partial_name | escape | underline}} 2 | 3 | *{{ fullname }}* module. 4 | 5 | yyyyyxxx22 6 | {{ functions }} 7 | xxx 8 | 9 | .. automodule:: {{ fullname }} 10 | :imported-members: 11 | 12 | 13 | {% if functions %} 14 | Functions 15 | --------- 16 | 17 | .. autosummary:: 18 | :toctree: . 19 | {% for function in functions %} 20 | {{ function }} 21 | {% endfor %} 22 | {% endif %} 23 | -------------------------------------------------------------------------------- /source/_templates/sidebar/brand.html: -------------------------------------------------------------------------------- 1 | {#- 2 | 3 | Hi there! 4 | 5 | You might be interested in https://pradyunsg.me/furo/customisation/sidebar/ 6 | 7 | Although if you're reading this, chances are that you're either familiar 8 | enough with Sphinx that you know what you're doing, or landed here from that 9 | documentation page. 10 | 11 | Hope your day's going well. :) 12 | 13 | -#} 14 | 32 | -------------------------------------------------------------------------------- /source/_templates/sidebar/search.html: -------------------------------------------------------------------------------- 1 | 2 | 24 | -------------------------------------------------------------------------------- /source/api/client/index.rst: -------------------------------------------------------------------------------- 1 | .. _tradingstrategy: 2 | 3 | Market data client 4 | ================== 5 | 6 | This is the API documentation for Python `tradingstrategy` package. 7 | 8 | `tradingstrategy` is a Python client for downloading decentralised 9 | market data from Trading Strategy :ref:`oracles `. 10 | 11 | This allows 12 | 13 | - Processing :term:`Decentralised exchange` market data using 14 | :term:`pandas` 15 | 16 | - Quantitative finance research for decentralised market trading opportunities 17 | 18 | For code examples, see :ref:`getting started tutorial `. 19 | 20 | Trading Strategy client 21 | ----------------------- 22 | 23 | .. autosummary:: 24 | :toctree: help 25 | :recursive: 26 | 27 | tradingstrategy.client 28 | tradingstrategy.chain 29 | tradingstrategy.exchange 30 | tradingstrategy.pair 31 | tradingstrategy.candle 32 | tradingstrategy.liquidity 33 | tradingstrategy.trade 34 | tradingstrategy.timebucket 35 | tradingstrategy.token 36 | tradingstrategy.reader 37 | tradingstrategy.priceimpact 38 | tradingstrategy.stablecoin 39 | tradingstrategy.types 40 | tradingstrategy.utils 41 | tradingstrategy.transport 42 | tradingstrategy.charting 43 | tradingstrategy.testing 44 | tradingstrategy.top 45 | tradingstrategy.binance 46 | tradingstrategy.alternative_data 47 | tradingstrategy.frameworks.backtrader 48 | tradingstrategy.frameworks.qstrader 49 | tradingstrategy.direct_feed 50 | -------------------------------------------------------------------------------- /source/api/execution/index.rst: -------------------------------------------------------------------------------- 1 | .. _tradeexecutor: 2 | 3 | Trade execution engine 4 | ====================== 5 | 6 | This is the API documentation for Python `tradeexecutor` package. 7 | 8 | `tradeexecutor` is a trade execution framework to 9 | 10 | - Run live DeFi trading strategies 11 | - Backtest trading strategies 12 | 13 | See :ref:`running-strategies` for narrative documentation and tutorials. 14 | 15 | Trade execution framework 16 | ------------------------- 17 | 18 | .. autosummary:: 19 | :toctree: help 20 | :recursive: 21 | 22 | tradeexecutor.state 23 | tradeexecutor.strategy 24 | tradeexecutor.analysis 25 | tradeexecutor.visual 26 | tradeexecutor.backtest 27 | tradeexecutor.ethereum 28 | tradeexecutor.cli 29 | tradeexecutor.utils 30 | tradeexecutor.webhook 31 | tradeexecutor.testing 32 | tradeexecutor.monkeypatch -------------------------------------------------------------------------------- /source/api/index.rst: -------------------------------------------------------------------------------- 1 | API reference 2 | ============= 3 | 4 | This is the API documentation for :term:`Python` 5 | :ref:`trading-strategy ` 6 | and :ref:`trade-executor ` packages. 7 | 8 | See :ref:`tutorial` for getting started. 9 | 10 | **API documentation** 11 | 12 | - :ref:`trading-strategy ` - DeFi and DEX market data client 13 | - :ref:`trade-executor ` - algorithmic trading live execution and backtesting 14 | - :ref:`pandas_ta ` - technical analysis libraries for :term:`Pandas` 15 | 16 | 17 | .. toctree:: 18 | :maxdepth: 1 19 | 20 | client/index 21 | execution/index 22 | technical-analysis/index 23 | web3 24 | 25 | .. raw:: html 26 | 27 | 28 | 33 | 34 | **Additional documentation** 35 | 36 | References for related packages. 37 | 38 | - :ref:`eth_defi` 39 | 40 | Indices and tables 41 | ------------------ 42 | 43 | * :ref:`genindex` 44 | * :ref:`modindex` 45 | * :ref:`search` 46 | -------------------------------------------------------------------------------- /source/api/technical-analysis/candles/index.rst: -------------------------------------------------------------------------------- 1 | Candle pattern indicators 2 | ------------------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.candles.cdl_doji 10 | pandas_ta.candles.cdl_inside 11 | pandas_ta.candles.cdl_pattern 12 | pandas_ta.candles.cdl_z 13 | pandas_ta.candles.ha -------------------------------------------------------------------------------- /source/api/technical-analysis/cycles/index.rst: -------------------------------------------------------------------------------- 1 | Market cycles 2 | ------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.cycles.ebsw 10 | -------------------------------------------------------------------------------- /source/api/technical-analysis/index.rst: -------------------------------------------------------------------------------- 1 | .. _technical analysis: 2 | 3 | Technical analysis 4 | ================== 5 | 6 | This documentation covers technical indicators, statistical calculations 7 | and portfolio performance analysis functions. 8 | 9 | .. _pandas_ta: 10 | 11 | About pandas_ta 12 | --------------- 13 | 14 | :ref:`tradeexecutor` strategies use `pandas_ta` open source library for :term:`technical indicators `. 15 | 16 | `pandas_ta` is a :term:`Pandas` Python library for :ref:`technical analysis`. 17 | Currently `pandas_ta` supports over 150 technical indicator and analysis functions. 18 | 19 | `See the pandas_ta homepage for more information `__. 20 | 21 | Technical analysis functions 22 | ---------------------------- 23 | 24 | The documentation for technical analysis functions by category below. 25 | 26 | .. toctree:: 27 | :maxdepth: 1 28 | 29 | statistics/index 30 | overlap/index 31 | trend/index 32 | momentum/index 33 | volatility/index 34 | volume/index 35 | candles/index 36 | cycles/index 37 | performance/index 38 | 39 | 40 | -------------------------------------------------------------------------------- /source/api/technical-analysis/momentum/index.rst: -------------------------------------------------------------------------------- 1 | Momentum indicators 2 | ----------------------- 3 | 4 | .. autosummary:: 5 | :toctree: help 6 | 7 | pandas_ta.momentum.ao 8 | pandas_ta.momentum.apo 9 | pandas_ta.momentum.bias 10 | pandas_ta.momentum.bop 11 | pandas_ta.momentum.brar 12 | pandas_ta.momentum.cci 13 | pandas_ta.momentum.cfo 14 | pandas_ta.momentum.cg 15 | pandas_ta.momentum.cmo 16 | pandas_ta.momentum.coppock 17 | pandas_ta.momentum.cti 18 | pandas_ta.momentum.dm 19 | pandas_ta.momentum.er 20 | pandas_ta.momentum.eri 21 | pandas_ta.momentum.fisher 22 | pandas_ta.momentum.inertia 23 | pandas_ta.momentum.kdj 24 | pandas_ta.momentum.kst 25 | pandas_ta.momentum.macd 26 | pandas_ta.momentum.mom 27 | pandas_ta.momentum.pgo 28 | pandas_ta.momentum.ppo 29 | pandas_ta.momentum.psl 30 | pandas_ta.momentum.pvo 31 | pandas_ta.momentum.qqe 32 | pandas_ta.momentum.roc 33 | pandas_ta.momentum.rsi 34 | pandas_ta.momentum.rsx 35 | pandas_ta.momentum.rvgi 36 | pandas_ta.momentum.slope 37 | pandas_ta.momentum.smi 38 | pandas_ta.momentum.squeeze 39 | pandas_ta.momentum.squeeze_pro 40 | pandas_ta.momentum.stc 41 | pandas_ta.momentum.stoch 42 | pandas_ta.momentum.stochrsi 43 | pandas_ta.momentum.td_seq 44 | pandas_ta.momentum.trix 45 | pandas_ta.momentum.tsi 46 | pandas_ta.momentum.uo 47 | pandas_ta.momentum.willr 48 | 49 | -------------------------------------------------------------------------------- /source/api/technical-analysis/overlap/index.rst: -------------------------------------------------------------------------------- 1 | Overlap and moving averages 2 | --------------------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.overlap.alma 10 | pandas_ta.overlap.dema 11 | pandas_ta.overlap.ema 12 | pandas_ta.overlap.fwma 13 | pandas_ta.overlap.hilo 14 | pandas_ta.overlap.hl2 15 | pandas_ta.overlap.hlc3 16 | pandas_ta.overlap.hma 17 | pandas_ta.overlap.hwma 18 | pandas_ta.overlap.ichimoku 19 | pandas_ta.overlap.jma 20 | pandas_ta.overlap.kama 21 | pandas_ta.overlap.linreg 22 | pandas_ta.overlap.ma 23 | pandas_ta.overlap.mcgd 24 | pandas_ta.overlap.midpoint 25 | pandas_ta.overlap.midprice 26 | pandas_ta.overlap.ohlc4 27 | pandas_ta.overlap.pwma 28 | pandas_ta.overlap.rma 29 | pandas_ta.overlap.sinwma 30 | pandas_ta.overlap.sma 31 | pandas_ta.overlap.ssf 32 | pandas_ta.overlap.supertrend 33 | pandas_ta.overlap.swma 34 | pandas_ta.overlap.t3 35 | pandas_ta.overlap.tema 36 | pandas_ta.overlap.trima 37 | pandas_ta.overlap.vidya 38 | pandas_ta.overlap.vwap 39 | pandas_ta.overlap.vwma 40 | pandas_ta.overlap.wcp 41 | pandas_ta.overlap.wma 42 | pandas_ta.overlap.zlma 43 | -------------------------------------------------------------------------------- /source/api/technical-analysis/performance/index.rst: -------------------------------------------------------------------------------- 1 | Portfolio performance 2 | --------------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.performance.drawdown 10 | pandas_ta.performance.log_return 11 | pandas_ta.performance.percent_return 12 | -------------------------------------------------------------------------------- /source/api/technical-analysis/statistics/index.rst: -------------------------------------------------------------------------------- 1 | Statistics 2 | ---------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.statistics.entropy 10 | pandas_ta.statistics.kurtosis 11 | pandas_ta.statistics.mad 12 | pandas_ta.statistics.median 13 | pandas_ta.statistics.quantily 14 | pandas_ta.statistics.skew 15 | pandas_ta.statistics.stdev 16 | pandas_ta.statistics.tos_stdevall 17 | pandas_ta.statistics.variance 18 | pandas_ta.statistics.zscore 19 | -------------------------------------------------------------------------------- /source/api/technical-analysis/trend/index.rst: -------------------------------------------------------------------------------- 1 | Trend indicators 2 | ---------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.trend.adx 10 | pandas_ta.trend.amat 11 | pandas_ta.trend.aroon 12 | pandas_ta.trend.chop 13 | pandas_ta.trend.cksp 14 | pandas_ta.trend.decay 15 | pandas_ta.trend.decreasing 16 | pandas_ta.trend.dpo 17 | pandas_ta.trend.increasing 18 | pandas_ta.trend.long_run 19 | pandas_ta.trend.psar 20 | pandas_ta.trend.qstick 21 | pandas_ta.trend.short_run 22 | pandas_ta.trend.tsignals 23 | pandas_ta.trend.ttm_trend 24 | pandas_ta.trend.vhf 25 | pandas_ta.trend.vortex 26 | pandas_ta.trend.xsignals 27 | -------------------------------------------------------------------------------- /source/api/technical-analysis/volatility/index.rst: -------------------------------------------------------------------------------- 1 | Volatility indicators 2 | --------------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.volatility.aberration 10 | pandas_ta.volatility.accbands 11 | pandas_ta.volatility.atr 12 | pandas_ta.volatility.bbands 13 | pandas_ta.volatility.donchian 14 | pandas_ta.volatility.hwc 15 | pandas_ta.volatility.kc 16 | pandas_ta.volatility.massi 17 | pandas_ta.volatility.natr 18 | pandas_ta.volatility.pdist 19 | pandas_ta.volatility.rvi 20 | pandas_ta.volatility.thermo 21 | pandas_ta.volatility.true_range 22 | pandas_ta.volatility.ui 23 | -------------------------------------------------------------------------------- /source/api/technical-analysis/volume/index.rst: -------------------------------------------------------------------------------- 1 | Volume based indicators 2 | ----------------------- 3 | 4 | Documentation for :ref:`pandas_ta` Python package. 5 | 6 | .. autosummary:: 7 | :toctree: help 8 | 9 | pandas_ta.volume.ad 10 | pandas_ta.volume.adosc 11 | pandas_ta.volume.aobv 12 | pandas_ta.volume.cmf 13 | pandas_ta.volume.efi 14 | pandas_ta.volume.eom 15 | pandas_ta.volume.kvo 16 | pandas_ta.volume.mfi 17 | pandas_ta.volume.nvi 18 | pandas_ta.volume.obv 19 | pandas_ta.volume.pvi 20 | pandas_ta.volume.pvol 21 | pandas_ta.volume.pvr 22 | pandas_ta.volume.pvt 23 | pandas_ta.volume.vp -------------------------------------------------------------------------------- /source/api/web3.rst: -------------------------------------------------------------------------------- 1 | .. _eth_defi: 2 | 3 | Web3 Ethereum DeFi 4 | ================== 5 | 6 | `Web3-Ethereum-DeFi `_ is a low-level library for smart contracts, DeFi trading (Uniswap, PancakeSwap), Ethereum JSON-RPC, EVM transactions and automated test suites using Python. 7 | 8 | See the separate `web3-ethereum-defi documentation `_ for low level Ethereum interactions. 9 | 10 | More information 11 | ---------------- 12 | 13 | * `Github `_ 14 | * `README `_ 15 | * `Documentation `_ 16 | 17 | -------------------------------------------------------------------------------- /source/architecture/cli.rst: -------------------------------------------------------------------------------- 1 | .. _cli: 2 | 3 | Command line application 4 | ======================== 5 | 6 | The trade executor comes with a command line application interface, 7 | shortly referred as *CLI*. 8 | 9 | - The application is defined by :py:mod:`tradeeexecutor.cli` module 10 | 11 | - The application can run as a standalone Python application or 12 | as a :term:`Docker` 13 | 14 | - The application can do live trading or backtesting 15 | 16 | Running trade executor CLI 17 | -------------------------- 18 | 19 | Docker 20 | ~~~~~~ 21 | 22 | See the example `docker-compose.yml` in trade-executor repository. 23 | 24 | Python 25 | ~~~~~~ 26 | 27 | Assuming you have `tradeexecutor` package installed through Poetry: 28 | 29 | .. code-block:: shell 30 | 31 | poetry run trade-executor 32 | 33 | This should output: 34 | 35 | :: 36 | 37 | poetry run trade-executor --help 38 | Usage: trade-executor [OPTIONS] COMMAND [ARGS]... 39 | 40 | Options: 41 | --install-completion [bash|zsh|fish|powershell|pwsh] 42 | Install completion for the specified shell. 43 | --show-completion [bash|zsh|fish|powershell|pwsh] 44 | Show completion for the specified shell, to 45 | copy it or customize the installation. 46 | --help Show this message and exit. 47 | 48 | Commands: 49 | check-universe Checks that the trading universe is helthy for a given... 50 | check-wallet Prints out the token balances of the hot wallet. 51 | start Launch Trade Executor instance. 52 | -------------------------------------------------------------------------------- /source/architecture/index.rst: -------------------------------------------------------------------------------- 1 | .. _architecture: 2 | 3 | Architecture 4 | ============ 5 | 6 | This section discussed about Python and infrastructure 7 | architecture of :ref:`Trading Strategy framework `. 8 | 9 | .. toctree:: 10 | :maxdepth: 1 11 | 12 | architecture 13 | cli 14 | webhook 15 | strategy-types 16 | serialisation 17 | unit-testing 18 | 19 | -------------------------------------------------------------------------------- /source/architecture/serialisation.rst: -------------------------------------------------------------------------------- 1 | .. _serialisation: 2 | 3 | Serialisation 4 | ============= 5 | 6 | The strategy :ref:`state` is serialised as JSON 7 | 8 | - Both backtesting and :ref:`live trade execution` use the same 9 | file format. Live trades and backtesting results have the same format. 10 | 11 | - The raw state is written to the disk as a flat JSON file 12 | 13 | - The web frontend downloads the same JSON file to display the strategy execution 14 | state to the user 15 | 16 | - State is defined as nested, tree-like, structure of Python :py:mod:`dataclass` classes 17 | 18 | Here are some gotchas. 19 | 20 | Serialisation library 21 | --------------------- 22 | 23 | Python `dataclasses-json` library is used to seralise everything. 24 | 25 | Dates 26 | ----- 27 | 28 | JSON does not have native date type. 29 | 30 | Dates are serialised as UTC UNIX timestamps, or integer seconds 31 | since 1970. 32 | 33 | Prices 34 | ------ 35 | 36 | Because we are doing algorithmic trading, not accounting, 37 | prices do not need to be exact. 38 | 39 | Prices are serialised as floats. 40 | 41 | Accounting quantities 42 | --------------------- 43 | 44 | Numbers needing accounting purposes, like quantity of token holdings, 45 | are presented by Python :py:class:`decimal.Decimal`. Because JSON 46 | cannot present these numbers, they are serialised as infinite accurate 47 | strings. 48 | 49 | Inline token and trading pair identifiers 50 | ----------------------------------------- 51 | 52 | Token and trading pair identifiers are not passed by a reference, 53 | lie trading pair id or address, but by a copy. This copy contains 54 | information like token names and decimals. This information 55 | is duplicated in every copy, making this inefficient, but it 56 | greatly simplifies client side and executor side coding, 57 | because the :ref:`trading universe` may be dynamic. 58 | 59 | 60 | -------------------------------------------------------------------------------- /source/architecture/strategy-types.rst: -------------------------------------------------------------------------------- 1 | .. _strategy types: 2 | 3 | Strategy types 4 | ============== 5 | 6 | :py:mod:`tradeexecutor` supports different strategy types. 7 | 8 | * Pandas numeric analysis based strategies 9 | 10 | * QSTrader inspired (deprecated) 11 | 12 | "Pandas trader" - Internal strategy type 13 | ---------------------------------------- 14 | 15 | The internal strategy type is called "Pandas strategy type" 16 | and based on :py:mod:`tradeexecutor.strategy.pandas_trader` module. 17 | 18 | The core features of this strategy type are 19 | 20 | * The name comes from the fact that the strategy operates 21 | on Python Pandas library data format for candles and liquidity 22 | 23 | * Receiving :ref:`trading universe` as :py:mod:`tradingstrategy` client data: 24 | exchange, pairs, candles and liquidity 25 | 26 | * Strategies are self-contained Python modules 27 | 28 | * The same strategy definition can be used for backtesting and live trading 29 | 30 | * Strategy module contains two core functions: *decide_trades* and *create_trading_universe* 31 | 32 | .. _decide_trades: 33 | 34 | decide_trades 35 | ~~~~~~~~~~~~~ 36 | 37 | See :py:class:`tradeexecutor.strategy.strategy_module.DecideTradesProtocol` 38 | 39 | Example `decide_trades` function: 40 | 41 | .. code-block:: python 42 | 43 | def decide_trades( 44 | timestamp: pd.Timestamp, 45 | universe: Universe, 46 | state: State, 47 | pricing_model: PricingModel, 48 | cycle_debug_data: Dict) -> List[TradeExecution]: 49 | 50 | assert timestamp.minute == 0 51 | assert timestamp.second == 0 52 | assert timestamp.hour == 0 53 | 54 | # Create a position manager helper class that allows us easily to create 55 | # opening/closing trades for different positions 56 | position_manager = PositionManager(timestamp, universe, state, pricing_model) 57 | 58 | pair = universe.pairs.get_single() 59 | 60 | cash = state.portfolio.get_current_cash() 61 | 62 | # 30 days EMA 63 | candles: pd.DataFrame = universe.candles.get_single_pair_data(sample_count=30) 64 | close = candles["close"] 65 | 66 | slow_ema = close.ewm(span=30).mean().iloc[-1] 67 | fast_ema = close.ewm(span=10).mean().iloc[-1] 68 | 69 | # https://stackoverflow.com/a/623312/315168 70 | day_number = timestamp.to_pydatetime().timetuple().tm_yday 71 | 72 | trades = [] 73 | 74 | if day_number % 2 == 0: 75 | # buy on even days 76 | if not position_manager.is_any_open(): 77 | buy_amount = cash * position_size 78 | trades += position_manager.open_1x_long(pair, buy_amount) 79 | else: 80 | # sell on odd days 81 | if position_manager.is_any_open(): 82 | trades += position_manager.close_all() 83 | 84 | visualisation = state.visualisation 85 | visualisation.plot_indicator(timestamp, "Slow EMA", PlotKind.technical_indicator_on_price, slow_ema, colour="forestgreen") 86 | visualisation.plot_indicator(timestamp, "Fast EMA", PlotKind.technical_indicator_on_price, fast_ema, colour="limegreen") 87 | 88 | return trades 89 | 90 | create_trading_universe 91 | ~~~~~~~~~~~~~~~~~~~~~~~ 92 | 93 | See :py:class:`tradeexecutor.strategy.strategy_module.CreateTradingUniverseProtocol` 94 | 95 | Example `create_trading_universe` function: 96 | 97 | .. code-block:: python 98 | 99 | 100 | # Time bucket for our candles 101 | candle_time_bucket = TimeBucket.h4 102 | 103 | # Which chain we are trading 104 | chain_id = ChainId.bsc 105 | 106 | # Which exchange we are trading on. 107 | exchange_slug = "pancakeswap-v2" 108 | 109 | # Which trading pair we are trading 110 | trading_pair = ("WBNB", "BUSD") 111 | 112 | def create_trading_universe( 113 | ts: datetime.datetime, 114 | client: Client, 115 | execution_context: ExecutionContext, 116 | **kwargs, 117 | ) -> TradingStrategyUniverse: 118 | """Creates the trading universe where the strategy trades. 119 | 120 | If `execution_context.live_trading` is true then this function is called for 121 | every execution cycle. If we are backtesting, then this function is 122 | called only once at the start of backtesting and the `decide_trades` 123 | need to deal with new and deprecated trading pairs. 124 | 125 | As we are only trading a single pair, load data for the single pair only. 126 | 127 | :param ts: 128 | The timestamp of the trading cycle. For live trading, 129 | `create_trading_universe` is called on every cycle. 130 | For backtesting, it is only called at the start 131 | 132 | :param client: 133 | Trading Strategy Python client instance. 134 | 135 | :param execution_context: 136 | Information how the strategy is executed. E.g. 137 | if we are live trading or not. 138 | 139 | :param candle_timeframe_override: 140 | Allow the backtest framework override what candle size is used to backtest the strategy 141 | without editing the strategy Python source code file. 142 | 143 | :return: 144 | This function must return :py:class:`TradingStrategyUniverse` instance 145 | filled with the data for exchanges, pairs and candles needed to decide trades. 146 | The trading universe also contains information about the reserve asset, 147 | usually stablecoin, we use for the strategy. 148 | """ 149 | 150 | # Load all datas we can get for our candle time bucket 151 | dataset = load_all_data(client, candle_time_bucket, execution_context) 152 | 153 | # Filter down to the single pair we are interested in 154 | universe = TradingStrategyUniverse.create_single_pair_universe( 155 | dataset, 156 | chain_id, 157 | exchange_slug, 158 | trading_pair[0], 159 | trading_pair[1], 160 | ) 161 | 162 | return universe 163 | 164 | Other strategy module members 165 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 166 | 167 | Strategy module contains other parameters like 168 | * Strategy version 169 | * :term:`cycle duration` 170 | * Used routing model 171 | * Used reserve currency 172 | * See :py:class:`tradeexecutor.strategy.strategy_module.StrategyModuleInformation` for more info 173 | 174 | QSTrader strategy type 175 | ---------------------- 176 | 177 | :py:mod:`tradeexecutor` supports :term:`QSTrader` style strategies 178 | and are based on portfolio construction model theory. 179 | 180 | However this strategy type was an early attempt and is now 181 | superset by internal Pandas and PositionManager based strategy 182 | runner :py:mod:`tradeexecutor.strategy.pandas_trader`. -------------------------------------------------------------------------------- /source/architecture/unit-testing.rst: -------------------------------------------------------------------------------- 1 | Unit testing 2 | ============ 3 | 4 | Unit testing 5 | 6 | - Ensures :py:mod:`tradeexecutor` module internally acts coherently 7 | 8 | - Helps to do quick smoke tests on strategies 9 | 10 | Pytest based 11 | ------------ 12 | 13 | Unit tests are written using pytest library. 14 | 15 | Debug data 16 | ---------- 17 | 18 | Each :ref:`strategy cycle` takes in a Python dictionary called `cycle_debug_data` 19 | 20 | - This dictionary can contain anything, and unlike state, does not need 21 | to be JSON serialisable 22 | 23 | - The content of this dictionary should not be used to make trading decisions 24 | 25 | - The strategies can write internal flags and such into this dta 26 | 27 | - Unit tests can inspect this debug data to see if strategy is working 28 | 29 | - In live trading, this data is discarded after each cycle 30 | 31 | See :ref:`decide_trades` function. -------------------------------------------------------------------------------- /source/architecture/webhook.rst: -------------------------------------------------------------------------------- 1 | .. _webhook: 2 | 3 | Webhook server 4 | ============== 5 | 6 | The webhook server allows web frontends to display the current 7 | status of a trade executor. 8 | 9 | - Open positions 10 | 11 | - Current profit and loss, performance 12 | 13 | - Logs and error conditions 14 | 15 | .. note :: 16 | 17 | Even if the `trade-executor` live trade loop dies, the web server stays up 18 | to provide the diagnostics information about the cause of the crash. 19 | See :ref:`checking for trade execution main loop crash` how to monitor 20 | the trade execution crashes. 21 | 22 | About the server 23 | ---------------- 24 | 25 | - The server is written in Pyramid web framework 26 | 27 | - The server API is specified as OpenAPI 28 | 29 | - The default port of the server is `3456` 30 | 31 | - The server is safe to expose to public Internet, 32 | assuming the underlying strategy is public 33 | 34 | State download 35 | -------------- 36 | 37 | - A trade executor persits is state as a JSON blob 38 | 39 | - This JSON blob is described by :py:mod:`tradeexecutor.state` 40 | 41 | - The web frontend download the whole state as a single blob 42 | download from the webhook server 43 | 44 | -------------------------------------------------------------------------------- /source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | 3 | project = 'Trading Strategy' 4 | copyright = '2021, Mikko Ohtamaa' 5 | author = 'Mikko Ohtamaa' 6 | 7 | 8 | # -- General configuration --------------------------------------------------- 9 | 10 | # Add any Sphinx extension module names here, as strings. They can be 11 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 12 | # ones. 13 | extensions = [ 14 | 'nbsphinx', 15 | "sphinx.ext.intersphinx", 16 | "sphinx_sitemap", 17 | "sphinx.ext.autodoc", 18 | "sphinx.ext.autosummary", 19 | "sphinx.ext.viewcode", 20 | 'sphinx_reredirects', 21 | 'sphinx_tags', 22 | # "sphinx_toolbox.more_autodoc", 23 | # "sphinx_autodoc_typehints" 24 | ] 25 | 26 | tags_create_tags = True 27 | 28 | tags_extension = ["rst", "ipynb"] 29 | 30 | intersphinx_mapping = { 31 | "pandas": ("http://pandas.pydata.org/pandas-docs/dev", None), 32 | "matplotlib": ("https://matplotlib.org/stable/", None), 33 | "numpy": ("https://numpy.org/doc/stable/", None), 34 | "python": ("https://docs.python.org/3/", None), 35 | "web3": ("https://web3py.readthedocs.io/en/latest/", None), 36 | "web3-ethereum-defi": ("https://web3-ethereum-defi.readthedocs.io/", None), 37 | } 38 | 39 | # https://help.farbox.com/pygments.html 40 | pygments_style = 'perldoc' 41 | 42 | # Add any paths that contain templates here, relative to this directory. 43 | templates_path = ['_templates'] 44 | 45 | # List of patterns, relative to source directory, that match files and 46 | # directories to ignore when looking for source files. 47 | # This pattern also affects html_static_path and html_extra_path. 48 | exclude_patterns = [] 49 | 50 | html_theme = "furo" 51 | 52 | # Add any paths that contain custom static files (such as style sheets) here, 53 | # relative to this directory. They are copied after the builtin static files, 54 | # so a file named "default.css" will overwrite the builtin "default.css". 55 | html_static_path = ['_static'] 56 | 57 | 58 | # See if this fixed Google crawling issues 59 | html_baseurl = "https://tradingstrategy.ai/docs/" 60 | 61 | # Fix "en" in sitemap URL 62 | # https://pypi.org/project/sphinx-sitemap/ 63 | sitemap_url_scheme = "{link}" 64 | 65 | # Bump to force Google reindex 66 | sitemap_filename = "sitemap-docs.xml" 67 | 68 | # Logos 69 | # https://pradyunsg.me/furo/customisation/logo/ 70 | html_theme_options = { 71 | "light_logo": "logo-light.svg", 72 | "dark_logo": "logo-dark.svg", 73 | 74 | # https://pradyunsg.me/furo/customisation/edit-button/ 75 | "source_repository": "https://github.com/tradingstrategy-ai/docs/", 76 | "source_branch": "master", 77 | "source_directory": "source/", 78 | } 79 | 80 | # Fix plotly.js loading 81 | html_js_files = [ 82 | "require.min.js", 83 | "custom.js", 84 | ] 85 | 86 | html_css_files = [ 87 | "https://cdn.jsdelivr.net/npm/typesense-docsearch-css@0.4.1", 88 | "custom.css" 89 | ] 90 | 91 | html_context = { 92 | "theme_sidebar_hide_name": True, 93 | } 94 | 95 | # 96 | # All notebooks in documentation needs an API key and must be pre-executed 97 | # https://nbsphinx.readthedocs.io/en/0.8.6/never-execute.html 98 | # 99 | nbsphinx_execute = 'never' 100 | 101 | 102 | nbsphinx_prolog = """ 103 | 104 | .. raw:: html 105 | 106 | 107 | 108 | 109 | 110 | """ 111 | 112 | # For the sitemap 113 | html_baseurl = 'https://tradingstrategy.ai/docs' 114 | 115 | # https://stackoverflow.com/a/62613202/315168 116 | autodoc_class_signature = "separated" 117 | 118 | autodoc_typehints = "description" 119 | 120 | autosummary_generate = True 121 | 122 | add_module_names = False 123 | 124 | autodoc_member_order = "bysource" 125 | 126 | # autosummary_imported_members = True 127 | 128 | # Needed to document DecideTrades 129 | # https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_default_options 130 | autodoc_default_options = { 131 | 'special-members': "__init__, __call__" 132 | } 133 | 134 | redirects = { 135 | "learn": "learn/index.html", 136 | "home": "index.html" 137 | } 138 | 139 | # Monkey-patch sphinx-sitemap to support XML argument 140 | import trading_strategy_docs.sphinx_sitemap_patch 141 | import trading_strategy_docs.sphinx_render_patch 142 | 143 | 144 | -------------------------------------------------------------------------------- /source/deployment/index.rst: -------------------------------------------------------------------------------- 1 | .. _running-strategies: 2 | 3 | .. _running strategies: 4 | 5 | .. _strategy deployment: 6 | 7 | Deploying live trading strategies 8 | ================================= 9 | 10 | .. note:: 11 | 12 | First check `Getting started with live trade execution example `__ repository. 13 | 14 | In this section, we discuss how to run trading strategies 15 | developed with :ref:`Trading Strategy framework `. 16 | 17 | Live trading is done by :ref:`trade-executor` command 18 | that is deployed as :term:`Docker` container. When 19 | you deploy a live trading strategy, you first need 20 | to choose how you wish to run it, see :ref:`live trading modes`. 21 | 22 | .. toctree:: 23 | :maxdepth: 1 24 | 25 | trade-executor 26 | live-trading 27 | metadata 28 | hot-wallet-deployment 29 | vault-deployment 30 | lagoon-vault 31 | velvet-portfolio 32 | monitoring 33 | docker-images 34 | backtest-vs-live-execution 35 | troubleshooting 36 | repair 37 | wallet-operations 38 | 39 | -------------------------------------------------------------------------------- /source/deployment/lagoon-vault.rst: -------------------------------------------------------------------------------- 1 | Lagoon vault deployment 2 | ======================= 3 | 4 | Here are specific instructions to deploy a vault with :term:`Lagoon`. 5 | The instructions have only Lagoon specific bits. For full guide see :ref:`vault deployment`. 6 | 7 | Preface 8 | ------- 9 | 10 | An automated trading Lagoon vault consists of 11 | 12 | - Safe multisig wallet 13 | - Lagoon vault smart contract: manages deposit and redemption calls 14 | - Lagoon silo smart contract: stores deposit queue assets before they are settled in the vault 15 | - Gnosis Safe multisig: main contract storing the assets 16 | - `Trading Strategy Module `__: 17 | A Zodiac-module to enable automated asset management with safeguard 18 | 19 | Lagoon example deploy script 20 | ---------------------------- 21 | 22 | This example deploy script used with Docker Compose setup for creating a vault on Base. 23 | 24 | The deployment creates contracts 25 | - Safe 26 | - Vault 27 | - TradingStrategyModuleV0 28 | 29 | To deploy 30 | - You need Ethescan-compatible API key to verify deployed contracts onchain 31 | - Do Anvil-based simulation first 32 | - Then do live deployment 33 | - You need to give a bunch of multisig cosigners who will be owners of the created Safe 34 | 35 | The deployer creates several transactions to configure ``TradingStrategyModuleV0``. 36 | 37 | Secrets needed, give to the script via Docker compose environment variable files: 38 | 39 | .. code-block:: text 40 | 41 | PRIVATE_KEY= 42 | ETHERSCAN_API_KEY= 43 | 44 | An example deployment script: 45 | 46 | .. code-block:: shell 47 | 48 | #!/bin/bash 49 | # 50 | # Deploy Lagoon vault for a strategy defined in docker-compose.yml 51 | # 52 | # Set up 53 | # - Gnosis Safe 54 | # - Vault smart contract 55 | # - TradingStrategyModuleV0 guard with allowed assets 56 | # - trade executor hot wallet as the asset manager role 57 | # 58 | # To run: 59 | # 60 | # SIMULATE=true deploy/deploy-base-ath.sh 61 | # 62 | 63 | 64 | set -e 65 | 66 | if [ "$SIMULATE" = "" ]; then 67 | echo "Set SIMULATE=true or SIMULATE=false" 68 | exit 1 69 | fi 70 | 71 | if [ "$TRADE_EXECUTOR_VERSION" = "" ]; then 72 | echo "TRADE_EXECUTOR_VERSION missing" 73 | exit 1 74 | fi 75 | 76 | set -u 77 | 78 | # docker composer entry name 79 | ID="base-ath" 80 | 81 | # ERC-20 share token symbol 82 | export FUND_SYMBOL="ATH1" 83 | 84 | # ERC-20 share toke name 85 | export FUND_NAME="All-time high (Base)" 86 | 87 | # The vault is nominated in USDC on Base 88 | export DENOMINATION_ASSET="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" 89 | 90 | # 0% 91 | export MANAGEMENT_FEE=0 92 | 93 | #: 20% 94 | export PERFORMANCE_FEE=2000 95 | 96 | # Set as the initial owners or deployed Safe + deployer will be threre 97 | # Safe signing threshold is number of cosigners minus one. 98 | export MULTISIG_OWNERS="0xa7208b5c92d4862b3f11c0047b57a00Dc304c0f8, 0xbD35322AA7c7842bfE36a8CF49d0F063bf83a100, 0x05835597cAf9e04331dfe1f62C2Ec0C2aDc0d4a2, 0x5C46ab9e42824c51b55DcD3Cf5876f1132F9FbA9" 99 | 100 | # Terms of service manager smart contract address. 101 | # This one is deployed on Polygon. 102 | # export TERMS_OF_SERVICE_ADDRESS="0xDCD7C644a6AA72eb2f86781175b18ADc30Aa4f4d" 103 | 104 | # Run the command 105 | # - Pass private key and JSON-RPC node from environment variables 106 | # - Set vault-info.json to be written to a local file system 107 | 108 | export TRADE_EXECUTOR_IMAGE=ghcr.io/tradingstrategy-ai/trade-executor:${TRADE_EXECUTOR_VERSION} 109 | echo "Using $TRADE_EXECUTOR_IMAGE" 110 | docker compose run \ 111 | -e SIMULATE \ 112 | $ID \ 113 | lagoon-deploy-vault \ 114 | --vault-record-file="deploy/$ID-vault-info.json" \ 115 | --fund-name="$FUND_NAME" \ 116 | --fund-symbol="$FUND_SYMBOL" \ 117 | --denomination-asset="$DENOMINATION_ASSET" \ 118 | --any-asset \ 119 | --uniswap-v2 \ 120 | --uniswap-v3 \ 121 | --multisig-owners="$MULTISIG_OWNERS" \ 122 | --performance-fee="$PERFORMANCE_FEE" \ 123 | --management-fee="$MANAGEMENT_FEE" 124 | 125 | 126 | 127 | Example output: 128 | 129 | .. code-block:: text 130 | 131 | Key Label 132 | Deployer 0x5BbB9768f878a2eDe9A4317878606fd1BA9e7879 133 | Safe 0x04a7cBA3f913eC9aD3f9A26E604F3e75d4E6b530 134 | Vault 0x6E20dA351c36eb30241E9D62961681288FD34397 135 | Trading strategy module 0x4ef44a6835F98D4Eac7D74aE3c196a832B19B939 136 | Asset manager 0x5BbB9768f878a2eDe9A4317878606fd1BA9e7879 137 | Underlying token 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 138 | Underlying symbol USDC 139 | Share token 0x6E20dA351c36eb30241E9D62961681288FD34397 140 | Share token symbol MEMEX 141 | Multisig owners 0xa7208b5c92d4862b3f11c0047b57a00Dc304c0f8, 0xbD35322AA7c7842bfE36a8CF49d0F063bf83a100, 0x05835597cAf9e04331dfe1f62C2Ec0C2aDc0d4a2, 0x5C46ab9e42824c51b55DcD3Cf5876f1132F9FbA9 142 | Block number 24,773,588 143 | 144 | Safe multisignature wallet cosigners 145 | ------------------------------------ 146 | 147 | Each Lagoon vault has an underlying Safe multisignature wallet with cosigners. 148 | 149 | These cosigners are given to the development script, but you need to manually remove the deployer key 150 | from the Safe cosigner list. This operation has to be done by other cosigners. 151 | 152 | Executing Safe actions manually 153 | ------------------------------- 154 | 155 | Multisig cosigners may need to do manual actions on behalf of the vault owners. Such actions include 156 | - Trading away broken ERC-20 tokens (can't swap) 157 | - Liquidating any airdrops 158 | 159 | To do that 160 | 161 | - You need to access the underlying Safe multisignature wallet of the vault through Safe URL 162 | - Open any service where you wish to do transactions through Safe app menu, e.g. 1inch 163 | - Initiate a transaction 164 | - Confirm the transaction 165 | 166 | Safe multisignature URL is format of: https://app.safe.global/home?safe=base:0x6ad1A91Ca59Cf12D58c5F81dd737E8081c7C6e64 167 | 168 | .. note :: 169 | 170 | The vault address (Lagoon Silo smart contract) is different from the underlying Safe address. 171 | 172 | -------------------------------------------------------------------------------- /source/deployment/live-trading.rst: -------------------------------------------------------------------------------- 1 | .. _live trading modes: 2 | 3 | .. _deployment mode: 4 | 5 | Live trading modes 6 | ================== 7 | 8 | Different live trading models are supported 9 | 10 | - Single owner Ethereum hot wallet and private strategies 11 | 12 | - Multiple shareholders using :term:`Enzyme protocol` :term:`vault`, 13 | single :ref:`oracle` and public strategies (coming soon) 14 | 15 | - Multiple strategy shareholders using :term:`Enzyme protocol`, 16 | decentralised :ref:`oracle` network and public strategies (coming soon) 17 | 18 | Running modes 19 | ------------- 20 | 21 | Single oracle 22 | ~~~~~~~~~~~~~ 23 | 24 | See :ref:`hot wallet deployment` for the reference. 25 | 26 | Enzyme vault 27 | ~~~~~~~~~~~~~ 28 | 29 | See :ref:`vault deployment` for the reference. -------------------------------------------------------------------------------- /source/deployment/metadata.rst: -------------------------------------------------------------------------------- 1 | .. _strategy metadata: 2 | 3 | Strategy metadata 4 | ================= 5 | 6 | Live trade execution has metadata that lives outside the strategy module. 7 | Metadata includes on-chain connector data, human description mostly to display and route 8 | the trade executor data on the web frontend. 9 | Metadata lives outside the core strategy module, in :ref:`environment file` 10 | given to the `trade-executor`. 11 | 12 | Configured metadata 13 | ------------------- 14 | 15 | - **Python module**: A strategy module as Python source code file. This is slightly different from backtesting notebook, 16 | but can be constructed from the backtest with copy-paste. *The filename of this module 17 | is the same as the strategy id.** In this documentation, we use `pancake-eth-usd-sma` as an example. 18 | 19 | - **Logo**: Strategy logo image URL. The image must be 1:1 aspect ratio. 20 | 21 | - **Machine readable id** e.g. `enzyme-polygon-eth-usdc`. This is automatically set: If this is not 22 | explicitly set then this is the same as the strategy module filename. 23 | 24 | - **Domain**: A URL and a domain name for `trade-executor` webhook server. 25 | For the sake of convenience, use the same as machine readable id. 26 | 27 | - **Configuration files**: The strategy execution configuration that include the hot wallet private key, 28 | API keys for oracle market data feeds, blockchain nodes, Discord webhook notifications 29 | and such. Setting up the configuration files are described below. 30 | 31 | - **Server**: A server where you run the `trade-executor` Docker container and any related infrastructure, 32 | like a reverse proxy web server. 33 | 34 | - **Private key** needed for the hot wallet that executes the transactions. 35 | 36 | - **Initial test funds**: native blockchain token and USDC for gas fees. 37 | 38 | - **Backtest results**: this will be generated during the strategy deployment process 39 | 40 | Enzyme vault-based trading configuration 41 | ---------------------------------------- 42 | 43 | For vault-based strategies, you will also need the various smart contracts 44 | given by `trade-executor enzyme-vault-deploy` command. 45 | 46 | * Vault deployment block number (because Ethereum nodes have broken 47 | model for reading events) 48 | 49 | * Vault smart contract address 50 | 51 | * USDC payment forwarder address 52 | 53 | * `trade-executor` adapter address 54 | 55 | For more details see :ref:`Vault deployment`. 56 | 57 | Strategy state 58 | -------------- 59 | 60 | The persistent state of the strategy lives in a JSON-based file ("flat file database"). 61 | For :ref:`Docker` this file is mapped to the host file system `state` 62 | folder. 63 | 64 | The frontend can read the whole state file as is and it does not contain any secrets 65 | which could not be deduced from the on-chain activity. 66 | 67 | For the state details see :ref:`Serialisation`. 68 | 69 | Run-time data 70 | ------------- 71 | 72 | The live trade executor generates run-time data. This includes things like 73 | 74 | - Is the service healthy 75 | 76 | - What is the exception message in the case of a crash 77 | 78 | - Log output 79 | 80 | - Profiling and diagnostics stats 81 | 82 | Run-time data is not persistent and is reset every time the `trade-executor` restarts. 83 | See :ref:`Strategy monitoring` for more information. 84 | 85 | Webhook routing 86 | --------------- 87 | 88 | A live trading strategy exposes itself to the world using a :ref:`webhook` over an internal web server. 89 | 90 | For this you need 91 | 92 | - DNS name e.g. `mystrategy.example.com`. The best practice is to use the `id` from metadata 93 | as the subdomain name. 94 | 95 | - An internal localhost port to map to the Docker container. 96 | 97 | - A reverse proxy web server configuration e.g. via :term:`Caddy` 98 | so that the webhook is securely exposed to the world. 99 | 100 | 101 | -------------------------------------------------------------------------------- /source/deployment/monitoring.rst: -------------------------------------------------------------------------------- 1 | .. _strategy monitoring: 2 | 3 | Website and monitoring 4 | ====================== 5 | 6 | After deploying your strategy either through :ref:`hot wallet deployment` or :ref:`vault deployment`, 7 | it can start trading immediately. 8 | 9 | You will still need to want to 10 | 11 | - See how the strategy performs 12 | 13 | - Set up alerts for error conditions like software crashes and gas spikes 14 | 15 | Preface 16 | ------- 17 | 18 | `trade-executor` offers multiple ways to report what it is doing 19 | 20 | - Website frontend (lives in `Trading Strategy frontend repositry `__) 21 | 22 | - Discord alerts 23 | 24 | - Logstash centralised logging 25 | 26 | - Docker logs 27 | 28 | Exposing the webhook port using a reverse HTTP proxy 29 | ---------------------------------------------------- 30 | 31 | After the `trade-executor` is running, its :ref:`webhook` is functional. 32 | You still need to map HTTPS reverse proxy 33 | that exposes `trade-executor` webhook to the world. 34 | 35 | - `trade-executor` webhook server is read by the web frontend, 36 | monitoring tools 37 | 38 | - We need to have a DNS name which points to our trade executor 39 | 40 | - We need to map this DNS name to our server and our 41 | server needs to have a web server at ports 80 and 443 42 | to proxy the traffic 43 | 44 | Here is an example how to configure `Caddyfile` subdomain for the trade executor webhook. 45 | We do not cover how to run Caddy in these instructions, 46 | more examples can be found in `proxy-server repository `__. 47 | 48 | .. code-block:: text 49 | 50 | # 51 | # pancake-eth-usd-sma trade executor 52 | # 53 | # See https://tradingstrategy.ai/docs for details. 54 | # Internal 19003 port is set in docker-compose.yml 55 | # 56 | http://pancake-eth-usd-sma.example.com { 57 | reverse_proxy 127.0.0.1:19003 58 | } 59 | 60 | .. note :: 61 | 62 | http:// or https:// in Caddy depends on how your server traffic is configured. 63 | For details see Caddy documentation. 64 | 65 | Point your DNS service to have `A` and `AAAA` subdomains for `pancake-eth-usd-sma`. 66 | 67 | After restaring Caddy with the new configutaion, you can do the same ping test as 68 | we did using the localhost interface earlier. This time, we are using the 69 | world exposed URL. 70 | 71 | Perform the command your your local computer: 72 | 73 | .. code-block:: shell 74 | 75 | curl https://pancake-eth-usd-sma.example.com/ping 76 | 77 | This should give you the JSON result: 78 | 79 | .. code-block:: text 80 | 81 | {"ping": "pong"} 82 | 83 | Web frontend 84 | ------------ 85 | 86 | Trading Strategy SvelteKit based web frontend provides user interface for the strategy execution. 87 | 88 | - The frontend runs as its independent web server using SvelteKit's built-in Vite 89 | web server, plus any number of reverse proxies like Cloudflare 90 | 91 | - The frontend pulls the data from the trade executor over the webhook interface 92 | 93 | Available strategies displayed on the website are configured in `TS_PUBLIC_STRATEGIES` 94 | environment variable passed to the frontend when it is launched. This is usually done 95 | when the Docker instance of the frontend is restarted. 96 | 97 | - To test the frontend updates, you can run the frontend locally, you just need Node and NPM. 98 | The instructions are in `README `_. 99 | 100 | - Edit the `.env file `__ 101 | on tbe production server to include the new strategy information 102 | 103 | - `TS_PUBLIC_STRATEGIES` is a JSON encoded list of JavaScript objects 104 | 105 | - For each strategy you need `id`, `name`, and webhook `url` 106 | 107 | - Restart Docker instance 108 | 109 | - Visit on `/strategies` landing page to see your new strategy is now showing up 110 | 111 | `For more information, see frontend Github repository `_. 112 | 113 | Discord notifications 114 | --------------------- 115 | 116 | A strategy can report its status to Discord. 117 | 118 | - `trade-executor` takes this setting in `DISCORD_WEBHOOK_URL` configuration variable 119 | 120 | - Create a Discord channel 121 | 122 | - Choose Channel settings > *Integrations* > *Create Webhook* 123 | 124 | - Name your webhook the same as your strategy 125 | 126 | - Store the Discord webhook URL as `DISCORD_WEBHOOK_URL` in the secrets configuration file 127 | 128 | Logstash logging 129 | ---------------- 130 | 131 | Logstash provides centralised logging server where multiple applications can send their logs. 132 | 133 | - Better security and auditability as logs are centrally managed and secured 134 | 135 | - Good search functionality over logs, allowing to diagnose issues faster 136 | 137 | - Logstash is using unauthenticated UDP for log streams: you need to authenticate 138 | any logger using firewall IP address based whitelisting 139 | 140 | A `trade-executor` can send its Python logs to LogStash using `LogStash adapter `__. 141 | 142 | For further configuration about LogStash logging, see `python-logstash` documentation. 143 | 144 | Monitoring the Docker container 145 | ------------------------------- 146 | 147 | The Docker container is set up in such a way that it won't crash 148 | in the case `trade-execution` fails with a Python exception 149 | 150 | - The instance and its webhook service stay up despite `trade-executor` stopping 151 | 152 | - You can read the status of the `trade-executor` is running back from `/status` endpoint 153 | 154 | - `See /status documentation here `_. 155 | 156 | Thus, the normal `docker-compose` restart policies are not working. Any trade execution restart 157 | should be done only manually. 158 | 159 | You can check the status if `trade-executor` is running by: 160 | 161 | .. code-block:: shell 162 | 163 | curl http://localhost:19003/status | jq 164 | 165 | .. code-block:: text 166 | 167 | { 168 | "last_refreshed_at": 1669801614.073565, 169 | "executor_running": true, 170 | "completed_cycle": null, 171 | "exception": null 172 | } 173 | 174 | 175 | For any uptime monitoring you can check the status of `executor_running` field 176 | to confirm the trade executor is properly running. -------------------------------------------------------------------------------- /source/deployment/repair.rst: -------------------------------------------------------------------------------- 1 | .. _repairing positions 2 | 3 | Repairing frozen trading positions 4 | ================================== 5 | 6 | Automatically managed positions may end up to a "frozen" state in the case the trade execution logic encounters and error and 7 | a safety trips. 8 | 9 | - Trading position is marked as frozen if a trade executor attempts to trade a position, 10 | but the trade fails for a reason or another 11 | 12 | - Positions are shown on Frozen positions list 13 | 14 | - Frozen positions are not included in the total equity of a strategy 15 | 16 | - Frozen positions need manual intervention 17 | 18 | The reasons why a trade executor may mark a position as a frozen 19 | 20 | - The gas fee needed to complete the trade was higher than the allowed limit 21 | 22 | - A blockchain node was down 23 | 24 | - The blockchain itself was halted (see `BNB Chain incident `__) 25 | 26 | - Internal error that needs to be patched 27 | 28 | - Out of gas money 29 | 30 | Checking positions 31 | ------------------ 32 | 33 | You can check open/frozen/closed positions from the command line: 34 | 35 | .. code-block:: shell 36 | 37 | docker compose run ethereum-memecoin-swing show-positions 38 | 39 | Fixing frozen positions 40 | ----------------------- 41 | 42 | Currently the frozen positions can be fixed manually on the server where the trade executor is running. 43 | 44 | First clear any obstacles that might be blocking the frozen position trades, like 45 | topping up the gas wallet. 46 | 47 | Go to the server and `docker-compose.yml` folder where the trade executor is running. 48 | 49 | Choose the trade executor Docker image version (you can peak the current version using `docker ps` command): 50 | 51 | .. code-block:: shell 52 | 53 | # Sets TRADE_EXECUTOR_VERSION environment variable needed for docker-compose.yml file 54 | source scripts/set-latest-tag.sh 55 | 56 | Check running strategies 57 | 58 | .. code-block:: shell 59 | 60 | docker compose ps 61 | 62 | For any strategy to be repaired, its trade executor must be stopped first. 63 | 64 | .. code-block:: shell 65 | 66 | $EXECUTOR_ID=ethereum-memecoin-swing 67 | docker compose stop $EXECUTOR_ID 68 | 69 | Now you can start the repair: 70 | 71 | .. code-block:: shell 72 | 73 | docker-compose run $EXECUTOR_ID repair 74 | 75 | This will attempt to re-execute all trades that failed prior. 76 | 77 | .. note :: 78 | 79 | The process is interactive and will prompt you the trades 80 | before attempting to fix them, so it is safe to run. 81 | 82 | After the repair command is run you get a report: 83 | 84 | .. code-block:: text 85 | 86 | Saved state to state/quickswap-matic-usd-ema.json, total 1623881 chars 87 | 88 | Restarting the executor 89 | ----------------------- 90 | 91 | For any strategy to be repaired, its trade executor must be stopped first. 92 | 93 | .. code-block:: shell 94 | 95 | docker-compose up -d $EXECUTOR_ID 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /source/deployment/trade-executor.rst: -------------------------------------------------------------------------------- 1 | .. _trade-executor: 2 | 3 | Trade-executor command 4 | ====================== 5 | 6 | The live trading is handled by `trade-executor` daemon that 7 | is deployed as a :term:`Docker` container. 8 | 9 | This command 10 | 11 | - Runs as a daemon for live trade execution. 12 | 13 | - Offers various command line helper commands to diagnose 14 | live strategies like 15 | `backtest`, `console`, `show-accounts`. On these, 16 | see more in :ref:`troubleshooting live trading`. 17 | 18 | Running trade-executor 19 | ---------------------- 20 | 21 | You need to 22 | 23 | - Know UNIX command line basics 24 | 25 | - Have enabled docker login to Github - see 26 | `how to set up Github access token to download Docker images from GHCR `_. 27 | 28 | To get started, `check the latest version from trade-executor release `__. 29 | 30 | Run the command to see the command line help: 31 | 32 | .. code-block:: shell 33 | 34 | # Replace with the latest version 35 | export TRADE_EXECUTOR_VERSION=v163 36 | 37 | # Read command line help 38 | docker run ghcr.io/tradingstrategy-ai/trade-executor:${TRADE_EXECUTOR_VERSION} --help 39 | 40 | Further information 41 | ------------------- 42 | 43 | See :ref:`managing docker images` for more information on running Docker images. 44 | -------------------------------------------------------------------------------- /source/deployment/velvet-portfolio.rst: -------------------------------------------------------------------------------- 1 | Velvet portfolio deployment 2 | =========================== 3 | 4 | Here are specific instructions to deploy a vault with :term:`Velvet Capital`. 5 | The instructions have only Velvet specific bits. For full guide see :ref:`vault deployment`. 6 | 7 | Preface 8 | ------- 9 | 10 | An automated trading Velvet vault consists of 11 | 12 | - Safe multisig wallet 13 | - Velvet Capital proprietary vault contracts for the share token and deposit flow management 14 | - Special integrations for whitelisted trading protocols like Enso 15 | 16 | Velvet deployment 17 | ----------------- 18 | 19 | 1. Create a new private key for the oracle 20 | 2. Import this private key to Metamask or Rabby 21 | 3. Go to Velvet website 22 | 4. Manually create a portfolio 23 | 5. Configure vault based on this private key and portfolio contract address 24 | 6. Top up vault with some USDT/USDC 25 | 26 | Example Velvet configuration 27 | ---------------------------- 28 | 29 | Example env file for trade-executor Docker: 30 | 31 | .. code-block:: shell 32 | 33 | # 34 | # This is the public environment variables file for a trade executor. 35 | # This is only partial configuration. 36 | # 37 | 38 | # This is a vault based strategy 39 | ASSET_MANAGEMENT_MODE="velvet" 40 | 41 | # 42 | # Strategy assets and metadata 43 | # 44 | 45 | STRATEGY_FILE=strategy/bnb-ath.py 46 | 47 | # Port 3456 is mapped to the public IP on the host using Caddy 48 | HTTP_ENABLED=true 49 | 50 | # The trigger mode for the decide_trades() 51 | MIN_GAS_BALANCE=0.01 52 | GAS_BALANCE_WARNING_LEVEL=0.03 53 | 54 | # mainly for TVL data since we have only daily candles 55 | MAX_DATA_DELAY_MINUTES=1600 56 | 57 | # Vault 58 | # https://dapp.velvet.capital/ManagerVaultDetails/0x806b760f99ce80fa01bf9b3a8de6dd3590d4d1a9 59 | VAULT_ADDRESS=0x806b760f99ce80fa01bf9b3a8de6dd3590d4d1a9 60 | 61 | Preflight sequence 62 | ------------------ 63 | 64 | See :ref:`vault-deployment` for full details. 65 | 66 | 1. Manually create vault 67 | 2. Deploy env file 68 | 3. Update docker-compose.yml 69 | 4. Update Caddy 70 | 5. `trade-executor init` 71 | 6. `trade-executor check-universe` 72 | 7. `trade-executor check-wallet` 73 | 8. `trade-executor perform-test-trade --simulate` 74 | 9. `trade-executor perform-test-trade --no-simulate` 75 | 10. Adjust strategy parameter thresholds for low launch capital amounts 76 | 11. `trade-executor start` 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /source/deployment/wallet-operations.rst: -------------------------------------------------------------------------------- 1 | Vault manual transactions 2 | ========================= 3 | 4 | In this chapter, we show how to directly transact as Trade Executor when manual correction operations are required (broken token, airdrops, etc.). 5 | 6 | Sending a transaction through the hot wallet 7 | -------------------------------------------- 8 | 9 | Here is an example how ot constrct a transaction through the Trade Executor console from the hot wallet. 10 | 11 | In this example, we do ERC-20 transfer. If a token is outside guard's rules, it is usually free to transfer. 12 | 13 | Stop Trade Executor. 14 | 15 | Then start the console from terminal using Docker Compose. 16 | 17 | .. code-block:: shell 18 | 19 | docker compose run ethereum-memecoin-swing console 20 | 21 | Copy paste script wit ``%cpaste` to execute a transaction. 22 | 23 | .. code-block:: python 24 | 25 | from decimal import Decimal 26 | from eth_defi.token import fetch_erc20_details 27 | from eth_defi.trace import assert_transaction_success_with_explanation 28 | from eth_defi.enzyme.vault import Vault 29 | 30 | print("Using RPC provider", web3.provider) 31 | 32 | transfer_amount = Decimal(5004) 33 | target_address = "0xC9E60a9605a67c408a16c47652070Aa5E28ddD64" 34 | 35 | print(f"Sending USDC from our hot wallet {hot_wallet.address}, amount {transfer_amount} USDC") 36 | usdc_address = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" # USDC on Ethereum 37 | usdc = fetch_erc20_details(web3, usdc_address) 38 | our_address = hot_wallet.address 39 | 40 | out_gas_balance = web3.eth.get_balance(hot_wallet.address) / (10**18) 41 | our_usdc_balance = usdc.fetch_balance_of(our_address) 42 | assert our_usdc_balance > transfer_amount, f"We have only {our_usdc_balance} USDC at {hot_wallet.address}, we need {transfer_amount} USDC" 43 | 44 | raw_amount = usdc.convert_to_raw(transfer_amount) 45 | 46 | tx_hash = usdc.contract.functions.transfer( 47 | target_address, 48 | raw_amount, 49 | ).transact({"from": hot_wallet.address}) 50 | print(f"Transfer in TX {tx_hash.hex()}") 51 | assert_transaction_success_with_explanation(web3, tx_hash) 52 | print(f"All done") 53 | 54 | Sending a transaction through the vault 55 | --------------------------------------- 56 | 57 | TODO: See vault deployment chapter for examples. 58 | 59 | .. note :: 60 | 61 | The transaction will be checked by the onchain guard smart contract, and it will be reverted 62 | if it does not adhere guard's rules. -------------------------------------------------------------------------------- /source/getting-started.rst: -------------------------------------------------------------------------------- 1 | Getting started 2 | =============== 3 | 4 | Trading Strategy is a solution for algorithmic trading on decentralised markets: 5 | 6 | * To access DeFi market data, decentralised exchanges like lending protocols, 7 | in free APIs and batch download files 8 | 9 | * Develop trading strategies in Python using Trading Strategy framework, 10 | tailored for automated DeFi trading 11 | 12 | * Backtest trading stragies across hundreds of thousands 13 | of DEX trading pairs on protocols like Uniswap, Aave, PancakeSwap 14 | 15 | * Turn key solution to take your backtested strategy to live trading 16 | 17 | * Raise capital for your trading strategies by using vault protocol integrations like Enzyme Finance 18 | and Velvet Finance 19 | 20 | .. note :: 21 | 22 | If you are new to the Trading Strategy framework or algorithmic trading in general, 23 | please start by watching `the recorded workshop tutorial session from Avalanche Summit `__. 24 | 25 | Explore DeFi market data 26 | ------------------------ 27 | 28 | If you want to explore DeFi market data 29 | 30 | - `Visit Trading Strategy website trading data section `_ to start exploring data feeds 31 | 32 | - `Use Trading Strategy advanced search to find trading pairs and tokens `_ 33 | 34 | Write your own trading strategies 35 | --------------------------------- 36 | 37 | If you want to trade using algorithms on DeFi markets 38 | 39 | - Read :doc:`Getting started coding tutorial ` 40 | how to get started with Python and DeFi data research 41 | 42 | - See our :doc:`example strategies ` 43 | 44 | Learn about Trading Strategy protocol 45 | ------------------------------------- 46 | 47 | See :ref:`protocol` section for more information about Trading Strategy protocol, 48 | its stakeholders and protocol components. 49 | 50 | Learn about algorithmic trading 51 | ------------------------------- 52 | 53 | See :ref:`learning` section for references to books and tutorials. 54 | 55 | More questions? 56 | --------------- 57 | 58 | For any question, come to our `community Discord `_. -------------------------------------------------------------------------------- /source/home.rst: -------------------------------------------------------------------------------- 1 | Documention home 2 | ================ 3 | 4 | Redirects to the :ref:`table of contents`. -------------------------------------------------------------------------------- /source/index.rst: -------------------------------------------------------------------------------- 1 | .. meta:: 2 | :description: Trading Strategy technical documentation 3 | 4 | .. _documentation: 5 | 6 | Trading Strategy documentation 7 | ============================== 8 | 9 | This is the technical documentation for Trading Strategy algorithmic trading framework and protocol. 10 | 11 | .. image:: landing-page-splash.png 12 | 13 | The documentation is divided into three parts: overview, trading strategy development framework and trading strategy protocol. 14 | 15 | .. note :: 16 | 17 | If you want to get started with writing or porting your own algorithms, you can directly jump to 18 | `Getting started Github repository `__, which 19 | provides Github Codespaces cloud environment and Visual Studio Code Dev Container 20 | to develop and backtest strategies right away. 21 | 22 | .. _table of contents: 23 | 24 | Table of contents 25 | ----------------- 26 | 27 | .. toctree:: 28 | :maxdepth: 1 29 | 30 | home 31 | getting-started 32 | overview/index 33 | programming/index 34 | architecture/index 35 | deployment/index 36 | learn/index 37 | glossary 38 | api/index 39 | 40 | See also 41 | -------- 42 | 43 | This is the landing page for the technical documentation. 44 | Quick links to elsewhere: 45 | 46 | - `Website `_ 47 | - `About Trading Strategy `_ 48 | - `Community Discord for questions `_ 49 | -------------------------------------------------------------------------------- /source/landing-page-splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/landing-page-splash.png -------------------------------------------------------------------------------- /source/learn.html: -------------------------------------------------------------------------------- 1 | Learn 2 | ---- -------------------------------------------------------------------------------- /source/learn/additional-resources.rst: -------------------------------------------------------------------------------- 1 | Additional algorithmic trading links 2 | ==================================== 3 | 4 | A collection of random links and notes that are not a good fit for other learning categories. 5 | 6 | Miscellaneous 7 | ------------- 8 | 9 | - `Using tqdm progress bars in notebooks `__. 10 | 11 | - `Forecasting prices `__. 12 | 13 | - `Adding custom DataFrames to Backtrader `__. 14 | 15 | - `Tracking multiple data feeds with Backtrader `__. 16 | 17 | - `Multiple data feeds with Backtrader - tutorial `__. 18 | 19 | - `Classifying Uniswap scams and rug pulls with machine learning `__. 20 | 21 | - `Detecting scams on Uniswap `__. 22 | 23 | - `Backtesting Uniswap v3 strategies `_ 24 | 25 | - `The 7 Reasons Most Machine Learning Funds Fail `_ 26 | 27 | - `The Case for Variable Fees in Constant Product Markets: An Agent Based Simulation `__ 28 | 29 | - `Hurst Exponent to Identify Trading Strategies `__ 30 | 31 | - `Automated Market Makers: Mean-Variance Analysis of LPs Payoffs and Design of Pricing Functions `__ 32 | 33 | - `On Uniswap listing bots `_ 34 | 35 | - `Blockchain SaaS node provider latency comparison `__ 36 | 37 | - `Awesome On-Chain Investigations HandBook `__ 38 | 39 | - `Uniswap v3 liquidity provider strategies `__ 40 | 41 | - `Uniswap V3 TWAP: Assessing TWAP Market Risk `__ and `the related portal `__ 42 | 43 | - `Liquidity Provider Strategies for Uniswap v3: Dynamic Hedging `__ 44 | 45 | - `In-Sample vs. Out-Of-Sample Analysis of Trading Strategies `__ 46 | 47 | - `Awesome Conformal Prediction for time series `__ 48 | 49 | - `Portfolio Optimization in Python With Datalore and AI Assistant `__ 50 | 51 | Risk, portfolio construction, optimization, and factor essentials 52 | ----------------------------------------------------------------- 53 | 54 | Risk and Portfolio Construction 55 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 56 | 57 | "Advanced Portfolio Management" (Paleologo) https://buff.ly/3Jn0hcj 58 | "Active Portfolio Management" (Grinold & Kahn) https://buff.ly/3Z3ooUr 59 | "Advances in Active Portfolio Management" (G&K) https://buff.ly/3VrgIeP 60 | "Quantitative Equity Portfolio Management" https://buff.ly/3r6vYkC 61 | "Quantitative Portfolio Management" https://buff.ly/44wamvO 62 | "Portfolio Risk Analysis" (Connor & Goldberg) https://buff.ly/3yDK5RW 63 | "Equity Portfolio Management" (Fabozzi) https://buff.ly/3qWKBHd 64 | "Modern Invesment Management" (Litterman/GSAM) https://buff.ly/3PqZF9K 65 | 66 | Factor Models & Related 67 | ~~~~~~~~~~~~~~~~~~~~~~~ 68 | 69 | "Modeling Equities Returns: The Linear Case" (Zhang, HRT) https://buff.ly/4e9t1DB 70 | "Factor Models of Asset Returns" (Connor) https://buff.ly/3V5g852 71 | "The Econometrics of Financial Markets" (Campbell & Lo) https://buff.ly/3Vfa4XM 72 | "Multi-factor Models & Signal Processing Techniques" https://buff.ly/3RdeQUh 73 | "Elements of Quantitative Investing" (Paleologo) https://buff.ly/4566DqM 74 | "Asset Management: Systematic Factor Investing" (Ang) https://buff.ly/4e7Hr7h 75 | "Finding Alphas" (Tulchinsky) https://buff.ly/4bG4c0H 76 | "Practioner's Guide to Factor Models" (CFA, 1994) https://buff.ly/4bIxR9r 77 | "The Remarkable Multidimensionality in Stock Returns" https://buff.ly/3yLNJJA 78 | 79 | Optimization 80 | ~~~~~~~~~~~~ 81 | 82 | "Dispelling Myths in Mean-Variance Optimization" https://buff.ly/4aKIs2j 83 | "Portfolio Optimization Cookbook" (Mosek) https://buff.ly/3Va7uC4 84 | "Multi-Period Trading via Complex Optimization" (Boyd) https://buff.ly/4aGJf4k 85 | "Optimal Turnover" (Baldacci, more t cost emphasis) https://buff.ly/3V5bZhf 86 | 87 | Broader list of mathematical finance references: https://buff.ly/3tH37Vb -------------------------------------------------------------------------------- /source/learn/algorithmic-trading-frameworks.rst: -------------------------------------------------------------------------------- 1 | Algorithmic trading frameworks for Python 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | 4 | See also :doc:`AI and machine learning topics <./ai-and-machine-learning.rst>` if you are especially looking for AI-based trading solutions. 5 | 6 | Trading Strategy 7 | ---------------- 8 | 9 | Trading Strategy is the next generation algorithmic trading protocol for decentralised markets. 10 | 11 | It includes 12 | 13 | - Market data fetch 14 | - Backtesting and strategy development framework 15 | - Live trade execution 16 | - Capital and investor management with smart contract-based vaults 17 | 18 | `View website `__. 19 | 20 | Demeter 21 | ------- 22 | 23 | Demeter is a :term:`liquidity provision` :term:`backtest` framework for :term:`Uniswap`, :term:`Aave` 24 | and other :term:`decentralised finance` protocols. 25 | 26 | Demeter allows you to simulate :term:`high-frequency trading` :term:`market making` using :term:`Python` code. 27 | 28 | Demeter is good for backtesting 29 | 30 | - :term:`CLMM` strategies 31 | 32 | - :term:`Delta hedged` strategies (e.g. with Aave) 33 | 34 | - :term:`Gamma hedged` strategies (e.g. with decentralised options market places like Aevo or Derive) 35 | 36 | Examples of Demeter strategies are available in `Trading Strategy's Getting started `__ repository. 37 | 38 | See -`Demeter website `__ by Zelos Alpha. 39 | 40 | .. _backtrader: 41 | 42 | Backtrader 43 | ---------- 44 | 45 | **Backtrader is no longer maintained**. 46 | 47 | Backtrader is one of the oldest and most popular Python based backtesting frameworks. It supports live trading. Direct support for Jupyter notebooks. `Read more on BackTrader `__. 48 | 49 | 50 | .. _qstrader: 51 | 52 | QsTrader 53 | -------- 54 | 55 | **QsTrader is no longer maintained**. 56 | 57 | QsTrader is a portfolio optimisation backtesting framework for Python. It originally focused on ETFs and stock. `Read more on QsTrader `__. 58 | 59 | Fastquant 60 | --------- 61 | 62 | **FastQuant is no longer maintained**. 63 | 64 | A simplified one-liner backtesting solution built on the top of Backtrader. `Read more `__. 65 | 66 | Zipline Reloaded 67 | ---------------- 68 | 69 | Continued work of the famous ZipLine library that was created by now defunctional Quantopian. `Read more `__. 70 | 71 | AlphaPy 72 | ------- 73 | 74 | AlphaPy is a machine learning framework for both speculators and data scientists. It is written in Python mainly with the scikit-learn and pandas libraries, as well as many other helpful packages for feature engineering and visualization. `Read more `__. 75 | 76 | bt 77 | -- 78 | 79 | bt is a flexible backtesting framework for Python used to test quantitative trading strategies. The framework allows you to easily create strategies that mix and match different Algos. It aims to foster the creation of easily testable, re-usable and flexible blocks of strategy logic to facilitate the rapid development of complex trading strategies. `Read more `__. 80 | 81 | 82 | AlphaLens 83 | --------- 84 | 85 | Alpha factor library for ZipLine. `Read more `__. 86 | 87 | PyFolio 88 | ------- 89 | 90 | Performance and risk analysis for portfolios. `Read more `__. 91 | 92 | PyAlgoTrade 93 | ----------- 94 | 95 | Was originally written for Bitstamp. Offers backtesting, paper trading, live trading. Looks abandoned now. `Read more `__. 96 | 97 | LEAN 98 | ---- 99 | 100 | Lean Engine is an open-source algorithmic trading engine built for easy strategy research, backtesting and live trading. We integrate with common data providers and brokerages so you can quickly deploy algorithmic trading strategies. 101 | 102 | The core of the LEAN Engine is written in C#; but it operates seamlessly on Linux, Mac and Windows operating systems. It supports algorithms written in Python 3.8 or C#. Lean drives the web-based algorithmic trading platform QuantConnect. 103 | 104 | `View LEAN Github page `__. 105 | 106 | FreqTrade 107 | --------- 108 | 109 | Freqtrade is a free and open source crypto trading bot written in Python. It is designed to support all major exchanges and be controlled via Telegram or webUI. It contains backtesting, plotting and money management tools as well as strategy optimization by machine learning. 110 | 111 | `View FreqFrade on Github `__. 112 | 113 | Gekko 114 | ----- 115 | 116 | **Gekko is no longer maintainer**. 117 | 118 | Gekko is an open source platform for automating trading strategies over bitcoin markets. 119 | 120 | `View Gekko homepage `__. 121 | 122 | HftBacktest 123 | ----------- 124 | 125 | This framework is designed for developing high-frequency trading and market-making strategies. It focuses on accounting for both feed and order latencies, as well as the order queue position for order fill simulation. The framework aims to provide more accurate market replay-based backtesting, based on full order book and trade tick feed data. 126 | 127 | Written in Python and Rust. 128 | 129 | - Complete tick-by-tick simulation with a variable time interval. 130 | - Full order book reconstruction based on L2 feeds(Market-By-Price). 131 | - Backtest accounting for both feed and order latency, using provided models or your own custom model. 132 | - Order fill simulation that takes into account the order queue position, using provided models or your own custom model. 133 | 134 | `View homepage `__. 135 | 136 | -------------------------------------------------------------------------------- /source/learn/charting-solutions.rst: -------------------------------------------------------------------------------- 1 | Charting solutions for Python 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | 4 | Charting solutions for Jupyter Notebook and Python. 5 | 6 | - `Plotly `__ 7 | 8 | - `Different candlestick chart libraries for Jupyter. `__. 9 | 10 | - `Cufflinks tutorial `__ 11 | 12 | - `Beautiful charts in Jupyter Notebooks. `__ 13 | 14 | - `Google Colab charts example `__. 15 | 16 | - `Interesting 3d distribution diagrams `__ 17 | 18 | - `Limit order book visualisation `__ 19 | 20 | - `Bookmap `__ 21 | 22 | - `Market depth historical graph `__ 23 | -------------------------------------------------------------------------------- /source/learn/communities.rst: -------------------------------------------------------------------------------- 1 | Communities around algorithmic trading 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | 4 | Trading Strategy Discord 5 | ------------------------ 6 | 7 | Join Discord server to to discuss about algorithmic trading decentralised markets. 8 | 9 | `Join Discord `__. 10 | 11 | Pyquant News 12 | ------------ 13 | 14 | Level up with Python for quantitative and data analysis. 15 | Join 3,600+ subscribers to the PyQuant Newsletter. Every Saturday morning, you'll get Python code you can use right now for quantitative & data analysis. 16 | 17 | `Subscribe to the newsletter `__. 18 | 19 | Algotrading on Reddit 20 | ------------------------------- 21 | 22 | A place for redditors to discuss quantitative trading, statistical methods, econometrics, programming, implementation, automated strategies, and bounce ideas off each other for constructive criticism. Feel free to submit papers/links of things you find interesting. 23 | 24 | `View Subreddit `__ 25 | 26 | Awesome Quant Github repository 27 | ------------------------------- 28 | 29 | A curated list of insanely awesome libraries, packages and resources for Quants (Quantitative Finance). 30 | 31 | `View Github repository `__ 32 | 33 | Machine Learning for Trading 34 | ---------------------------- 35 | 36 | Managed by Stefan Jansen zalongside the ZipLine reloaded and his book Machine Learning for Algorithmic Trading. `View forum `__. 37 | 38 | Develop tools and Jupyter Notebook environments 39 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 40 | 41 | Here are some tools for developing and running :term:`Jupyter notebooks `, 42 | which are the foundation of all data research. 43 | 44 | Locally installable applications 45 | 46 | * :term:`Visual Studio Code` 47 | 48 | * :term:`PyCharm` 49 | 50 | Cloud based 51 | 52 | * :term:`Google Colab` 53 | 54 | * `Binder `_ turns a Github repository to executable Jupyter Python notebooks. 55 | 56 | * Github Codespaces 57 | 58 | * Jupyter Hub 59 | 60 | * `Datalore from Jetbrain `_ -------------------------------------------------------------------------------- /source/learn/conference-presentations.rst: -------------------------------------------------------------------------------- 1 | .. meta:: 2 | :description: YouTube videos on algorithmic trading 3 | 4 | Conference presentations and videos 5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 6 | 7 | PyChain 2022 8 | ------------ 9 | 10 | Watch various presentations in `PyChain 2022 YouTube channel `__. 11 | PyChain was an virtual conference for Python blockchain developers and traders. 12 | 13 | - `Bringing Your Automated Trading Strategy to Decentralised Market by Teemu Sorvisto `__ 14 | 15 | - `Backtesting Crypto Trading Strategies by David Florysiak `__ 16 | 17 | - `The Anatomy Of An Machine Learning Powered Stock Picking Engine by Anshuman Mishra `__ 18 | 19 | - `On-Chain Analysis For Algorithmic Trading by Marek Hakala, Parity `__ 20 | 21 | - `Opportunities For Trading Bots With DeFi Options by Ali Nuraldin, Opium Network `__ 22 | 23 | ... `any many others `__. -------------------------------------------------------------------------------- /source/learn/courses.rst: -------------------------------------------------------------------------------- 1 | Online courses on algorithmic trading 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | 4 | Getting Started With Python for Quant Finance 5 | --------------------------------------------- 6 | 7 | Getting Started With Python for Quant Finance is the cohort-based course and community that will take you from complete beginner to up and running with Python for quant finance in 30 days. 8 | It contains 51-lesson curriculum you can review at your own pace and 10 live sessions. 9 | 10 | You’ll find practical, real-life problems to solve. Then use pre-built code templates to accelerate your learning, stay consistent, and get experience to break free of the constraints that are holding you back from your goals. 11 | 12 | The course is organised by Jason Strimpel. 13 | 14 | `View course `__. 15 | 16 | Master AI-Driven Algorithmic Trading 17 | ------------------------------------ 18 | 19 | This is an intense online training program about Python techniques for algorithmic trading. By signing up to this program you get access to 150+ hours of live/recorded instruction, 1,200+ pages PDF as well as 5,000+ lines of Python code and 60+ Jupyter Notebooks (read the 16 week study plan). Master AI-Driven Algorithmic Trading, get started today. 20 | 21 | `Read more `__. 22 | 23 | Universities offering blockchain education 24 | ------------------------------------------ 25 | 26 | There are several top tier universities offering courses on the blockchaine education. 27 | 28 | `See this Cointelegraph post for details `__. 29 | 30 | -------------------------------------------------------------------------------- /source/learn/index.rst: -------------------------------------------------------------------------------- 1 | .. _learning: 2 | 3 | .. meta:: 4 | :description: Learn algorithmic trading with Python and AI. 5 | 6 | 7 | Learn algorithmic trading 8 | ========================= 9 | 10 | We have compiled resources for learning algorithmic trading, decentralised finance, and technical analysis. 11 | 12 | - See below our link collection for books, tutorials and courses. 13 | 14 | - If you are already familiar with :term:`algorithmic trading` and you want to program using Trading Strategy framework 15 | to trade on :term:`decentralised exchanges ` you can directly hop into :ref:`Getting started tutorial `. 16 | 17 | - If you have questions or need more hand holding please come to our `Trading Strategy online community discussion `__ for a chat. 18 | 19 | - If you are new to DeFi and automated, you can also browser `DeFi and trading dictionary `__ to learn the industry vocabulary. 20 | 21 | 22 | Algorithmic trading learning resources 23 | -------------------------------------- 24 | 25 | .. toctree:: 26 | :maxdepth: 1 27 | 28 | influencers 29 | conference-presentations 30 | books 31 | courses 32 | tutorials 33 | ai-and-machine-learning 34 | papers 35 | python 36 | jupyter-notebook 37 | algorithmic-trading-frameworks 38 | communities 39 | charting-solutions 40 | additional-resources 41 | 42 | 43 | Trading Strategy's learning material 44 | ------------------------------------ 45 | 46 | .. toctree:: 47 | :maxdepth: 1 48 | 49 | posts/portfolio-construction/portfolio-construction-model.rst 50 | -------------------------------------------------------------------------------- /source/learn/influencers.rst: -------------------------------------------------------------------------------- 1 | To follow 2 | ========= 3 | 4 | Here are some quant trades and macro traders to follow, on Twitter and LinkedIn. 5 | They often share good insights into the markets, free :term:`alpha` and strategy ideas. 6 | 7 | Quant trades on Twitter (now known as X) 8 | ---------------------------------------- 9 | 10 | - `Pavel Kycek `__ 11 | - `pedma `__ 12 | - `rysky.eth `__ 13 | - `Andreas Himmelreich `__ 14 | - `Systematic Peter `__ 15 | - `QuantSeeker `__ 16 | - `Robot James `__ 17 | - `Chief Number Optimizer `__ 18 | - `Quant Science `__ 19 | - `Piotr Pomorski `__ 20 | - `Hakan `__ 21 | - `TradeQuantiX `__ 22 | - `Stat Arb `__ 23 | - `Zion Trading Algos `__ 24 | - `qm `__ 25 | - `Ali Martinez `__ 26 | - `Concretum Research `__ 27 | - `onchainquant `__ 28 | 29 | Quant trades on LinkedIn 30 | ------------------------ 31 | 32 | - `Nick Francis `__ 33 | - `Lucas Inglese `__ 34 | - `Kurtis Hemmerling `__ 35 | - `Lou Lindley `__ 36 | - `Doug Busch `__ 37 | - `Lou Lindley `__ 38 | - `Aditya Narayan Garnaik `__ 39 | 40 | Macro trades on Twitter 41 | ----------------------- 42 | 43 | - `Michael J. Kramer `__ 44 | - `Michael Melissinos `__ 45 | - `Robin Brooks `__ 46 | - `Michael Antonelli `__ 47 | - `Kacper Piotr Kaminski `__ 48 | - `David Woo `__ 49 | 50 | Macro trades on LinkedIn 51 | ------------------------ 52 | 53 | - `Mitchell Askew `__ 54 | - `Charles-Henry Monchau `__ 55 | - `Dr. Maximilian Bader `__ 56 | - `Alfonso Peccatiello `__ 57 | - `Robert Karas `__ 58 | - `Mario Ottaiano `__ 59 | - `John Reade `__ -------------------------------------------------------------------------------- /source/learn/jupyter-notebook.rst: -------------------------------------------------------------------------------- 1 | Jupyter Notebook learning material 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | 4 | Jupyter Notebook basics 5 | ----------------------- 6 | 7 | A tutorial by Dataquest. 8 | 9 | `Read more `__. 10 | 11 | Pandas Illustrated: The Definitive Visual Guide to Pandas 12 | --------------------------------------------------------- 13 | 14 | Visual guide to Pandas functions. 15 | 16 | `Read the post `__. 17 | 18 | Vectorised backtesting with Pandas 19 | ---------------------------------- 20 | 21 | A tutorial by Yao Lei Xu. 22 | 23 | `Read more `__. 24 | -------------------------------------------------------------------------------- /source/learn/liquidity-provision.rst: -------------------------------------------------------------------------------- 1 | Liquidity provision 2 | ~~~~~~~~~~~~~~~~~~~ 3 | 4 | How to become a :term:`liquidity provider` (:term:`market maker`) on :term:`CLMM` and :term:`AMM` :term:`DEXes `. 5 | 6 | See :doc:`papers <./papers>` for more advanced learning material. 7 | 8 | Tools 9 | ===== 10 | 11 | Revert Finance 12 | -------------- 13 | 14 | A tool website to watch Uniswap 3 LP positions. 15 | 16 | `View website `__. 17 | 18 | Papers 19 | ====== 20 | 21 | What Drives Liquidity on Decentralized Exchanges? Evidence from the Uniswap Protocol 22 | ------------------------------------------------------------------------------------ 23 | 24 | We empirically study liquidity and market depth on decentralized exchanges (DEXs), identifying factors at the blockchain, token pair, and pool levels that predict future effective spreads for fixed trade sizes on Uniswap v3 pools. Introducing the v2 counterfactual spread metric, a novel criterion that assesses the degree of liquidity concentration in pools using the ``concentrated liquidity'' mechanism, we decompose the effect of each factor on market depth into two channels: total value locked (TVL) and concentration. We further explore how external liquidity from competing DEXs and fillers with private inventory on DEX aggregators influence market depth. We find, for moderately-sized swaps, that (i) gas prices, returns, and volatility affect spreads primarily through concentration, (ii) internalization of swaps by private liquidity sources affects spreads primarily through TVL, and (iii) fee revenue, markout, and DEX competition affect spreads through both channels. 25 | 26 | `Read the paper `__ 27 | 28 | Providing Liquidity in Uniswap V3 29 | --------------------------------- 30 | 31 | One of the largest :term:`DEX` :term:`Uniswap` released their version v3 in 2021 and introduced 32 | the concept of concentrated liquidity. Now liquidity providers in Uniswap v3 33 | need to choose a range in which they want to provide liquidity. We built a 34 | robust and precise backtester based on the original Uniswap v3 smart contract 35 | and used it to test eleven different strategies for liquidity providers. We analyzed 36 | those strategies on the USDC-ETH pool with 0.05% transaction fee. We found 37 | strategies that performed really well when Ethereum was going up, but most of 38 | these strategies did not perform so well when Ethereum was going down. We 39 | also analyzed the delta of liquidity provision strategies. 40 | 41 | `Read the paper `__ 42 | 43 | Opportunity Costs and Profitability: Insights into LP Behavior 44 | -------------------------------------------------------------- 45 | 46 | Analysis on which :term:`liquidity providers ` are profitable on :term:`Uniswap` v3. 47 | 48 | `Read the post `__ 49 | 50 | Backtesting Framework for Concentrated Liquidity Market Makers on Uniswap V3 Decentralized Exchange 51 | --------------------------------------------------------------------------------------------------- 52 | 53 | Decentralized finance (DeFi) has revolutionized the financial landscape, with protocols like Uniswap 54 | offering innovative automated market-making mechanisms. This article explores the development of 55 | a backtesting framework specifically tailored for concentrated liquidity market makers (CLMM). The 56 | focus is on leveraging the liquidity distribution approximated using a parametric model, to estimate 57 | the rewards within liquidity pools. The article details the design, implementation, and insights derived 58 | from this novel approach to backtesting within the context of Uniswap V3. The developed backtester 59 | was successfully utilized to assess reward levels across several pools using historical data from 2023 60 | (pools Uniswap v3 for pairs of altcoins, stablecoins and USDC/ETH with different fee levels). Moreover, 61 | the error in modeling the level of rewards for the period under review for each pool was less than 1%. 62 | This demonstrated the effectiveness of the backtester in quantifying liquidity pool rewards and its 63 | potential in estimating LP’s revenues as part of the pool rewards, as focus of our next research. The 64 | backtester serves as a tool to simulate trading strategies and liquidity provision scenarios, providing a 65 | quantitative assessment of potential returns for liquidity providers (LP). By incorporating statistical 66 | tools to mirror CLMM pool liquidity dynamics, this framework can be further leveraged for strategy 67 | enhancement and risk evaluation for LPs operating within decentralized exchanges. 68 | 69 | `Read the paper `__ 70 | -------------------------------------------------------------------------------- /source/learn/posts/portfolio-construction/equity-curve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/learn/posts/portfolio-construction/equity-curve.png -------------------------------------------------------------------------------- /source/learn/posts/portfolio-construction/position-table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/learn/posts/portfolio-construction/position-table.png -------------------------------------------------------------------------------- /source/learn/posts/portfolio-construction/summary-stats-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/learn/posts/portfolio-construction/summary-stats-example.png -------------------------------------------------------------------------------- /source/learn/python.rst: -------------------------------------------------------------------------------- 1 | .. meta:: 2 | :description: How to learn Python, online and with books 3 | 4 | Python 5 | ====== 6 | 7 | Python is the de facto programming language of data science and quant finance. 8 | Python is the second most popular language on Github, and a safe bet 9 | for the future software developer career development. 10 | 11 | Here is a collection of resources to start learning Python. 12 | 13 | - Books 14 | 15 | - Online courses 16 | 17 | - Communities for Python learning 18 | 19 | See also :doc:`AI and machine learning topics <./ai-and-machine-learning.rst>`. 20 | 21 | Online courses to learn Python 22 | ------------------------------ 23 | 24 | `See discussion on Reddit `__. 25 | 26 | Learn Python Reddit 27 | ------------------- 28 | 29 | A Reddit community for Python learning questions. 30 | 31 | `Go to /r/LearnPython `__. 32 | 33 | Learn Python Wiki 34 | ----------------- 35 | 36 | Community managed wiki for learning Python resources on Reddit. 37 | 38 | `Visit wiki in Reddit `__. 39 | 40 | The official Python's beginners guide 41 | ------------------------------------- 42 | 43 | Python's beginner guide on the official Python wiki. 44 | 45 | `View guide at python.org `__. 46 | 47 | pythonbooks.org 48 | --------------- 49 | 50 | A site dedicated to the published books about Python programming. 51 | 52 | `View pythonbooks.org `__. 53 | 54 | Python For Kids 55 | --------------- 56 | 57 | Python for Kids brings Python to life and brings kids (and their parents) into the wonderful world of programming. Author Jason R. Briggs guides readers through the basics, experimenting with unique (and often hilarious) example programs that feature ravenous monsters, secret agents, thieving ravens, and more. New terms are defined; code is coloured, dissected, and explained; and quirky, full-colour illustrations keep things fun and engaging throughout. 58 | 59 | `View book on Amazon `__. 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /source/learn/tutorials.rst: -------------------------------------------------------------------------------- 1 | Tutorials on algorithmic trading 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | 4 | Here is a collection of blog posts and tutorials that are relevant for algorithmic trading in Python. 5 | 6 | Financial Models and Numerical Methods 7 | --------------------------------------- 8 | 9 | A collection of Jupyter notebooks based on different topics in the area of quantitative finance. 10 | 11 | `Read more `__. 12 | 13 | Gallery of Jupyter Books 14 | ------------------------ 15 | 16 | Multiple data research and quantative finance books for Python and Jupyter 17 | 18 | `View gallery at Executable Books `__ 19 | 20 | Teddy Koker's blog 21 | ------------------ 22 | 23 | Articles on trading, gambling and machine learning. 24 | 25 | `Read blog `__. 26 | 27 | Backtesting option strategy with Backtrader 28 | ------------------------------------------- 29 | 30 | An example tutorial. 31 | 32 | `Read post `__. 33 | 34 | ML Algotrading Wiki 35 | ------------------- 36 | 37 | A wiki website with research and various news sources. 38 | 39 | `MLTraders’ Algotrading and Machine Learning work for everybody. `__. 40 | 41 | Pair Trading: A market-neutral trading strategy with integrated Machine Learning 42 | -------------------------------------------------------------------------------- 43 | 44 | The primary goal in an investment endeavor is the implementation of strategies that minimize the risk while also maximizing the financial gain or return from the said investment. While there have been many popular strategies and techniques developed over the years that point towards the same goal, the 'Pairs-Trading' strategy is one that has been used to great extent in modern hedge-funds, for its simplicity and inherent market-neutral qualities. 45 | 46 | `Read post `__. 47 | 48 | Dead Simple 2-Asset Portfolio that Crushes the S&P500 49 | ----------------------------------------------------- 50 | 51 | This is an update to the original blog series that explored a simple strategy of being long UPRO and TMF in equal weight, inverse volatility and inverse-inverse volatility. This strategy crushed the cumulative and risk-adjusted returns of the benchmark SPY etf. 52 | 53 | `Read post `__. 54 | 55 | Didact AI 56 | --------- 57 | 58 | The anatomy of an ML-powered stock picking engine. 59 | 60 | `Read post `__. 61 | 62 | Trend following regime filter with HMM 63 | -------------------------------------- 64 | 65 | In this article the Hidden Markov Model will be utilised within the QSTrader framework as a risk-managing market regime filter. It will disallow trades when higher volatility regimes are predicted. The hope is that by doing so it will eliminate unprofitable trades and possibly remove volatility from the strategy, thus increasing its Sharpe ratio. 66 | 67 | `Read post `__. 68 | 69 | Uniswap v3 and Aave delta hedged strategy 70 | ----------------------------------------- 71 | 72 | A blog outlining an example trading strategy creating Uniswap V3 :term:`liquidity provision` position 73 | which is :term:`delta hedged` using :term:`Aave` :term:`lending protocol`. 74 | 75 | `Read post `__. -------------------------------------------------------------------------------- /source/notes.txt: -------------------------------------------------------------------------------- 1 | --- Random notes and scratchpad 2 | 3 | 4 | Volatility basket 5 | 6 | A volatility basket is a :term:`portfolio construction` :term:`trading strategy` where assets are picked 7 | by their :term:`volatility`. 8 | 9 | Volatility measures 10 | 11 | - Magnitude of price fluctuation 12 | * A higher volatility number indicates greater variability in returns, meaning the asset or portfolio experiences more dramatic swings in value. This can imply higher risk, as the asset's price is more unpredictable. 13 | * A lower volatility number suggests smaller fluctuations, implying that the asset or portfolio is more stable over the measured period. 14 | - Relative risk 15 | * Volatility allows investors to compare the risk of different assets or :term:`portfolios `. For example, an asset with 20% volatility is considered riskier than one with 10% volatility over the same period. 16 | - Impact on expected returns 17 | * While high volatility does not directly correlate with higher returns, assets with higher volatility are often associated with higher potential returns (and losses), as they tend to make larger movements. 18 | 19 | Volatility basket strategy can 20 | 21 | - Calculate the trailing volatility of the asset for a certain period time (weeks, months) to benchmark different assets. 22 | - Include multiple assets that may have different volatility characteristics—some with high volatility, others with low volatility, and potentially even inverse relationships. 23 | - Be around a certain sector (see :term:`factor investing`). 24 | - Go degen and pick only assets with the highest volatility. 25 | - Because :term:`volatility` metric itself does not tell the direction of asset price, 26 | a strategy may use its derivative like :term:`Sharpe` ratio which also includes whether asset made positive or negative returns (to long or to short). 27 | 28 | See also 29 | 30 | - :term:`Volatility` 31 | 32 | - :term:`Portfolio construction` 33 | 34 | - :term:`Portfolio` 35 | 36 | - :term:`Sharpe` 37 | 38 | - :term:`Trading strategy` 39 | 40 | - :term:`Risk-adjusted return` -------------------------------------------------------------------------------- /source/overview/about.rst: -------------------------------------------------------------------------------- 1 | .. _about: 2 | 3 | About Trading Strategy 4 | ====================== 5 | 6 | Trading Strategy provides tools to do algorithmic and sophisticated trading in 7 | decentralised finance markets. 8 | 9 | - :doc:`Market data feeds <./market-data-feeds>` for decentralised finance protocols 10 | 11 | - :doc:`Strategy development and backtesting ` framework in Python 12 | 13 | - :ref:`Trade execution and running strategies ` for decentralised exchanges 14 | 15 | - :ref:`A decentralised protocol ` for deploying strategies as smart contracts for DeFi users 16 | 17 | - `A community of sophisticated DeFi traders and strategy developers `_ 18 | 19 | For more general overview, `see overview on the main website `_. 20 | -------------------------------------------------------------------------------- /source/overview/index.rst: -------------------------------------------------------------------------------- 1 | Overview 2 | ======== 3 | 4 | This technical documentation section gives an introduction to the 5 | different parts of Trading Strategy :ref:`market data `, 6 | :ref:`strategy development framework ` and :ref:`protocol `. 7 | 8 | Overview 9 | -------- 10 | 11 | 12 | .. toctree:: 13 | :maxdepth: 1 14 | 15 | about 16 | supported-markets 17 | market-data-feeds 18 | tooling 19 | oracles 20 | 21 | 22 | -------------------------------------------------------------------------------- /source/overview/market-data-feeds.rst: -------------------------------------------------------------------------------- 1 | .. _market data: 2 | 3 | .. _trading data: 4 | 5 | Accessing market data 6 | ===================== 7 | 8 | To efficiently trade, a high quality information about markets is needed. 9 | Trading Strategy provides various :term:`market data feeds ` 10 | that trades can use to trade on :term:`DeFi markets ` and :term:`decentralised exchanges `. 11 | 12 | Explore data 13 | ------------ 14 | 15 | You can explore `the available data on Trading Strategy market data pages `_. 16 | You will find the lists of decentralised exchanges, trading pairs, price charts and metadata. 17 | 18 | Not all trading pairs and tokens are included in the dataset. See :ref:`tracking` for more information about inclusion criteria. 19 | 20 | 21 | Data flavours 22 | ------------- 23 | 24 | Real-time API 25 | ~~~~~~~~~~~~~ 26 | 27 | `Real-time API `__ for live trading and price charts. 28 | 29 | See `OpenAPI explorer `__ for available APIs. 30 | 31 | Backtesting datasets API 32 | ~~~~~~~~~~~~~~~~~~~~~~~~ 33 | 34 | `Backtesting datasets `_ for testing strategies. 35 | 36 | Microsoft Excel data files 37 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 38 | 39 | For some datasets, like the best performing trading pairs, there is direct Microsoft Excel export available. 40 | 41 | `See PancakeSwap trading pairs `_ as an example. 42 | 43 | 44 | Accessing data 45 | -------------- 46 | 47 | You can access market data 48 | 49 | - Programmatically using API 50 | 51 | - Download datasets manually 52 | 53 | Programmatic access may require an API key 54 | 55 | - Real-time API does not require authentication 56 | 57 | - Backtesting data requires authentication by an API key due to large size of served files 58 | 59 | API key registration 60 | ~~~~~~~~~~~~~~~~~~~~ 61 | 62 | You can get a free `API key with a newsletter subscription `_. 63 | 64 | Datasets manual download 65 | ~~~~~~~~~~~~~~~~~~~~~~~~ 66 | 67 | After you have obtained an API key `you can download datasets from the backtesting page `_. 68 | 69 | Downloading programmatically 70 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 71 | 72 | See :ref:`dataset download` for examples. 73 | 74 | 75 | API endpoints 76 | ------------- 77 | 78 | Datasets can be downloaded over authenticated HTTPS API endpoints. 79 | 80 | At the moment, all API endpoints are served by a private beta server https://tradingstrategy.ai/api. 81 | 82 | APIs are described by Python dataclasses. For more information about the dataset data structure, see the API documentation and the relevant source code. 83 | 84 | Parquet endpoints 85 | ~~~~~~~~~~~~~~~~~ 86 | 87 | These take HTTP GET parameter ``bucket``. See available values in :py:class:`tradingstrategy.timebucket.TimeBucket`. 88 | They return a Parquet file download. 89 | 90 | .. code-block:: none 91 | 92 | /pair-universe 93 | /candles-all 94 | /liquidity-all 95 | 96 | JSON endpoints 97 | ~~~~~~~~~~~~~~ 98 | 99 | These do not take parameters. They return a JSON file download. 100 | 101 | .. code-block:: none 102 | 103 | /exchanges 104 | -------------------------------------------------------------------------------- /source/overview/oracles.rst: -------------------------------------------------------------------------------- 1 | .. _oracle: 2 | 3 | Oracles 4 | ======= 5 | 6 | In the core of :ref:`Trading Strategy protocol ` is the concept of an oracle. 7 | 8 | - Oracles read blockchain and converts raw blockchain events to :doc:`market data feeds <./market-data-feeds>` 9 | - Oracles :ref:`execute ` trading strategies based on these market data feeds 10 | - Oracles will eventually form the :ref:`decentralised network ` 11 | - Oracles are similar to other oracles in other decentralised networks, like ones provided by Chainlink. 12 | In the case of Trading Strategy, oracles deal with trading signals and trading instructions, 13 | instead of price data. 14 | 15 | Operating oracles 16 | ----------------- 17 | 18 | You can 19 | 20 | - Use Trading Strategy public oracle network for public trading strategies, 21 | in this case you do not need to run your own oracle 22 | - Run your own private oracle if you want to trade with private algorithms 23 | 24 | Oracle software 25 | --------------- 26 | 27 | The oracle is written in Python and can be deployed as :term:`Docker` containers. 28 | 29 | Development status 30 | ------------------ 31 | 32 | The oracle development is still ongoing and in beta. 33 | The full oracle source code is not fully available yet. 34 | 35 | - See :ref:`tradingstrategy` market data client source code 36 | - See :ref:`tradeexecutor` strategy executor source code -------------------------------------------------------------------------------- /source/overview/supported-markets.rst: -------------------------------------------------------------------------------- 1 | Supported markets and venues 2 | ---------------------------- 3 | 4 | Trading Strategy supports 5 | 6 | - Decentralised exchanges like Uniswap, PancakeSwap, SushiSwap, Trader Joe and Curve 7 | 8 | - Decentralised lending protocols like Aave and Compound 9 | 10 | - Investor vaults and shareable strategies with :term:`Enzyme Finance ` 11 | 12 | `You can explore the available data `_ on Trading Strategy website. 13 | -------------------------------------------------------------------------------- /source/overview/tooling.rst: -------------------------------------------------------------------------------- 1 | Tooling 2 | ======= 3 | 4 | Trading Strategy tooling is centered around Python programming language and its quant finance libraries. 5 | Python, Jupyter Notebook and Pandas mathematical libraries are the most popular data research solutions for 6 | finance. 7 | 8 | See :ref:`getting started tutorial ` for more information. -------------------------------------------------------------------------------- /source/programming/code-examples/dataset-download.rst: -------------------------------------------------------------------------------- 1 | .. _dataset download: 2 | 3 | Dataset download 4 | ================ 5 | 6 | This is a generic example how to access Trading Strategy datasets by hand. 7 | 8 | If you are a Python user, you should use the `trading-strategy` package to access the data (see :ref:`tutorial`). 9 | In thes examples, we give Python pseudocode other programming languages can adapt. 10 | 11 | Downloading datasets programmatically 12 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 13 | 14 | All endpoints need your API key in the ``Authorisation`` header. 15 | 16 | Because files are large, you need to stream them, as they are unlikely to fit in the RAM. 17 | 18 | Example how to download: 19 | 20 | .. code-block:: python 21 | 22 | import os 23 | import requests 24 | 25 | # Read API key from the process environment 26 | # should be in format "secret-token:tradingstrategy-48... 27 | # where the secret-token is the part of the API key itself 28 | api_key = os.environ["TRADING_STRATEGY_API_KEY"] 29 | 30 | session = requests.Session() 31 | session.headers.update({'Authorization': api_key}) 32 | server = "https://tradingstrategy.ai/api" 33 | url = f"{server}/candles-all" 34 | params= {"bucket": "1d"} 35 | resp = session.get(url, allow_redirects=True, stream=True, params=params) 36 | resp.raise_for_status() 37 | size = 0 38 | with open('candles.parquet', 'wb') as handle: 39 | for block in resp.iter_content(64*1024): 40 | handle.write(block) 41 | size += len(block) 42 | 43 | print(f"Downloaded {size:,} bytes") 44 | 45 | Here is a `curl` example for getting 1d liquidity candles and save the file in the current folder: 46 | 47 | .. code-block:: shell 48 | 49 | export TRADING_STRATEGY_API_KEY="secret-token:tradingstrategy-..." 50 | curl -v -H "Authorization: $TRADING_STRATEGY_API_KEY" "https://tradingstrategy.ai/api/liquidity-all?bucket=1d" --output liquidity-1d.parquet 51 | 52 | Reading datasets 53 | ~~~~~~~~~~~~~~~~ 54 | 55 | Datasets are distributed as compressed :term:`Parquet` files, using Parquet version 2.0. 56 | 57 | You can read the files using PyArrow: 58 | 59 | .. code-block:: python 60 | 61 | import pyarrow as pa 62 | from pyarrow import parquet as pq 63 | 64 | table: pa.Table = pq.read_table("candles.parquet") 65 | 66 | Then, you can directly import the table into your database or convert the table to a Pandas DataFrame for further manipulation. 67 | -------------------------------------------------------------------------------- /source/programming/code-examples/index.rst: -------------------------------------------------------------------------------- 1 | .. _tutorial: 2 | 3 | Code examples 4 | ============= 5 | 6 | This section contains basic examples for Trading Strategy client 7 | 8 | - How to access market data from Trading Strategy oracle and APIs (Parquet 9 | datasets, real time API, and so on) 10 | 11 | - How to plot different charts using Jupyter Notebook tooling 12 | 13 | Preface 14 | ------- 15 | 16 | Before getting started see :ref:`Setting up development environment`. 17 | 18 | Examples 19 | -------- 20 | 21 | .. toctree:: 22 | :maxdepth: 1 23 | 24 | getting-started 25 | candle-chart-example 26 | interactive-charts 27 | technical-analysis 28 | pairs 29 | low-fee-pairs 30 | liquidity-analysis 31 | price-impact 32 | pool-liquidity 33 | dataset-download 34 | plotting-old 35 | lending-market-summary 36 | uniswap-v3-data 37 | xsgd-json-lines 38 | 39 | Next steps 40 | ---------- 41 | 42 | Examples in this section are not full-blown trading strategies. 43 | 44 | For strategy development and backtesting see :ref:`strategy examples`. -------------------------------------------------------------------------------- /source/programming/example-trading-strategies.rst: -------------------------------------------------------------------------------- 1 | .. meta :: 2 | :description: Full algorithmic trading strategy examples in Python 3 | :title: Trading strategy examples in Python 4 | 5 | Trading strategy examples 6 | ========================= 7 | 8 | Trading Strategy examples are in `Getting Started `__ github repository. 9 | 10 | - `Refer to the Example strategy backtests for the full example list `__ 11 | 12 | Old examples 13 | ------------ 14 | 15 | .. warning:: 16 | 17 | These examples won't run anymore. 18 | 19 | You can find some old code examples which have been deprecated. 20 | 21 | - :doc:`Old trading strategies <../old-strategies>` 22 | - :doc:`More trading strategies <../more-old-strategy-examples>` -------------------------------------------------------------------------------- /source/programming/index.rst: -------------------------------------------------------------------------------- 1 | .. meta :: 2 | :description: How to develop your own trading strategy in Python 3 | :title: Developing trading strategies 4 | 5 | .. _framework: 6 | 7 | Developing strategies 8 | ===================== 9 | 10 | This documentation covers how to develop and backtest :term:`algorithmic trading strategies ` 11 | for :ref:`Trading Strategy framework`. 12 | 13 | - If you want to get started quickly, hop to the `Getting started Github repository `__. 14 | 15 | - If you are new to algorithmic trading and want to just learn algorithmic trading, 16 | see :ref:`learning` section. 17 | 18 | - If you are an end-user and just want to deposit money into the ready automated trading strategies 19 | visit `Trading Strategy website `__ and its 20 | `Strategies section `__ 21 | 22 | 23 | Developer documentation: 24 | 25 | .. toctree:: 26 | :maxdepth: 1 27 | 28 | setting-up-development-environment/index 29 | example-trading-strategies 30 | code-examples/index 31 | api/index 32 | market-data/index 33 | troubleshooting 34 | development 35 | 36 | -------------------------------------------------------------------------------- /source/programming/market-data/candle-format.rst: -------------------------------------------------------------------------------- 1 | .. _ohlcv: 2 | 3 | OHLCV Candle format 4 | =================== 5 | 6 | Trading Strategy has a specific OHLCV (open-high-low-close) :term:`candle` format 7 | that is more tailored for decentralised markets. Trading Strategy uses (first trade, last trade) 8 | style candle pricing over traditional cryptocurrency open/close price where open is the last close. 9 | 10 | - The opening price `open` is **the price of the first trade** during the candle period. 11 | 12 | - `high` / `low` / `close` fields are the same as for normal candles. 13 | 14 | - OHLV data **sparse**: if there are no trades, no zero volume candle is generated. 15 | If your strategy needs to have zero volume candles, you can :term:`forward fill` 16 | the data when you are constructing the trading universe. 17 | 18 | This is because we believe this formats fit better for DeFi market data feeds 19 | 20 | - There is no information lost, it is only presented differently. 21 | More information is retained in this format. 22 | 23 | - Candles are snapped to underlying blockchain block ranges: 24 | trades can only happen within a block and are physically represented by 25 | (block number, log index) tuples. 26 | 27 | - On AMM markets, the price can only move if there is a trade event. 28 | 29 | - There are no gaps between close and open because markets are 24h. 30 | Furthermore there are no opening and closing auctions as one might have 31 | at stock markets. 32 | 33 | .. forward filling data: 34 | 35 | Forward filling data 36 | -------------------- 37 | 38 | Transforming Trading Strategy candle format to the traditional open/close definitions can be done with 39 | following: 40 | 41 | - For strategies that read a candle open price, 42 | just choose to use previous candle close price instead. 43 | 44 | - For strategies, be mindful that there might not be a candle, 45 | because there are no trades. Many of the DeFi markets are low volume, 46 | and might not see any trades for minutes and sometimes hours. 47 | Thus the timestamp of the last candle might not be necessarily 48 | the previous tick. 49 | 50 | - Replace the open price 51 | with the close price of the previous candle. 52 | 53 | - For any missing sparse timestamps, generate a candle where open/high/low 54 | close are set the the volume to zero using :term:`forward fill`. 55 | 56 | Some methods for forward fill your data: 57 | 58 | - :py:meth:`tradeexecutor.strategy.trading_strategy_universe.TradingStrategyUniverse.create_from_dataset` 59 | takes `forward_fill` argument (`False` by default). You can use this in your `create_trading_universe` 60 | function to forward fill loaded data. 61 | 62 | - For low-level forward filling see :py:func:`tradingstrategy.utils.groupeduniverse.resample_candles` 63 | and :py:func:`tradingstrategy.utils.groupeduniverse.resample_series`. 64 | 65 | Distinction between buys and sells 66 | ---------------------------------- 67 | 68 | We include logic to determine if a trade was "buy" or "sell" 69 | 70 | - On AMM markets there are no true sides: everything is a swap. 71 | Sell is a swap with reverse token order compared to buy. 72 | 73 | - We consider anything to be buy if the amount of quote token 74 | decreases after the trade (your USD goes down, ETH balance increases). 75 | 76 | - See additional rules regarding the :ref:`token order`. 77 | 78 | Large differences between close and open 79 | ---------------------------------------- 80 | 81 | Sometimes for exotic and illiquid pairs there might be a great different 82 | between the last close and open price. Some potential explanations incluse 83 | 84 | - Mint / burn mechanisms of tokens 85 | 86 | - Backdoored / scam tokens 87 | 88 | Extra price feed columns 89 | ------------------------ 90 | 91 | The following extra fields may be avaiable depending on the payload 92 | 93 | - `start_block` 94 | 95 | - `end_block` 96 | 97 | - `buys` 98 | 99 | - `sells` 100 | 101 | - Volume might be split to separate `buy_volume` and `sell_volume` columns 102 | 103 | For the details of the candle fields see :py:class:`tradingstrategy.candle.Candle`. -------------------------------------------------------------------------------- /source/programming/market-data/client.rst: -------------------------------------------------------------------------------- 1 | .. _client: 2 | 3 | Market data client 4 | ================== 5 | 6 | Market data client is a Python library to aid 7 | fetching and processing decentralised market data easily. 8 | 9 | - The client is provided by :py:mod:`tradingstrategy` Python package 10 | 11 | - The client connects to a Trading Strategy oracle using HTTP and WebSocket protocols 12 | 13 | - For the client usage, see :py:class:`tradingstrategy.client.Client` 14 | 15 | 16 | -------------------------------------------------------------------------------- /source/programming/market-data/good-trading-pairs.rst: -------------------------------------------------------------------------------- 1 | Good trading pairs to start with 2 | ================================ 3 | 4 | In this page, we discuss about some "easy" pairs for technical analysis and automatic trading. 5 | 6 | Challenges of DeFi markets and trading 7 | -------------------------------------- 8 | 9 | Decentralised finance is challenging as the market is immature ane volatile 10 | 11 | - There is no historical data, as most trading pairs are very new with less 12 | than two years of history. 13 | 14 | - Trading data is spotty; DeFi markets have been more illiquid than :term:`CEX` for a long time, 15 | although this is now changing. There might minutes or somestimes even hours without trades. 16 | (See :ref:`OHLCV` page why Trading Strategy candle data is sparse for this reason.) 17 | 18 | - Many DeFi tokens suffer for starups issues. 80% of startups die young. 19 | 20 | - :term:`MEV` and other bots cause large wicks in candles, because they can do arbitrary 21 | size trades without fear of loss. OHLC candle high and low may be very arbitrary values 22 | that do not reflect the overall market price honestly. 23 | 24 | - Pairs trade do not trade against a stablecoin, but a volatile cryptocurrency :term:`quote token`. 25 | 26 | - DeFi markets contain :term:`rug pulls `, and especially :term:`honey pots ` 27 | designed to scam :term:`trading algorithms ` with fake volume 28 | and manipulated tokens. 29 | 30 | Good DeFi trading pairs 31 | ----------------------- 32 | 33 | Good and easy DeFi trading pairs are once with long history, robust organisation backing up the 34 | token, good price data and deep liquidity. 35 | 36 | Here is a short list of some hand picked trading pairs with some history to start analyse. 37 | These pairs where chosen for the good data availability. Older :term:`DEX` pairs usually have 38 | higher fees (0.30%) and nowadays the same pair may appear with a lower fee tier on the same or a 39 | a different exchange. 40 | 41 | Polygon 42 | ~~~~~~~ 43 | 44 | - `MATIC-USDC on QuickSwap `__ 45 | 46 | - `Klima-USDC on QuickSwap `__ 47 | (note: Klima is a :term:`rebase token` ) 48 | 49 | - `Voxel-USDC on QuickSwap `__ 50 | 51 | - `SAND-MATIC on QuickSwap `__ 52 | 53 | - `GHST-USDC on QuickSwap `__ 54 | 55 | - `CRV-USDC on Quickswap `__ 56 | 57 | - `DFYN-USDC on Dfyn exchange `__ 58 | 59 | - `AAVE-ETH on Quickswap `__ 60 | 61 | - `CROWD-USDT on QuickSwap `__ 62 | 63 | - `WBTC-USDC on Quickswap `__ 64 | 65 | BNB Chain 66 | ~~~~~~~~~ 67 | 68 | - `BNB-BUSD on BNB Chain `__ 69 | 70 | - `Cake-BUSD on BNB Chain `__ 71 | 72 | - `BTCB-BUSD (wrapped Bitcoin) on BNB Chain `__ 73 | 74 | Ethereum mainnet 75 | ~~~~~~~~~~~~~~~~ 76 | 77 | (Ethereum mainnet has prohibitive transaction fees) 78 | 79 | - `ETH-USDC on Uniswap v2 `__ 80 | 81 | Avalanche 82 | ~~~~~~~~~ 83 | 84 | - `WAVAX-USDC on Trader Joe `__ 85 | 86 | - `SOL-USDC on Trader Joe `__ 87 | 88 | - `JOE-USDC on Trader Joe `__ 89 | 90 | Need more trading pairs? 91 | ------------------------ 92 | 93 | `You can use Advanced search to quickly explore trading pairs `__. 94 | 95 | -------------------------------------------------------------------------------- /source/programming/market-data/index.rst: -------------------------------------------------------------------------------- 1 | Market data format details 2 | ========================== 3 | 4 | This documentation covers market data features your can access through Trading Strategy. 5 | 6 | .. toctree:: 7 | :maxdepth: 1 8 | 9 | client 10 | candle-format 11 | tracking 12 | reference-price 13 | trading-pairs 14 | internal-id 15 | token-tax 16 | good-trading-pairs 17 | wrapped-tokens 18 | profitability 19 | -------------------------------------------------------------------------------- /source/programming/market-data/internal-id.rst: -------------------------------------------------------------------------------- 1 | .. _internal-id: 2 | 3 | Internal ids 4 | ============ 5 | 6 | Trading Strategy has several datasets that refer to each other. For example pair dataset refers to exchange dataset via ``exchange_id``. 7 | 8 | These foreign keys, or primary keys, are not stable. They can across different datasets, when data is being healed or reimported. 9 | Always access the data using symbolic notation, called *slugs* or token symbols. 10 | 11 | Duplicate token symbols 12 | ----------------------- 13 | 14 | Exchanges may have duplicate trading pairs with the same token symbol. The duplicates are usually scam tokens. 15 | Trading Strategy access methods try to automatically pick the real trading pair among multiple entries by 16 | the pair's trading volume. 17 | 18 | .. warning:: 19 | There is no curated list available, so be careful when accessing tokens and trading pairs by their symbol. 20 | 21 | More information 22 | ---------------- 23 | 24 | - See :py:class:`tradingstrategy.types.PrimaryKey` type alias. 25 | 26 | - See :py:meth:`tradingstrategy.exchange.ExchangeUniverse.get_by_chain_and_slug` method 27 | 28 | - See :py:meth:`tradingstrategy.pair.PairUniverse.get_pair_by_ticker_by_exchange` method -------------------------------------------------------------------------------- /source/programming/market-data/profitability.rst: -------------------------------------------------------------------------------- 1 | .. _profitability: 2 | 3 | Profitability calculations 4 | ========================== 5 | 6 | In this chapter, we discuss differerent ways to calcualte profitability of the trading strategy 7 | and what are the trade offs. 8 | 9 | Challenges come from the effects of deposits and redemptions: 10 | a live trading strategy does not have a fixed capital over its life time 11 | like a backtest. 12 | 13 | For open strategies, there can deposits and redemptions any time. 14 | This will affect the equity, cash and thus performance per dollar. 15 | To make matters more complex, on :term:`vault` based strategies 16 | the underlying positions can be reduced by a redemption event. 17 | 18 | To understand if a strategy is performing well we can look 19 | 20 | - Profit of trades 21 | 22 | - Profit of trades, considering position sizing 23 | 24 | - Profit of assets under management 25 | 26 | - Profit per share 27 | 28 | - Profit for individual investors 29 | 30 | Profitability as realised positions profit 31 | ------------------------------------------ 32 | 33 | This is the default measurement for profitability. 34 | 35 | For most of use cases, we want to measure the trading performance of the strategy, 36 | not the return on capital. The realised positions profit is simply % profitability 37 | of closed positions during the time period. 38 | 39 | The realised position profit can be 40 | 41 | - Absolute performance % of the trades 42 | 43 | - Relative % to the size of the total portfolio equity, 44 | as :term:`position sizing` is used as the risk control method. 45 | 46 | .. warning:: 47 | 48 | Currently :term:`vault` based strategies can do in-kind redemption 49 | which directly affects the underlying open trading positions. 50 | Currently this is not yet accounted on these positions. 51 | 52 | .. _compounding realised positions profit: 53 | 54 | Compounding realised positions profit 55 | ------------------------------------- 56 | 57 | All trading strategies assume that they are :term:`compounding `: 58 | you will reinvest the profits to new trading positions. 59 | Over the time, profits will compound. 60 | 61 | The compounding realised positions profit tells the trading strategy 62 | profitability assuming there are not depositons and redemptions 63 | during the trading period, and all strategy profits will be 64 | reinvested to trading. 65 | 66 | This gives us a good metric to benchmark the performance 67 | of differents strategies independent of funding flow. 68 | 69 | Trading Stratey calculates compounding realised profitability with 70 | :term:`position sizing considered`. 71 | The formula for Trading Strategy default profitability calculation over time is: 72 | 73 | .. code-block:: text 74 | 75 | strategy_profitability = 76 | (1 + position_1_realised_profit_percent * position_1_relative_size) * 77 | (1 + position_2_realised_profit_percent * position_2_relative_size) * 78 | (1 + position_3_realised_profit_percent * position_3_relative_size) 79 | ... 80 | - 1 81 | 82 | Profit per share 83 | ---------------- 84 | 85 | :term:`Vault` based strategies have underlying share token. 86 | We can calculate profit per share that is comparable 87 | to a profit per share calculations in any corporation or a fund. 88 | 89 | .. warning:: 90 | 91 | Some vault implementations do profit sharing in the form minting new shares 92 | to the asset manager and diluting the depositors. This will affect profit per 93 | share calculations and comparisons. 94 | 95 | Total equity 96 | ------------ 97 | 98 | The :term:`equity curve` shows the both trading profits and new deposits and redemptions. 99 | It cannot be used to determine the :term:`trading strategy` profitability if 100 | deposits and redemptions can happen any time. 101 | 102 | Funding flow 103 | ------------ 104 | 105 | Funding flow shows US dollar valued deposits and redemptions over time. 106 | It's main use case is to calculate funding flow corrected returns. 107 | 108 | Funding flow corrected returns 109 | ------------------------------ 110 | 111 | The funding flow corrected returns is the daily/monthly returns 112 | minus any deposits and redemptions. 113 | 114 | Any large funding flow event will skew this calculation. 115 | Although funding flow corrected returns may be used as a profitability 116 | metric, it is still subject to skew by funding events. 117 | 118 | Profit for individual investors 119 | ------------------------------- 120 | 121 | For any individual investors, we can calculate how much profit 122 | this investor has done for his/her position over time. 123 | 124 | .. note:: 125 | 126 | Currently this information is not available through the trade execution user interface. 127 | 128 | Technical information 129 | --------------------- 130 | 131 | See :py:mod:`tradeexecutor.visual.equity_curve` for different profit calculation 132 | and equity curve formulas and examples. 133 | 134 | -------------------------------------------------------------------------------- /source/programming/market-data/reference-price.rst: -------------------------------------------------------------------------------- 1 | .. _price conversion: 2 | 3 | US dollar price conversion 4 | ========================== 5 | 6 | Introduction 7 | ------------ 8 | 9 | Each trading pair consists of two tokens 10 | 11 | * Base token e.g. AAVE: (the token you are going to buy) 12 | 13 | * Quote token e.g. ETH (the token you are going to use as the payment) 14 | 15 | A lot of decentralised exchange trades happens against these non-fiat quote tokens like ETH and BNB. 16 | 17 | Trading Strategy converts all trading pair quotes to US dollars. 18 | This mechanism is called *reference pricing*. 19 | 20 | * US dollar prices are more human readable, making analysing the market 21 | and comparing the prices and volumes easier 22 | 23 | * As the service is geared towards algorithmic trading, only the direction of the price matters, 24 | not its precise value 25 | 26 | The downside of the reference pricing is that you need to have a source of truth for 27 | what's the underlying price of the quote token in US dollars. This includes additional 28 | complexity to the internal processing for the benefit of a better user experience. 29 | It also adds another source of risk, as pricing information may not be correctly 30 | determined in the high volatility market movement. 31 | 32 | Not having a good US dollar conversion path also affects to <> 33 | 34 | Internal oracle process 35 | ----------------------- 36 | 37 | Here is the description of the current reference price process, known as the reference price ``v0``. 38 | 39 | .. danger:: 40 | This process is not final and not very safe in its current form and only applies to the beta version of Trading Strategy. 41 | 42 | Currently the US dollar conversion works as follows: 43 | 44 | * All reference price sources must be on-chain, to keep the data pure (exception: BTC/USD comes from Bitstamp). 45 | 46 | * All reference prices must be specific to the chain where the asset trades. E.g. 47 | Binance Smart Chain trading pairs can only have quote tokens of which reference price comes from a pool 48 | on Binance Smart Chain itself. 49 | 50 | * Reference price is generated as a separate step before OHLCV candle data, as OHLCV data generation requires to have 51 | good US dollar exchange rates. 52 | 53 | * Reference price is generated from known quote tokens - US dollar pools. 54 | 55 | * Price is formed from 1 minute swaps and liquidity events of the pool. 56 | If no trades have been done, the latest available on-chain trade event is 57 | used as the reference price. 58 | 59 | Currently reference price is supported for the following tokens: 60 | 61 | * ETH on Ethereum mainnet (ETH/USDC Uniswap v2 pool on Ethereum mainnet) 62 | 63 | * BNB 64 | 65 | * MATIC 66 | 67 | * Cake 68 | 69 | * QUICK 70 | 71 | 72 | .. _token order: 73 | 74 | Determining quote token 75 | ----------------------- 76 | 77 | Uniswap v2 compatible exchanges do not care which token is a base token and which token is a quote token - 78 | it only cares about token inputs and token outputs. Sell is just a buy with a reverse token order. 79 | 80 | For making the market data analysis easier, all trading pairs on Trading Strategy are converted to 81 | the form where we have an easier to understand ``base - quote`` token pair. 82 | 83 | The quote token is always determined to be a well-known token. Currently we use the following 84 | priority to determine which of the trading pairs tokens is a quote token. 85 | 86 | * An USD stablecoin (**beta note**: any stablecoin is assumed to be 1:1 with US dollar) 87 | 88 | * BTC 89 | 90 | * ETH 91 | 92 | * BNB 93 | 94 | * MATIC 95 | 96 | * Cake 97 | 98 | * Quick 99 | 100 | No three step quote tokens are supported. Each quote token must have a direct on-chain truth 101 | for its dollar price. E.g. we cannot support pair FOOBAR:AAVE where AAVE would be converted 102 | AAVE -> ETH -> USD. 103 | 104 | Risk mitigations 105 | ---------------- 106 | 107 | Every price quote and price chart from Trading Strategy comes with the information of US dollar 108 | exchange rate used for the reference price conversion for the quote token. You can always undo 109 | the reference price conversion by multiplying the quoted dollar price with the exchange rate 110 | and you get the original quote token amount back. 111 | 112 | Notes 113 | ----- 114 | 115 | About price oracle security 116 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 117 | 118 | `Read this post about spot price security when used in an oracle `_. -------------------------------------------------------------------------------- /source/programming/market-data/tracking.rst: -------------------------------------------------------------------------------- 1 | .. _tracking: 2 | 3 | Tracked trading pairs and tokens 4 | ================================ 5 | 6 | Currently, there exist more than a million tokens on Trading Strategy oracle supported blockchains. 7 | Most of these tokens do not have any real value; they are just tests or projects that never took off. 8 | As it would be impractical to generate complex market data analysis for such a large number of tokens, 9 | a filtering criteria is applied to tokens and trading pairs being tracked. 10 | 11 | Trading pair filtering 12 | ---------------------- 13 | 14 | The following criteria is applied to trading pairs. 15 | 16 | We have the following kinds of data collection for a trading pair. 17 | 18 | * **Untracked pairs**: The data exist on a blockchain, but the oracle indexer does not 19 | read it at all. For example, trading pairs on incompatible exchanges. 20 | 21 | * **Tracked pairs**: The oracle indexer is reading and indexing the raw data. 22 | A summary of the trading pair info is generated and the trading pair 23 | appears e.g. in the trading pair counts. However, no market data is yet 24 | produced. 25 | 26 | * **Active pairs**: The oracle indexer is generating the market data 27 | feed for this pair. The market data feed includes data like OHLCV candles, 28 | momentum, market cap and so on. 29 | 30 | Below is the criteria for a trading pair to be considered active: 31 | 32 | .. raw:: html 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 48 | 51 | 52 | 53 | 54 | 55 | 58 | 62 | 63 | 64 | 65 | 66 | 69 | 73 | 74 | 75 | 76 | 77 | 80 | 87 | 88 | 89 | 90 | 91 | 92 | 95 | 101 | 102 | 103 | 104 |
CriterionFiltering
#1 46 | Supported blockchain 47 | 49 | The trading pair must trade on a decentralised exchange on one of the supported blockchains. 50 |
#2 56 | Supported exchange 57 | 59 | The decentralised exchange must be on one of the supported exchange types. 60 | (Currently Uniswap v2 ABI compatible.) 61 |
#3 67 | Metadata validity 68 | 70 | The trading pair tokens must have valid metadata. This includes 71 | token names, symbols and decimals. 72 |
#4 78 | Supported quote token 79 | 81 | Each trading pair consists of base token and quote token. In decentralised exchange, the token order does not matter. 82 | However, for the sake of better data research, trading strategy converts all trading pairs to the format where 83 | we have a well known quote token and the quote token price can be directly translated to a US dollar price. 84 | Thus, the quote token will be always be one of the likes of USDC, USDT, ETH, BNB or similar high liquidity 85 | pair with direct dollar reference price available. 86 |
#5 93 | Minimum activity threshold 94 | 96 | The pair must meet the minimum trading activity threshold. 97 | This is different for each blockchain (Ethereum, Binance Smart Chain). 98 | The threshold may include numbers like the minimum number of swaps, 99 | and the minimum liquidity. 100 |
105 | 106 | 107 | Token filtering 108 | --------------- 109 | 110 | Like trading pairs, tokens themselves have some eligibility criteria to be included in the datasets. 111 | 112 | * **Untracked tokens**: The data exist on a blockchain, but the oracle indexer does not 113 | read it at all. For example, tokens that are not being traded on any compatible exchange. 114 | 115 | * **Tracked tokens**: Tokens appear in any of the tracked trading pairs. 116 | 117 | * **Active tokens**: Tokens appear in any of active trading pairs. These tokens have a token page created, showing the token market cap, available trading pairs and volume. 118 | 119 | Volume calculations 120 | ------------------- 121 | 122 | Volume can be only calculated for trading pairs with a supported quote token. 123 | If a trading pair has an unsupported quote token, as explained above, any trade on this pair is not included 124 | in the exchange or blockchain trading volume. 125 | 126 | This is because there must exist a stable, liquid path to convert any trading volume to US dollar. -------------------------------------------------------------------------------- /source/programming/market-data/wrapped-tokens.rst: -------------------------------------------------------------------------------- 1 | .. _wrapped token: 2 | 3 | Wrapped tokens 4 | ============== 5 | 6 | Due to legacy design issues with :term:`EVM-compatible` blockchains, 7 | any :term:`native token` must be "wrapped" in order it to be used with 8 | :term:`decentralised exchanges `. 9 | 10 | To distinguish wrapped tokens from their native token counterparts, 11 | a letter `W` is added at the front of the token. E.g. 12 | 13 | .. code-block:: text 14 | 15 | BNB -> WBNB 16 | 17 | Even though tokens always need to be wrapped to trading, 18 | sometimes they are still referred as "BNB" in the user interface, 19 | when though on the smart contract level you are usinb WBNB token. 20 | 21 | Wrapped token list 22 | ------------------ 23 | 24 | Here are some common wrapped tokens. 25 | 26 | WETH 27 | ~~~~ 28 | 29 | Ethereum mainnet: from ETH to WETH. 30 | 31 | WMATIC 32 | ~~~~~~ 33 | 34 | Polygon: from MATIC to WMATIC. 35 | 36 | WAVAX 37 | ~~~~~ 38 | 39 | Avanlanche C-chain: from AVAX to WAVAX. 40 | 41 | WBNB 42 | ~~~~ 43 | 44 | Binance smart chain: from BNB to WBNB. 45 | 46 | Bridged tokens 47 | -------------- 48 | 49 | Besides wrapped tokens, there are bridged tokens. 50 | Bridges tokens have their primary implementation living on one blockchain, 51 | but then throuhg a locking mechanism make token liquidity available on 52 | other chains. 53 | 54 | Bridges tokens do not have 'W' prefix. 55 | 56 | An example of bridged token is `ETH on Binance Smart Chain `_. 57 | This token is bridged through Binance custody. Because the native 58 | token of Binance Smart Chain is BNB, not ETH, ETH on Binance Smart Chain 59 | does not need to be wrapped. 60 | 61 | -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/binder-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/binder-example.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/binder/binder-api-key.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/binder/binder-api-key.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/binder/binder-development.rst: -------------------------------------------------------------------------------- 1 | Binder development 2 | ================== 3 | 4 | .. warning:: 5 | 6 | This is no longer maintained. You should use `Github Codespaces `__ instead. 7 | 8 | 9 | In this document, we show how to develop trading strategies using `Binder `_ cloud based 10 | :term:`Jupyter notebook` environment. 11 | 12 | Preface 13 | ------- 14 | 15 | Binder is free and popular software-as-a-service cloud environment 16 | for running Jupyter Notebooks. Binder is an open source project 17 | and supported by Thanks to Google Cloud, OVH, GESIS Notebooks and the Turing Institute. 18 | 19 | Limitations 20 | ----------- 21 | 22 | .. note :: 23 | 24 | Due to limitations on Binder instances in RAM, 25 | most of the examples won't run there or are 26 | prohibitive slow. 27 | 28 | .. note :: 29 | 30 | Binder cloud notebooks do not offer easy Save functionality. 31 | It is recommended that you use other methods for professional development. 32 | 33 | Prerequisites 34 | ~~~~~~~~~~~~~ 35 | 36 | Prerequisites for developing trading strategies with Binder are 37 | 38 | - Python programming basics 39 | 40 | - :doc:`You have completed quick start tutorial <./code-examples/getting-started>` 41 | 42 | - :doc:`You have read the backtest template notebook with its instructions <./strategy-examples/strategy-backtest-template>` 43 | 44 | Opening the template 45 | -------------------- 46 | 47 | Go to :doc:`strategy backtest template in the documentation <./strategy-examples/strategy-backtest-template>` 48 | 49 | Press *Launch Binder* at the top of the page. 50 | 51 | This will create a new Binder instance for you for editing and running the notebook. 52 | 53 | The launch of a new Binder instance may take up to couple of minutes. 54 | 55 | Run 56 | --- 57 | 58 | Press *Restart kernel and run all cells* to execute the template notebook. 59 | 60 | .. image:: binder-run.png 61 | 62 | You will be prompted to enter Trading Strategy API key: 63 | 64 | .. image:: binder-api-key.png 65 | 66 | After this you will see the notebook downloading the OHLCV data to run backtest. 67 | 68 | .. image:: binder-download.png 69 | 70 | Saving changes 71 | -------------- 72 | 73 | Binder instances are created on-demand and will erase themselves after a timeout. 74 | 75 | To save your changes, you need to download Jupyter Notebook .ipynb file to your local computer. 76 | 77 | .. note :: 78 | 79 | Binder is not ideal for long term development because difficult edit save workflow. 80 | Consider other options for professional development. 81 | 82 | Technical information 83 | --------------------- 84 | 85 | `Binder environment is configured in this Github repository `_. 86 | 87 | 88 | -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/binder/binder-download.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/binder/binder-download.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/binder/binder-run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/binder/binder-run.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/codespaces/index.rst: -------------------------------------------------------------------------------- 1 | .. _codespaces: 2 | 3 | Github Codespaces 4 | ================= 5 | 6 | Github offers its users Github Codespaces cloud virtual machines for development. 7 | You can create your Github repository for strategt backtesting notebooks 8 | and edit them you through web browsers. 9 | 10 | Pros 11 | 12 | - This is the easiest option to get started 13 | - Only Github user account required 14 | - Github Codespaces is equivalent of Visual Studio Code in cloud 15 | 16 | Cons 17 | 18 | - Github Codespaces is somewhat slows 19 | - Web browser is not as effective tool as a local development environment 20 | 21 | `See Getting started repository `__. 22 | 23 | Details 24 | ------- 25 | 26 | Github Codespaces offers a virtual machine with 8 GB RAM and 2 CPUs. -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/backtesting-period.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/backtesting-period.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/cloning-examples.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/cloning-examples.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/command-line-python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/command-line-python.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/dev-container-building.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/dev-container-building.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/git-clone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/git-clone.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/new-termianl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/new-termianl.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/open-folder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/open-folder.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/open-in-dev-container.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/open-in-dev-container.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/project-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/project-tree.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/run-all-results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/run-all-results.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/run-all.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/run-all.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/dev-container/vscode-splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/dev-container/vscode-splash.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/add-new-interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/add-new-interpreter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/docker-image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/docker-image.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/jupyter-configuration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/jupyter-configuration.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/jupyter-selector.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/jupyter-selector.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/pycharm-result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/pycharm-result.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/remote-interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/remote-interpreter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/docker-development-image/run-all.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/docker-development-image/run-all.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/google-colab.rst: -------------------------------------------------------------------------------- 1 | Google Colab 2 | ~~~~~~~~~~~~ 3 | 4 | .. warning:: 5 | 6 | This is no longer maintained. You should use `Github Codespaces `__ instead. 7 | -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/index.rst: -------------------------------------------------------------------------------- 1 | .. _running-code-examples: 2 | 3 | .. _Setting up development environment: 4 | 5 | Setting up development environment 6 | ================================== 7 | 8 | Preface 9 | ------- 10 | 11 | This documentation section covers how to run Trading Strategy code examples and notebooks: 12 | 13 | * How to set up a Python-based Trading Strategy development environment on your local computer 14 | or a cloud server 15 | 16 | .. note :: 17 | 18 | If you want to get started fast, you can directly jump to `Getting started Github repository and Codespaces `__. 19 | 20 | Prerequisites 21 | ------------- 22 | 23 | Code examples are available able :term:`Jupyter notebooks ` in this documentation. 24 | 25 | You to be able work with the examples you need to have 26 | 27 | * Python programming basics 28 | 29 | * Data sciense basics: Jupyter notebook and Pandas 30 | 31 | * :ref:`Price action and technical indicator basics ` 32 | 33 | Recommended set up 34 | ------------------ 35 | 36 | - We recommend trying out with :ref:`Github Codespaces ` cloud-based tutorial first 37 | - The next easiest option is with Visual Studio Code :ref:`Dev Container` 38 | - If you are experienced Python developer you can use any Python editor you wish, 39 | and install the source code from Github checkout 40 | 41 | Development environment options 42 | ------------------------------- 43 | 44 | We offer different strategy development environments for different level of developers: 45 | 46 | .. toctree:: 47 | :maxdepth: 1 48 | 49 | codespaces/index 50 | dev-container/visual-studio-code-docker-dev-container-for-jupyter-notebooks 51 | docker-development-image/docker-development-image 52 | pycharm/index 53 | local-python 54 | google-colab 55 | binder/binder-development 56 | 57 | Next steps 58 | ---------- 59 | 60 | After setting up your development environment, 61 | go to :ref:`tutorials ` section of the documentation. 62 | 63 | You find tutorials for: 64 | 65 | * How to develop and backtest your own automated trading strategies 66 | 67 | * How to analyse DeFi market data 68 | 69 | * How to use Trading Strategy API 70 | 71 | .. _get an API key: 72 | 73 | Getting an API key 74 | ------------------ 75 | 76 | To get a Trading Strategy API key needed to access some of the datasets, 77 | `please visit here `__. 78 | 79 | - Any notebook will prompt you to get and enter the API key if you do not have 80 | one yet 81 | 82 | - Some binaries like `trade-executor` docker will read the API key from 83 | `TRADING_STRATEGY_API_KEY` environment variable. 84 | 85 | - API key is free 86 | 87 | Example: 88 | 89 | .. code-block:: shell 90 | 91 | export TRADING_STRATEGY_API_KEY="secret-token:tradingstrategy-d534e28..." 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/local-python.rst: -------------------------------------------------------------------------------- 1 | .. _local python: 2 | 3 | Local Python installation 4 | ========================= 5 | 6 | This is the recommended method for advanced strategy development. 7 | You can checkout the example code and run it on your local computer. 8 | 9 | This method uses Git checkout and :term:`Poetry` package manager for Python (you can install poetry). 10 | 11 | This is a good option if you are using any of popular IDEs such as 12 | 13 | * PyCharm 14 | 15 | * Visual Studio Code with `Jupyter Visual Studio Code extension `_. Choosing a black-on-white theme recommended, because the default charts assume white background. 16 | 17 | We give instructions to Visual Studio Code, but PyCharm installation is very similar. 18 | 19 | Before starting 20 | --------------- 21 | 22 | .. note:: 23 | 24 | The installation method described here is for advanced Python developers. 25 | If you are new to Python we recommend using :ref:`Visual Studio Dev Container ` 26 | installation method instead. If you think you can set up your own local environment from the scratch, you need to be 27 | able to resolve Python version and package compatibility issues, or other issues which 28 | may occur. 29 | 30 | .. note:: 31 | 32 | Before getting started, double check that you are using a compatible 33 | Python version. Because of complex data analysis libraries 34 | used, the Python version compatibility is picky. 35 | 36 | `The current supported Python versions are listed in pyproject.toml `__. 37 | 38 | Installation steps 39 | ------------------ 40 | 41 | Git clone the `Trading Executor repository from Github `_. 42 | 43 | Install the client and its dependencies using `Poetry `_: 44 | 45 | .. code-block:: shell 46 | 47 | # Assumes you have SSH key set up with your Github account 48 | git clone git@github.com:tradingstrategy-ai/trade-executor.git 49 | cd trade-executor 50 | git submodule update --init --recursive 51 | 52 | # Extra dependencies 53 | # - execution: infrastructure to run live strategies 54 | # - web-server: support webhook server of live strategy executors 55 | # - qstrader: still needed to run legacy unit tests 56 | poetry install --all-extras 57 | 58 | # Optionally specify Python version 59 | poetry env use python3.11 60 | 61 | # Activate the virtual environment 62 | poetry env activate 63 | 64 | # Run commands in the Poetry environment, e.g.: 65 | poetry run ipython 66 | 67 | Configure Visual Studio Code 68 | --------------------------- 69 | 70 | Install `Jupyter Visual Studio Code extension `_. 71 | Choosing a black-on-white theme is recommended, because the default charts assume white background. 72 | 73 | To configure VS Code to use the Poetry Python interpreter: 74 | 75 | .. code-block:: shell 76 | 77 | # Find the interpreter path 78 | poetry run which python 79 | 80 | This gives you the full path of `python` command, for example: 81 | 82 | .. code-block:: text 83 | 84 | /Users/moo/Library/Caches/pypoetry/virtualenvs/tradingstrategy-lMEetNwg-py3.8/bin/python 85 | 86 | Use Visual Studio Code *Python: Select Interpreter* command from *Command palette* to configure this interpreter by choosing *Enter interpreter path* option. 87 | 88 | Now you can run `Getting started `_ and other example notebooks. Open any `ipynb` file in Visual Studio Code and choose *Run All* on the open notebook. 89 | 90 | .. image:: ./vscode.png 91 | :alt: Visual Studio Code example how to run a Jupyter Notebook 92 | 93 | Local Jupyter installation 94 | -------------------------- 95 | 96 | You run notebooks by installing a local `Jupyter notebook installation `_. 97 | This will create a local Jupyter server and open Jupyter notebooks in your web browser. 98 | 99 | Start Jupyter server at the root folder: 100 | 101 | .. code-block:: shell 102 | 103 | poetry run ipython notebook 104 | 105 | Navigate to a file you want to edit in your web browser. 106 | -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/add-existing-interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/add-existing-interpreter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/api-key.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/api-key.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/configure-python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/configure-python.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/interpreter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/managed-server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/managed-server.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/open.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/open.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/poetry-interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/poetry-interpreter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/poetry.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/poetry.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/project-interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/project-interpreter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/restart-jupyter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/restart-jupyter.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/result.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/run.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/running.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/running.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/search-python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/search-python.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/trust.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/trust.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/trusted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/trusted.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/pycharm/which.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/pycharm/which.png -------------------------------------------------------------------------------- /source/programming/setting-up-development-environment/vscode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tradingstrategy-ai/docs/4f9bb262d41112416a9f9bbe9e9f119a89a52052/source/programming/setting-up-development-environment/vscode.png -------------------------------------------------------------------------------- /source/programming/troubleshooting.rst: -------------------------------------------------------------------------------- 1 | Troubleshooting 2 | =============== 3 | 4 | Preface 5 | ------- 6 | 7 | Some common issues you might encounter and how to tackle them. 8 | 9 | Resetting the API key 10 | --------------------- 11 | 12 | You can reset the API key by deleting the config file: 13 | 14 | .. code-block:: shell 15 | 16 | rm ~/.tradingstrategy/settings.json 17 | 18 | Resetting the download cache 19 | ---------------------------- 20 | 21 | Downloaded files might get corrupted e.g. due to a partial download. 22 | 23 | You can see a message like: 24 | 25 | .. code-block:: none 26 | 27 | OSError: Could not open parquet input source '': Invalid: Parquet magic bytes not found in footer. Either the file is corrupted or this is not a parquet file. 28 | 29 | To fix this issue, you can remove all files in the download cache. 30 | 31 | .. code-block:: shell 32 | 33 | rm -rf ~/.cache/tradingstrategy/ 34 | 35 | Apple macOS on M1 ARM CPUs 36 | -------------------------- 37 | 38 | Some dependencies, namely `numpy` are notorious difficult to install on new M1 CPU based Macs. 39 | Here are some instructions for Macs only: 40 | 41 | Before running installer, make sure you use OpenBLAS correctly from Homebrew: 42 | 43 | .. code-block::shell 44 | 45 | brew install openblas 46 | export OPENBLAS="$(brew --prefix openblas)" 47 | 48 | Running Jupyter notebooks with pdb based debuggers 49 | -------------------------------------------------- 50 | 51 | You can run the notebooks from console: 52 | 53 | .. code-block::shell 54 | 55 | ipython --TerminalIPythonApp.file_to_run=notebooks/pancakeswap-ema-b.ipynb 56 | 57 | Then any `pdb` or `ipdb` breakpoints will work correctly. 58 | 59 | Manually setting up Jupyter kernel for Visual Studio Code 60 | --------------------------------------------------------- 61 | 62 | Create kern 63 | 64 | .. code-block:: shell 65 | 66 | # First activate virtual env 67 | python3 -m ipykernel install --user --name=testx 68 | 69 | Then 70 | 71 | Visual Studio Code IOPub limit issue 72 | ------------------------------------ 73 | 74 | You might need ot increase the kernel IOPub limits. 75 | The only way to do this for now is to start the kernel from the command line and 76 | then give it this as an option. 77 | 78 | .. code-block:: shell 79 | 80 | # Default is 1000/s 81 | jupyter server --ServerApp.iopub_msg_rate_limit 10000 82 | 83 | Then use Visual Studio Code or PyCharm "Connect to remote kernel" feature 84 | to connect this kernel you started from the command line yourself. 85 | Then run the notebook. 86 | 87 | PyCharm using a remote kernel 88 | ----------------------------- 89 | 90 | PyCharm "Managed kernel" option fail to run notebooks. 91 | You can work around this by launching Jupyter server in terminal 92 | and create "remote kernel" option: 93 | 94 | .. code-block:: shell 95 | 96 | poetry shell 97 | jupyter server --ServerApp.iopub_msg_rate_limit 10000 98 | 99 | - Get the URL with the access token 100 | 101 | - Add new kernel in PyCharm 102 | 103 | - Switch to this kernel -------------------------------------------------------------------------------- /trading_strategy_docs/__init__.py: -------------------------------------------------------------------------------- 1 | """Nothing here yet. Will put custom Python code for Sphinx here.""" -------------------------------------------------------------------------------- /trading_strategy_docs/sphinx_render_patch.py: -------------------------------------------------------------------------------- 1 | # Monkey-patch autosummary template context 2 | from sphinx.ext.autosummary.generate import AutosummaryRenderer 3 | 4 | 5 | def smart_fullname(fullname): 6 | parts = fullname.split(".") 7 | return ".".join(parts[1:]) 8 | 9 | 10 | def get_first_line(docstring: str | None) -> str: 11 | if not docstring: 12 | # __doc__ can be None 13 | return "" 14 | lines = docstring.split("\n") 15 | return lines[0] 16 | 17 | 18 | def extract_module_docstring(mod_name) -> str: 19 | """See _templates/autosummary/base.rst""" 20 | import sys 21 | mod = sys.modules[mod_name] 22 | return get_first_line(getattr(mod, "__doc__", "")) 23 | 24 | 25 | def partial_name(fullname): 26 | parts = fullname.split(".") 27 | return parts[-1] 28 | 29 | 30 | def extract_object_docstring(dotted_path: str) -> str: 31 | """See _templates/autosummary/base.rst""" 32 | from zope.dottedname.resolve import resolve 33 | try: 34 | obj = resolve(dotted_path) 35 | except AttributeError as e: 36 | # pandas_ta aliases a module with a function 37 | # 'pandas_ta.volatility.aberration' 38 | # AttributeError("'function' object has no attribute 'aberration'") 39 | return "" 40 | return get_first_line(getattr(obj, "__doc__", "")) 41 | 42 | 43 | def extract_mod_path(dotted_path: str) -> str: 44 | path = dotted_path.split(".") 45 | return ".".join(path[0:-1]) 46 | 47 | 48 | # Patch autosummary internals to allow our tuned templates to access 49 | # necessary Python functions 50 | def fixed_init(self, app): 51 | AutosummaryRenderer.__old_init__(self, app) 52 | self.env.filters["smart_fullname"] = smart_fullname 53 | self.env.filters["extract_module_docstring"] = extract_module_docstring 54 | self.env.filters["extract_object_docstring"] = extract_object_docstring 55 | self.env.filters["extract_mod_path"] = extract_mod_path 56 | self.env.filters["partial_name"] = partial_name 57 | 58 | 59 | AutosummaryRenderer.__old_init__ = AutosummaryRenderer.__init__ 60 | AutosummaryRenderer.__init__ = fixed_init 61 | 62 | 63 | # 64 | # Monkey patch meta generation. 65 | # See _templates/autosummary.base.rst 66 | # 67 | 68 | from sphinx.addnodes import meta 69 | from docutils import nodes 70 | import docutils.nodes 71 | from docutils.io import StringOutput 72 | from sphinx.util.osutil import relative_uri 73 | 74 | def write_doc(self, docname: str, doctree: nodes.document) -> None: 75 | destination = StringOutput(encoding='utf-8') 76 | doctree.settings = self.docsettings 77 | 78 | self.secnumbers = self.env.toc_secnumbers.get(docname, {}) 79 | self.fignumbers = self.env.toc_fignumbers.get(docname, {}) 80 | self.imgpath = relative_uri(self.get_target_uri(docname), '_images') 81 | self.dlpath = relative_uri(self.get_target_uri(docname), '_downloads') 82 | self.current_docname = docname 83 | self.docwriter.write(doctree, destination) 84 | self.docwriter.assemble_parts() 85 | body = self.docwriter.parts['fragment'] 86 | metatags = self.docwriter.clean_meta 87 | 88 | ctx = self.get_doc_context(docname, body, metatags) 89 | 90 | # Pass the custom meta attributes in raw objects instead 91 | # of contatenad HTML soup 92 | class ExtractMeta(nodes.GenericNodeVisitor): 93 | 94 | def __init__(self, document): 95 | super().__init__(document) 96 | self.metas = {} 97 | 98 | def default_visit(self, node): 99 | 100 | if isinstance(node, meta): 101 | self.metas[node.attributes.get("name")] = node.rawcontent 102 | 103 | if isinstance(node, docutils.nodes.meta): 104 | self.metas[node.attributes.get("name")] = node.attributes.get("content") 105 | 106 | return False 107 | 108 | def default_departure(self, node): 109 | return False 110 | 111 | meta_extractor = ExtractMeta(doctree) 112 | doctree.walkabout(meta_extractor) 113 | ctx["metas"] = meta_extractor.metas 114 | 115 | self.handle_page(docname, ctx, event_arg=doctree) 116 | 117 | from sphinx.builders.html import StandaloneHTMLBuilder 118 | StandaloneHTMLBuilder.write_doc = write_doc 119 | -------------------------------------------------------------------------------- /trading_strategy_docs/sphinx_sitemap_patch.py: -------------------------------------------------------------------------------- 1 | """Monkey-patch sphinx-sitemap to support XML argument 2 | 3 | """ 4 | 5 | import os 6 | import queue 7 | from multiprocessing import Manager 8 | from pathlib import Path 9 | from typing import Any, Dict, List, Optional 10 | from xml.etree import ElementTree 11 | import logging 12 | 13 | from sphinx.application import Sphinx 14 | from sphinx.util.logging import getLogger 15 | 16 | import sphinx_sitemap 17 | from sphinx_sitemap import get_locales, hreflang_formatter 18 | 19 | PRIORITY = 0.8 20 | 21 | logger = logging.getLogger(__name__) 22 | 23 | 24 | # def _create_sitemap_patched_old(app, exception): 25 | # """Generates the sitemap.xml from the collected HTML page links""" 26 | # site_url = app.builder.config.site_url or app.builder.config.html_baseurl 27 | # if site_url: 28 | # site_url.rstrip("/") + "/" 29 | # else: 30 | # logger.warning( 31 | # "sphinx-sitemap: html_baseurl is required in conf.py." "Sitemap not built.", 32 | # type="sitemap", 33 | # subtype="configuration", 34 | # ) 35 | # return 36 | # 37 | # env = app.builder.env 38 | # import ipdb ; ipdb.set_trace() 39 | # if env.sitemap_links.empty(): 40 | # logger.info( 41 | # "sphinx-sitemap: No pages generated for %s" % app.config.sitemap_filename, 42 | # type="sitemap", 43 | # subtype="information", 44 | # ) 45 | # return 46 | # 47 | # ET.register_namespace("xhtml", "http://www.w3.org/1999/xhtml") 48 | # 49 | # root = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9") 50 | # 51 | # locales = get_locales(app, exception) 52 | # 53 | # if app.builder.config.version: 54 | # version = app.builder.config.version + "/" 55 | # else: 56 | # version = "" 57 | # 58 | # while True: 59 | # try: 60 | # link = env.sitemap_links.get_nowait() 61 | # except queue.Empty: 62 | # break 63 | # 64 | # url = ET.SubElement(root, "url") 65 | # scheme = app.config.sitemap_url_scheme 66 | # if app.builder.config.language: 67 | # lang = app.builder.config.language + "/" 68 | # else: 69 | # lang = "" 70 | # 71 | # ET.SubElement(url, "loc").text = site_url + scheme.format( 72 | # lang=lang, version=version, link=link 73 | # ) 74 | # 75 | # ET.SubElement(url, "priority").text = str(PRIORITY) 76 | # 77 | # for lang in locales: 78 | # lang = lang + "/" 79 | # ET.SubElement( 80 | # url, 81 | # "{http://www.w3.org/1999/xhtml}link", 82 | # rel="alternate", 83 | # hreflang=hreflang_formatter(lang.rstrip("/")), 84 | # href=site_url + scheme.format(lang=lang, version=version, link=link), 85 | # ) 86 | # 87 | # filename = app.outdir + "/" + app.config.sitemap_filename 88 | # ET.ElementTree(root).write( 89 | # filename, xml_declaration=True, encoding="utf-8", method="xml" 90 | # ) 91 | # 92 | # logger.info( 93 | # "sphinx-sitemap: %s was generated for URL %s in %s" 94 | # % (app.config.sitemap_filename, site_url, filename), 95 | # type="sitemap", 96 | # subtype="information", 97 | # ) 98 | 99 | def _create_sitemap_patched(app: Sphinx, exception): 100 | """ 101 | Generates the sitemap.xml from the collected HTML page links. 102 | 103 | :param app: The Sphinx Application instance 104 | """ 105 | site_url = app.builder.config.site_url or app.builder.config.html_baseurl 106 | if site_url: 107 | site_url = site_url.rstrip("/") + "/" 108 | else: 109 | logger.warning( 110 | "sphinx-sitemap: html_baseurl is required in conf.py." "Sitemap not built.", 111 | type="sitemap", 112 | subtype="configuration", 113 | ) 114 | return 115 | 116 | if app.env.app.sitemap_links.empty(): # type: ignore 117 | logger.info( 118 | "sphinx-sitemap: No pages generated for %s" % app.config.sitemap_filename, 119 | type="sitemap", 120 | subtype="information", 121 | ) 122 | return 123 | 124 | ElementTree.register_namespace("xhtml", "http://www.w3.org/1999/xhtml") 125 | 126 | root = ElementTree.Element( 127 | "urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 128 | ) 129 | 130 | locales = get_locales(app) 131 | 132 | if app.builder.config.version: 133 | version = app.builder.config.version + "/" 134 | else: 135 | version = "" 136 | 137 | while True: 138 | try: 139 | link = app.env.app.sitemap_links.get_nowait() # type: ignore 140 | except queue.Empty: 141 | break 142 | 143 | url = ElementTree.SubElement(root, "url") 144 | scheme = app.config.sitemap_url_scheme 145 | if app.builder.config.language: 146 | lang = app.builder.config.language + "/" 147 | else: 148 | lang = "" 149 | 150 | ElementTree.SubElement(url, "loc").text = site_url + scheme.format( 151 | lang=lang, version=version, link=link, 152 | ) 153 | 154 | ElementTree.SubElement(url, "priority").text = str(PRIORITY) 155 | 156 | for lang in locales: 157 | lang = lang + "/" 158 | ElementTree.SubElement( 159 | url, 160 | "{http://www.w3.org/1999/xhtml}link", 161 | rel="alternate", 162 | hreflang=hreflang_formatter(lang.rstrip("/")), 163 | href=site_url + scheme.format(lang=lang, version=version, link=link), 164 | ) 165 | 166 | filename = Path(app.outdir) / app.config.sitemap_filename 167 | ElementTree.ElementTree(root).write( 168 | filename, xml_declaration=True, encoding="utf-8", method="xml" 169 | ) 170 | 171 | logger.info( 172 | "sphinx-sitemap: %s was generated for URL %s in %s" 173 | % (app.config.sitemap_filename, site_url, filename), 174 | type="sitemap", 175 | subtype="information", 176 | ) 177 | 178 | 179 | sphinx_sitemap.create_sitemap = _create_sitemap_patched --------------------------------------------------------------------------------