Repository: shanejones/goddard
Branch: main
Commit: 56d43b260f78
Files: 25
Total size: 97.1 KB
Directory structure:
gitextract_9e686ag2/
├── .flake8
├── .github/
│ └── workflows/
│ ├── ci.yml
│ └── scripts/
│ ├── comment-ci-results.py
│ └── download-previous-artifacts.py
├── .gitmodules
├── .mypy.ini
├── .pre-commit-config.yaml
├── .pylintrc
├── Apollo11.py
├── README.md
├── Saturn5.py
├── alternative_configs/
│ ├── blacklisted_coins.json
│ ├── dynamic_coin_list.json
│ └── whitelist_busd.json
├── config-binance.json
├── docker/
│ └── Dockerfile.custom
├── docker-compose.yml
└── tests/
├── __init__.py
├── backtests/
│ ├── __init__.py
│ ├── data.py
│ ├── helpers.py
│ └── test_winrate_and_drawdown.py
├── ci-requirements.txt
├── conftest.py
└── requirements.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .flake8
================================================
[flake8]
#ignore =
max-line-length = 120
max-complexity = 12
exclude =
.git,
__pycache__,
.eggs,
user_data,
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on: [push, pull_request]
jobs:
Pre-Commit:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Set PY Cache Key
run: echo "PY=$(python --version --version | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV
- name: Pre-Commit cache
uses: actions/cache@v2
with:
path: ~/.cache/pre-commit
key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }}
- name: Check ALL Files On Branch
uses: pre-commit/action@v2.0.0
Binance:
runs-on: ubuntu-20.04
needs:
- Pre-Commit
strategy:
fail-fast: false
matrix:
strategy:
- Apollo11
- Saturn5
stake-currency:
- busd
- usdt
timerange:
- 20210801-20210901
- 20210901-20211001
- 20210801-20211001
- 20210101-20211001
steps:
- uses: actions/checkout@v2
with:
submodules: true
- name: Build Tests Image
run: |
# Random sleep in order not to hit dockerhub at the same time
sleep $(shuf -i 5-15 -n 1)
docker-compose build tests
- name: Run Tests
env:
EXTRA_ARGS: -p no:cacheprovider --exchange=binance --stake-currency=${{ matrix.stake-currency }} --strategy=${{ matrix.strategy }} tests/backtests -k ${{ matrix.timerange }}
run: |
mkdir artifacts
chmod 777 artifacts
# Random sleep in order to contain the exchanges from being hit at the same time
sleep $(shuf -i 5-15 -n 1)
docker-compose run --rm tests
- name: List Artifacts
if: always()
run: |
tree artifacts/
- name: Show Backest Output
if: always()
run: |
cat artifacts/binance/${{ matrix.stake-currency }}/${{ matrix.strategy }}/backtest-output-${{ matrix.timerange }}.txt
- name: Upload Artifacts
if: always()
uses: actions/upload-artifact@v2
with:
name: binance-testrun-artifacts
path: artifacts/
Kucoin:
runs-on: ubuntu-20.04
needs:
- Pre-Commit
strategy:
fail-fast: false
matrix:
strategy:
- Apollo11
- Saturn5
stake-currency:
- usdt
timerange:
- 20210801-20210901
- 20210901-20211001
- 20210801-20211001
- 20210101-20211001
steps:
- uses: actions/checkout@v2
with:
submodules: true
- name: Build Tests Image
run: docker-compose build tests
- name: Run Tests
env:
EXTRA_ARGS: -p no:cacheprovider --exchange=kucoin --stake-currency=${{ matrix.stake-currency }} --strategy=${{ matrix.strategy }} tests/backtests -k ${{ matrix.timerange }}
run: |
mkdir artifacts
chmod 777 artifacts
# Random sleep in order to contain the exchanges from being hit at the same time
sleep $(shuf -i 5-10 -n 1)
docker-compose run --rm tests
- name: List Artifacts
if: always()
run: |
tree artifacts/
- name: Show Backest Output
if: always()
run: |
cat artifacts/kucoin/${{ matrix.stake-currency }}/${{ matrix.strategy }}/backtest-output-${{ matrix.timerange }}.txt
- name: Upload Artifacts
if: always()
uses: actions/upload-artifact@v2
with:
name: kucoin-testrun-artifacts
path: artifacts/
Backest-CI-Stats:
runs-on: ubuntu-20.04
if: always()
needs:
- Kucoin
- Binance
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.9
- name: Install Dependencies
run: |
python -m pip install -r tests/ci-requirements.txt
- name: Download Previous Binance CI Artifacts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
python .github/workflows/scripts/download-previous-artifacts.py \
--repo=${{ github.event.repository.full_name }} \
--branch=main \
--workflow=ci.yml \
--exchange=binance \
--name=binance-testrun-artifacts downloaded-results
- name: Download Previous Kucoin CI Artifacts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
python .github/workflows/scripts/download-previous-artifacts.py \
--repo=${{ github.event.repository.full_name }} \
--branch=main \
--workflow=ci.yml \
--exchange=kucoin \
--name=kucoin-testrun-artifacts downloaded-results
- name: Download Current Binance CI Artifacts
uses: actions/download-artifact@v2
with:
name: binance-testrun-artifacts
path: downloaded-results/current
- name: Download Current Kucoin CI Artifacts
uses: actions/download-artifact@v2
with:
name: kucoin-testrun-artifacts
path: downloaded-results/current
- name: Show Environ
run: |
env
- name: Show Downloaded Artifacts
run: |
tree downloaded-results
- name: Comment CI Results
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
python .github/workflows/scripts/comment-ci-results.py \
--repo=${{ github.event.repository.full_name }} downloaded-results
================================================
FILE: .github/workflows/scripts/comment-ci-results.py
================================================
# pylint: disable=invalid-name
import argparse
import json
import os
import pathlib
import pprint
import sys
import github
from github.GithubException import GithubException
def delete_previous_comments(commit, created_comment_ids, exchanges):
comment_starts = tuple({f"# {exchange.capitalize()}" for exchange in exchanges})
comment_starts += tuple({f"## {exchange.capitalize()}" for exchange in exchanges})
comment_starts += tuple({f"### {exchange.capitalize()}" for exchange in exchanges})
for comment in commit.get_comments():
if comment.user.login not in ("github-actions[bot]", "s0undt3ch"):
# Not a comment made by this bot
continue
if comment.id in created_comment_ids:
# These are the comments we have just created
continue
if not comment.body.startswith(comment_starts):
# This comment does not start with our headers
continue
# We have a match, delete it
print(f"Deleting previous comment {comment}")
comment.delete()
def build_row_line(*, current_value, previous_value, higher_is_better=True, percentage=True):
if percentage is True:
pct = " %"
else:
pct = ""
if isinstance(current_value, str) or isinstance(previous_value, str):
if not isinstance(current_value, str):
current_value = f"{current_value}{pct}"
if not isinstance(previous_value, str):
previous_value = f"{previous_value}{pct}"
return f" \N{DOUBLE EXCLAMATION MARK} | {current_value} | {previous_value} |"
same = "\N{SNOWFLAKE}"
if higher_is_better:
higher = "\N{ROCKET}"
lower = "\N{COLLISION SYMBOL}"
else:
lower = "\N{ROCKET}"
higher = "\N{COLLISION SYMBOL}"
row_line = ""
if current_value > previous_value:
row_line += f" {higher} | {current_value}{pct} |"
elif current_value == previous_value:
row_line += f" {same} | {current_value}{pct} |"
elif current_value < previous_value:
row_line += f" {lower} | {current_value}{pct} |"
row_line += f" {previous_value}{pct} |"
return row_line
def get_value_for_report(*, results_data, exchange, currency, strategy, timerange, report_name, key, round_cases=0):
value = results_data[exchange][report_name]["results"][currency][strategy][timerange][key]
if not isinstance(value, str) and round_cases:
value = round(value, round_cases)
return value
def comment_results(options, results_data):
gh = github.Github(os.environ["GITHUB_TOKEN"])
repo = gh.get_repo(options.repo)
print(f"Loaded Repository: {repo.full_name}", file=sys.stderr, flush=True)
exchanges = set()
comment_ids = set()
commit = repo.get_commit(os.environ["GITHUB_SHA"])
print(f"Loaded Commit: {commit}", file=sys.stderr, flush=True)
for exchange in sorted(results_data):
exchanges.add(exchange)
name = "Current"
for currency in results_data[exchange][name]["results"]:
for strategy in results_data[exchange][name]["results"][currency]:
comment_body = f"# {exchange.capitalize()} - {currency.upper()} - {strategy.capitalize()}\n\n"
timeranges = results_data[exchange][name]["results"][currency][strategy]
for timerange in timeranges:
comment_body += f"## {timerange}\n\n"
previous_report_sha = results_data[exchange]["Previous"]["sha"]
previous_report_label = (
f"[Previous](https://github.com/{options.repo}/commit/{previous_report_sha})"
)
comment_body += f"| | | Current | {previous_report_label} |\n"
comment_body += "| --: | :--: | --: | --: |\n"
# Sort key, making sure buy tags are also sorted, but last in the list
buy_tags = []
sorted_keys = []
for key in sorted(timeranges[timerange]):
if key.startswith("buy_signal_"):
buy_tags.append(key)
continue
sorted_keys.append(key)
for key in sorted_keys + buy_tags:
row_line = "| "
if key == "max_drawdown":
label = "Max Drawdown"
row_line += f" {label } |"
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
round_cases=4,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
round_cases=4,
)
row_line += build_row_line(
current_value=current_value, previous_value=previous_value, higher_is_better=False
)
comment_body += f"{row_line}\n"
elif key == "profit_mean_pct":
label = "Profit Mean"
row_line += f" {label } |"
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
round_cases=4,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
round_cases=4,
)
row_line += build_row_line(current_value=current_value, previous_value=previous_value)
comment_body += f"{row_line}\n"
elif key == "profit_sum_pct":
label = "Profit Sum"
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
round_cases=4,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
round_cases=4,
)
row_line += f" {label } |"
row_line += build_row_line(current_value=current_value, previous_value=previous_value)
comment_body += f"{row_line}\n"
elif key == "profit_total_pct":
label = "Profit Total"
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
round_cases=4,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
round_cases=4,
)
row_line += f" {label } |"
row_line += build_row_line(current_value=current_value, previous_value=previous_value)
comment_body += f"{row_line}\n"
elif key == "winrate":
label = "Win Rate"
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
round_cases=4,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
round_cases=4,
)
row_line += f" {label } |"
row_line += build_row_line(current_value=current_value, previous_value=previous_value)
comment_body += f"{row_line}\n"
elif key == "trades":
label = "Trades"
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
)
row_line += f" {label } |"
row_line += build_row_line(
current_value=current_value, previous_value=previous_value, percentage=False
)
comment_body += f"{row_line}\n"
elif key == "duration_avg":
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
)
label = "Average Duration"
comment_body += f" {label } | \N{STOPWATCH} | {current_value} | {previous_value} |\n"
elif key.startswith("buy_signal"):
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
)
comment_body += f" {key} | \N{SPORTS MEDAL} | {current_value} | {previous_value} |\n"
else:
current_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Current",
key=key,
)
previous_value = get_value_for_report(
results_data=results_data,
exchange=exchange,
currency=currency,
strategy=strategy,
timerange=timerange,
report_name="Previous",
key=key,
)
label = key
comment_body += f" {label } | | {current_value} | {previous_value} |\n"
ft_output = (
options.path / "current" / exchange / currency / strategy / f"backtest-output-{timerange}.txt"
)
comment_body += "\n<details>\n"
comment_body += "<summary>Freqtrade Backest Output (click me)</summary>\n"
comment_body += f"<pre>{ft_output.read_text().strip()}</pre>\n"
comment_body += "</details>\n"
comment_body += "\n\n"
comment = commit.create_comment(comment_body.rstrip())
print(f"Created Comment: {comment}", file=sys.stderr, flush=True)
comment_ids.add(comment.id)
delete_previous_comments(commit, comment_ids, exchanges)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--repo", required=True, help="The Organization Repository")
parser.add_argument("path", metavar="PATH", type=pathlib.Path, help="Path where artifacts are extracted")
if not os.environ.get("GITHUB_TOKEN"):
parser.exit(status=1, message="GITHUB_TOKEN environment variable not set")
options = parser.parse_args()
if not options.path.is_dir():
parser.exit(
status=1,
message=f"The directory where artifacts should have been extracted, {options.path}, does not exist",
)
reports_info_path = options.path / "reports-info.json"
if not reports_info_path.exists():
parser.exit(status=1, message=f"The {reports_info_path}, does not exist")
reports_info = json.loads(reports_info_path.read_text())
for exchange in reports_info:
reports_info[exchange]["Current"] = {
"results": {},
"sha": os.environ["GITHUB_SHA"],
"path": options.path / "current",
}
reports_data = {}
for exchange in reports_info:
keys = set()
reports_data[exchange] = {}
for name in sorted(reports_info[exchange]):
exchange_results = {}
reports_data[exchange][name] = {
"results": exchange_results,
"sha": reports_info[exchange][name]["sha"],
}
results_path = pathlib.Path(reports_info[exchange][name]["path"])
for _exchange in results_path.glob("*"):
if _exchange.name != exchange:
continue
for currency in _exchange.glob("*"):
exchange_results[currency.name] = {}
for strategy in currency.glob("*"):
exchange_results[currency.name][strategy.name] = {}
for results_file in strategy.rglob("ci-results-*"):
exchange_results[currency.name][strategy.name].update(json.loads(results_file.read_text()))
names = list(reports_data[exchange])
for name in names:
for currency in reports_data[exchange][name]["results"]:
for strategy in reports_data[exchange][name]["results"][currency]:
for timerange in reports_data[exchange][name]["results"][currency][strategy]:
for key in reports_data[exchange][name]["results"][currency][strategy][timerange]:
keys.add(key)
for oname in names:
if oname == name:
continue
oresults = reports_data[exchange][oname]["results"]
for part in (currency, strategy):
if part not in oresults:
oresults[part] = {}
oresults = oresults[part]
if timerange not in oresults:
oresults[timerange] = {}
oresults[timerange].setdefault(key, "n/a")
pprint.pprint(reports_data)
try:
comment_results(options, reports_data)
parser.exit(0)
except GithubException as exc:
parser.exit(1, message=str(exc))
if __name__ == "__main__":
main()
================================================
FILE: .github/workflows/scripts/download-previous-artifacts.py
================================================
# pylint: disable=invalid-name,protected-access
import argparse
import json
import os
import pathlib
import pprint
import sys
import zipfile
import github
from github.GithubException import GithubException
def get_artifact_url(workflow_run, name):
_, data = workflow_run._requester.requestJsonAndCheck("GET", workflow_run.artifacts_url)
for artifact in data.get("artifacts", ()):
if artifact["name"] == name:
return artifact["archive_download_url"]
def download_previous_artifacts(repo, options):
releases = get_previous_releases(repo, options.releases)
workflow = repo.get_workflow(options.workflow)
runs = {}
release_names = {release.name: release for release in releases}
for workflow_run in workflow.get_runs():
if "Current" in runs and "Previous" in runs and not release_names:
break
if "Previous" not in runs and workflow_run.head_branch == options.branch:
artifact_url = get_artifact_url(workflow_run, options.name)
if artifact_url:
runs["Previous"] = (workflow_run.head_sha, artifact_url)
continue
if "Current" not in runs and str(workflow_run.id) == os.environ.get("GITHUB_RUN_ID"):
runs["Current"] = (
os.environ["GITHUB_SHA"],
get_artifact_url(workflow_run, options.name),
)
continue
release = release_names.pop(workflow_run.head_branch, None)
if release:
runs[release.name] = (release.commit.sha, get_artifact_url(workflow_run, options.name))
print(f"Collected Runs:\n{pprint.pformat(runs)}", file=sys.stderr, flush=True)
reports_info_path = options.path / "reports-info.json"
if reports_info_path.exists():
reports_info = json.loads(reports_info_path.read_text())
else:
reports_info = {}
if options.exchange not in reports_info:
reports_info[options.exchange] = {}
for name, (sha, url) in runs.items():
if not url:
print(f"Did not find a download url for {name}", file=sys.stderr, flush=True)
reports_info[options.exchange][name] = {
"sha": sha,
"path": str(options.path / "current"),
}
continue
print(f"Downloading {name} {url}....", file=sys.stderr, flush=True)
# While pygithub doesn't support GH actions and their Artifacts interactions
# We doit the hacky way
req_headers = {}
repo._requester._Requester__authenticate(url, req_headers, None)
response = repo._requester._Requester__connection.session.get(url, headers=req_headers, allow_redirects=True)
if response.status_code == 200:
outfile = options.path / f"{name}-{options.name}.zip"
with open(outfile, "wb") as wfh:
for data in response.iter_content(chunk_size=512 * 1024):
if data:
wfh.write(data)
print(f"Wrote {outfile}", file=sys.stderr, flush=True)
outdir = options.path / name.lower()
if not outdir.is_dir():
outdir.mkdir()
zipfile.ZipFile(outfile).extractall(path=outdir)
outfile.unlink()
reports_info[options.exchange][name] = {"sha": sha, "path": str(outdir.resolve())}
reports_info_path.write_text(json.dumps(reports_info))
def get_previous_releases(repo, latest_n_releases):
releases = []
for tag in repo.get_tags():
if len(releases) == latest_n_releases:
break
releases.append(tag)
return releases
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--repo", required=True, help="The Organization Repository")
parser.add_argument("--exchange", required=True, help="The exchange name")
parser.add_argument("--name", required=True, help="The artifacts name to get")
parser.add_argument(
"--workflow",
required=True,
help="The workflow name from where to get artifacts",
)
parser.add_argument(
"--branch",
required=True,
help="The branch from where to get the previous artifacts",
)
parser.add_argument(
"--releases",
type=int,
default=3,
help="Besides previous artifacts, how many previous release(tags) artifacts to get",
)
parser.add_argument(
"path",
metavar="PATH",
type=pathlib.Path,
help="Path where to extract artifacts",
)
if not os.environ.get("GITHUB_TOKEN"):
parser.exit(status=1, message="GITHUB_TOKEN environment variable not set")
options = parser.parse_args()
results_dir = pathlib.Path(options.path).resolve()
if not results_dir.is_dir():
results_dir.mkdir()
gh = github.Github(os.environ["GITHUB_TOKEN"])
repo = gh.get_repo(options.repo)
print(f"Loaded Repository: {repo.full_name}", file=sys.stderr, flush=True)
try:
download_previous_artifacts(repo, options)
parser.exit(0)
except GithubException as exc:
parser.exit(1, message=str(exc))
if __name__ == "__main__":
main()
================================================
FILE: .gitmodules
================================================
[submodule "user_data/data"]
path = user_data/data
url = https://github.com/shanejones/goddard-data.git
branch = main
================================================
FILE: .mypy.ini
================================================
[mypy]
ignore_missing_imports = True
[mypy-tests.*]
ignore_errors = True
================================================
FILE: .pre-commit-config.yaml
================================================
---
minimum_pre_commit_version: 1.15.2
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: check-merge-conflict # Check for files that contain merge conflict strings.
- id: trailing-whitespace # Trims trailing whitespace.
args: [--markdown-linebreak-ext=md]
- id: mixed-line-ending # Replaces or checks mixed line ending.
args: [--fix=lf]
- id: end-of-file-fixer # Makes sure files end in a newline and only a newline.
- id: check-merge-conflict # Check for files that contain merge conflict strings.
- id: check-ast # Simply check whether files parse as valid python.
# ----- Formatting ------------------------------------------------------------------------------------------------>
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade
name: Rewrite Code to be Py3.5+
args: [--py38-plus]
- repo: https://github.com/hakancelik96/unimport
rev: "0.9.2"
hooks:
- id: unimport
name: Remove unused imports
args: [--remove]
- repo: https://github.com/asottile/reorder_python_imports
rev: v2.6.0
hooks:
- id: reorder-python-imports
args: [
--py38-plus,
]
- repo: https://github.com/psf/black
rev: 21.9b0
hooks:
- id: black
args: [--line-length=120, --target-version=py38]
- repo: https://github.com/asottile/blacken-docs
rev: v1.11.0
hooks:
- id: blacken-docs
args: [--skip-errors]
files: ^.*\.py$
additional_dependencies: [black==21.9b0]
- repo: https://github.com/pycqa/flake8
rev: '4.0.1'
hooks:
- id: flake8
exclude: ^.github/workflows/.*$
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910
hooks:
- id: mypy
files: ^.*\.py$
args: []
additional_dependencies:
- pandas-stubs
- types-attrs
# <---- Formatting -------------------------------------------------------------------------------------------------
================================================
FILE: .pylintrc
================================================
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
# for backward compatibility.)
extension-pkg-whitelist=numpy,talib,talib.abstract
# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=
# Specify a score threshold to be exceeded before program exits with error.
fail-under=10.0
# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS,vendor
# Add files or directories matching the regex patterns to the ignore-list. The
# regex matches against paths.
ignore-paths=
# Files or directories matching the regex patterns are skipped. The regex
# matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Min Python version to use for version dependend checks. Will default to the
# version used to run pylint.
py-version=3.8
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
R,
missing-module-docstring,
missing-class-docstring,
missing-function-docstring
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'error', 'warning', 'refactor', and 'convention'
# which contain the number of messages in each category, as well as 'statement'
# which is the total number of statements analyzed. This score is used by the
# global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit,argparse.parse_error
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=120
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
#notes-rgx=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: none. To make it work,
# install the 'python-enchant' package.
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear and the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=numpy,talib,talib.abstract
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# List of decorators that change the signature of a decorated function.
signature-mutators=
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=no
# Signatures are removed from the similarity computation
ignore-signatures=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[DESIGN]
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception
================================================
FILE: Apollo11.py
================================================
from datetime import datetime
from datetime import timedelta
from functools import reduce
import freqtrade.vendor.qtpylib.indicators as qtpylib
import talib.abstract as ta
from freqtrade.persistence import Trade
from freqtrade.strategy import IStrategy
from pandas import DataFrame
def to_minutes(**timdelta_kwargs):
return int(timedelta(**timdelta_kwargs).total_seconds() / 60)
class Apollo11(IStrategy):
# Strategy created by Shane Jones https://twitter.com/shanejones
#
# Assited by a number of contributors https://github.com/shanejones/goddard/graphs/contributors
#
# Original repo hosted at https://github.com/shanejones/goddard
timeframe = "15m"
# Stoploss
stoploss = -0.16
startup_candle_count: int = 480
trailing_stop = False
use_custom_stoploss = True
use_sell_signal = False
# signal controls
buy_signal_1 = True
buy_signal_2 = True
buy_signal_3 = True
# ROI table:
minimal_roi = {
"0": 10, # This is 10000%, which basically disables ROI
}
# Indicator values:
# Signal 1
s1_ema_xs = 3
s1_ema_sm = 5
s1_ema_md = 10
s1_ema_xl = 50
s1_ema_xxl = 240
# Signal 2
s2_ema_input = 50
s2_ema_offset_input = -1
s2_bb_sma_length = 49
s2_bb_std_dev_length = 64
s2_bb_lower_offset = 3
s2_fib_sma_len = 50
s2_fib_atr_len = 14
s2_fib_lower_value = 4.236
s3_ema_long = 50
s3_ema_short = 20
s3_ma_fast = 10
s3_ma_slow = 20
@property
def protections(self):
return [
{
# Don't enter a trade right after selling a trade.
"method": "CooldownPeriod",
"stop_duration": to_minutes(minutes=0),
},
{
# Stop trading if max-drawdown is reached.
"method": "MaxDrawdown",
"lookback_period": to_minutes(hours=12),
"trade_limit": 20, # Considering all pairs that have a minimum of 20 trades
"stop_duration": to_minutes(hours=1),
"max_allowed_drawdown": 0.2, # If max-drawdown is > 20% this will activate
},
{
# Stop trading if a certain amount of stoploss occurred within a certain time window.
"method": "StoplossGuard",
"lookback_period": to_minutes(hours=6),
"trade_limit": 4, # Considering all pairs that have a minimum of 4 trades
"stop_duration": to_minutes(minutes=30),
"only_per_pair": False, # Looks at all pairs
},
{
# Lock pairs with low profits
"method": "LowProfitPairs",
"lookback_period": to_minutes(hours=1, minutes=30),
"trade_limit": 2, # Considering all pairs that have a minimum of 2 trades
"stop_duration": to_minutes(hours=15),
"required_profit": 0.02, # If profit < 2% this will activate for a pair
},
{
# Lock pairs with low profits
"method": "LowProfitPairs",
"lookback_period": to_minutes(hours=6),
"trade_limit": 4, # Considering all pairs that have a minimum of 4 trades
"stop_duration": to_minutes(minutes=30),
"required_profit": 0.01, # If profit < 1% this will activate for a pair
},
]
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# Adding EMA's into the dataframe
dataframe["s1_ema_xs"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xs)
dataframe["s1_ema_sm"] = ta.EMA(dataframe, timeperiod=self.s1_ema_sm)
dataframe["s1_ema_md"] = ta.EMA(dataframe, timeperiod=self.s1_ema_md)
dataframe["s1_ema_xl"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xl)
dataframe["s1_ema_xxl"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xxl)
s2_ema_value = ta.EMA(dataframe, timeperiod=self.s2_ema_input)
s2_ema_xxl_value = ta.EMA(dataframe, timeperiod=200)
dataframe["s2_ema"] = s2_ema_value - s2_ema_value * self.s2_ema_offset_input
dataframe["s2_ema_xxl_off"] = s2_ema_xxl_value - s2_ema_xxl_value * self.s2_fib_lower_value
dataframe["s2_ema_xxl"] = ta.EMA(dataframe, timeperiod=200)
s2_bb_sma_value = ta.SMA(dataframe, timeperiod=self.s2_bb_sma_length)
s2_bb_std_dev_value = ta.STDDEV(dataframe, self.s2_bb_std_dev_length)
dataframe["s2_bb_std_dev_value"] = s2_bb_std_dev_value
dataframe["s2_bb_lower_band"] = s2_bb_sma_value - (s2_bb_std_dev_value * self.s2_bb_lower_offset)
s2_fib_atr_value = ta.ATR(dataframe, timeframe=self.s2_fib_atr_len)
s2_fib_sma_value = ta.SMA(dataframe, timeperiod=self.s2_fib_sma_len)
dataframe["s2_fib_lower_band"] = s2_fib_sma_value - s2_fib_atr_value * self.s2_fib_lower_value
s3_bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=3)
dataframe["s3_bb_lowerband"] = s3_bollinger["lower"]
dataframe["s3_ema_long"] = ta.EMA(dataframe, timeperiod=self.s3_ema_long)
dataframe["s3_ema_short"] = ta.EMA(dataframe, timeperiod=self.s3_ema_short)
dataframe["s3_fast_ma"] = ta.EMA(dataframe["volume"] * dataframe["close"], self.s3_ma_fast) / ta.EMA(
dataframe["volume"], self.s3_ma_fast
)
dataframe["s3_slow_ma"] = ta.EMA(dataframe["volume"] * dataframe["close"], self.s3_ma_slow) / ta.EMA(
dataframe["volume"], self.s3_ma_slow
)
# Volume weighted MACD
dataframe["fastMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], 12) / ta.EMA(dataframe["volume"], 12)
dataframe["slowMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], 26) / ta.EMA(dataframe["volume"], 26)
dataframe["vwmacd"] = dataframe["fastMA"] - dataframe["slowMA"]
dataframe["signal"] = ta.EMA(dataframe["vwmacd"], 9)
dataframe["hist"] = dataframe["vwmacd"] - dataframe["signal"]
return dataframe
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# basic buy methods to keep the strategy simple
if self.buy_signal_1:
conditions = [
dataframe["vwmacd"] < dataframe["signal"],
dataframe["low"] < dataframe["s1_ema_xxl"],
dataframe["close"] > dataframe["s1_ema_xxl"],
qtpylib.crossed_above(dataframe["s1_ema_sm"], dataframe["s1_ema_md"]),
dataframe["s1_ema_xs"] < dataframe["s1_ema_xl"],
dataframe["volume"] > 0,
]
dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1")
if self.buy_signal_2:
conditions = [
qtpylib.crossed_above(dataframe["s2_fib_lower_band"], dataframe["s2_bb_lower_band"]),
dataframe["close"] < dataframe["s2_ema"],
dataframe["volume"] > 0,
]
dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_2")
if self.buy_signal_3:
conditions = [
dataframe["low"] < dataframe["s3_bb_lowerband"],
dataframe["high"] > dataframe["s3_slow_ma"],
dataframe["high"] < dataframe["s3_ema_long"],
dataframe["volume"] > 0,
]
dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_3")
if not all([self.buy_signal_1, self.buy_signal_2, self.buy_signal_3]):
dataframe.loc[(), "buy"] = 0
return dataframe
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# This is essentailly ignored as we're using strict ROI / Stoploss / TTP sale scenarios
dataframe.loc[(), "sell"] = 0
return dataframe
def custom_stoploss(
self, pair: str, trade: Trade, current_time: datetime, current_rate: float, current_profit: float, **kwargs
) -> float:
if current_profit > 0.2:
return 0.04
if current_profit > 0.1:
return 0.03
if current_profit > 0.06:
return 0.02
if current_profit > 0.03:
return 0.01
# Let's try to minimize the loss
if current_profit <= -0.10:
if trade.open_date_utc + timedelta(hours=60) < current_time:
# After 60H since buy
return current_profit / 1.75
if current_profit <= -0.08:
if trade.open_date_utc + timedelta(hours=120) < current_time:
# After 120H since buy
return current_profit / 1.70
return -1
================================================
FILE: README.md
================================================
# Goddard
**A collection of small, simple strategies for Freqtrade.** Simply add the strategy you choose in your strategies folder and run.
> ⚠️ General Crypto Warning
>
> Crypto and crypto markets are very volatile. By using these strategies, you do so at your own risk. We are not to be held accountable for any losses caused. We're not even to be held responsible for any wins you make either.
>
>The results you get will not always be the same as someone else because many factors cause differences in everyone's setups. Server location, server performance, coin lists, config and filter differences, market conditions all play into this.
>
>Don't let greed take over and always manage your own risk and make sure you take profits along the way to recoup your initial investment. Never invest more than you can afford to lose.
>
> *Always do your own backtesting or dry runs before running this strategy live*
# Strategies
Goddard is made up of 2 simple strategies that can be run on any time frame you want. The buy signals for both strategies are the same. They only differ in the way they sell.
Buy Signals can be seen and experimented with over on TradingView.
~~Head to this link https://www.tradingview.com/script/uXtX0WCT-Goddard/ and then scroll down and Add to your Favourite indicators. You can then add this to any chart. Using the settings for the strategy (Hover over the name on the chart, click the settings cog), you can adjust the values used to make those buy decisions.~~
~~If you find a better selection of values that result in better buy signals, be sure to submit these using the issues tracker within GitHub and we'll test and apply to the main repo after backtesting.~~
*TradingView keep blocking my script from the public library. Please ignore the above for now until I resolve it. *
You'll notice these strategies are not fast. Their intention is to hold out for profit. If you want a bot that trades hundreds of times per day, this is not for you. Is it profit you want or more trades?
These strategies work fine with any number of trade slots. During development, most of us used five trade slots. These strategies also work with any number of trade slots. The most we live tested to was 25 trade slots with a coin list of 25. This ensures we don't miss any trades on any coins.
## Saturn5
Uses buy signals to make trades low in a dip or at the start of an uplift. Our aim here is to get out of this trade when we hit 5% profit.
We have a 20% stop loss on this to allow for natural fluctuations at the start of the trade and to also get you out should this trade tank.
The aim of this strategy is to make another trade as soon as a trade sells. In our tests, this strategy always had full slots.
## Apollo11
This strategy is the same as Saturn5, except we remove the 5% fixed profit.
The sell signals here use a custom stop-loss function to help your trades travel as high as possible. This is done by using tiers, so the trailing stop loss changes as your profit rises too. In our tests, we found some trades to exceed 1000% in profit so we're pretty confident this works well.
# For developers
All tests should be done using branches on Git.
## Clone The Repository
If you plan to only clone the repository to use the strategy, a regular ``git clone`` will do.
However, if you plan on running additional strategies or run the test suite, you need to clone
the repository and it's submodules.
### Newer versions of Git
```bash
git clone --recurse-submodules git@github.com:shanejones/goddard.git checkout-path
```
### Older versions of Git
```bash
git clone --recursive git@github.com:shanejones/goddard.git checkout-path
```
### Existing Checkouts
```
git submodule update --remote --checkout
```
## Workflow
Development and test versions should all follow the same branch formatting. Some examples are below
```
dev/Saturn5-new-buy-signal
dev/Apollo11-add-csl-level
fix/Saturn5-fixing-logic
```
Prefix new functionality with `dev` and any bugfixes with `fix`.
Please ensure your commit messages give details on any significant changes
When a branch has been Merged and Squashed with the main branch, the branches will be deleted. If your branch test is unsuccessful in your tests, delete it when you are done. We should try to keep the number of branches minimal if possible.
## Pre-Commit
Code style guidelines and static lint checking is enforced by [pre-commit](https://pre-commit.com).
After cloning the repository, be sure to run the following:
```
pip install pre-commit
pre-commit install --install-hooks
```
# Why Goddard
Robert Goddard was an American physicist who sent the first liquid-fueled rocket aloft in Auburn, Massachusetts, on March 16, 1926. He had two U.S. patents for using a liquid-fueled rocket and also for a two- or three-stage rocket using solid fuel, according to NASA.
In case you haven't guessed, the strategies have space-themed names 🚀
================================================
FILE: Saturn5.py
================================================
from datetime import timedelta
from functools import reduce
import freqtrade.vendor.qtpylib.indicators as qtpylib
import talib.abstract as ta
from freqtrade.strategy import IStrategy
from pandas import DataFrame
def to_minutes(**timdelta_kwargs):
return int(timedelta(**timdelta_kwargs).total_seconds() / 60)
class Saturn5(IStrategy):
# Strategy created by Shane Jones https://twitter.com/shanejones
#
# Assited by a number of contributors https://github.com/shanejones/goddard/graphs/contributors
#
# Original repo hosted at https://github.com/shanejones/goddard
timeframe = "15m"
# Stoploss
stoploss = -0.20
startup_candle_count: int = 480
trailing_stop = False
use_custom_stoploss = False
use_sell_signal = False
# signal controls
buy_signal_1 = True
buy_signal_2 = True
buy_signal_3 = True
# ROI table:
minimal_roi = {
"0": 0.05,
}
# Indicator values:
# Signal 1
s1_ema_xs = 3
s1_ema_sm = 5
s1_ema_md = 10
s1_ema_xl = 50
s1_ema_xxl = 240
# Signal 2
s2_ema_input = 50
s2_ema_offset_input = -1
s2_bb_sma_length = 49
s2_bb_std_dev_length = 64
s2_bb_lower_offset = 3
s2_fib_sma_len = 50
s2_fib_atr_len = 14
s2_fib_lower_value = 4.236
s3_ema_long = 50
s3_ema_short = 20
s3_ma_fast = 10
s3_ma_slow = 20
@property
def protections(self):
return [
{
# Don't enter a trade right after selling a trade.
"method": "CooldownPeriod",
"stop_duration": to_minutes(minutes=0),
},
{
# Stop trading if max-drawdown is reached.
"method": "MaxDrawdown",
"lookback_period": to_minutes(hours=12),
"trade_limit": 20, # Considering all pairs that have a minimum of 20 trades
"stop_duration": to_minutes(hours=1),
"max_allowed_drawdown": 0.2, # If max-drawdown is > 20% this will activate
},
{
# Stop trading if a certain amount of stoploss occurred within a certain time window.
"method": "StoplossGuard",
"lookback_period": to_minutes(hours=3),
"trade_limit": 4, # Considering all pairs that have a minimum of 4 trades
"stop_duration": to_minutes(hours=6),
"only_per_pair": False, # Looks at all pairs
},
{
# Lock pairs with low profits
"method": "LowProfitPairs",
"lookback_period": to_minutes(hours=1, minutes=30),
"trade_limit": 2, # Considering all pairs that have a minimum of 2 trades
"stop_duration": to_minutes(hours=15),
"required_profit": 0.02, # If profit < 2% this will activate for a pair
},
{
# Lock pairs with low profits
"method": "LowProfitPairs",
"lookback_period": to_minutes(hours=6),
"trade_limit": 4, # Considering all pairs that have a minimum of 4 trades
"stop_duration": to_minutes(minutes=30),
"required_profit": 0.01, # If profit < 1% this will activate for a pair
},
]
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# Adding EMA's into the dataframe
dataframe["s1_ema_xs"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xs)
dataframe["s1_ema_sm"] = ta.EMA(dataframe, timeperiod=self.s1_ema_sm)
dataframe["s1_ema_md"] = ta.EMA(dataframe, timeperiod=self.s1_ema_md)
dataframe["s1_ema_xl"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xl)
dataframe["s1_ema_xxl"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xxl)
s2_ema_value = ta.EMA(dataframe, timeperiod=self.s2_ema_input)
s2_ema_xxl_value = ta.EMA(dataframe, timeperiod=200)
dataframe["s2_ema"] = s2_ema_value - s2_ema_value * self.s2_ema_offset_input
dataframe["s2_ema_xxl_off"] = s2_ema_xxl_value - s2_ema_xxl_value * self.s2_fib_lower_value
dataframe["s2_ema_xxl"] = ta.EMA(dataframe, timeperiod=200)
s2_bb_sma_value = ta.SMA(dataframe, timeperiod=self.s2_bb_sma_length)
s2_bb_std_dev_value = ta.STDDEV(dataframe, self.s2_bb_std_dev_length)
dataframe["s2_bb_std_dev_value"] = s2_bb_std_dev_value
dataframe["s2_bb_lower_band"] = s2_bb_sma_value - (s2_bb_std_dev_value * self.s2_bb_lower_offset)
s2_fib_atr_value = ta.ATR(dataframe, timeframe=self.s2_fib_atr_len)
s2_fib_sma_value = ta.SMA(dataframe, timeperiod=self.s2_fib_sma_len)
dataframe["s2_fib_lower_band"] = s2_fib_sma_value - s2_fib_atr_value * self.s2_fib_lower_value
s3_bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=3)
dataframe["s3_bb_lowerband"] = s3_bollinger["lower"]
dataframe["s3_ema_long"] = ta.EMA(dataframe, timeperiod=self.s3_ema_long)
dataframe["s3_ema_short"] = ta.EMA(dataframe, timeperiod=self.s3_ema_short)
dataframe["s3_fast_ma"] = ta.EMA(dataframe["volume"] * dataframe["close"], self.s3_ma_fast) / ta.EMA(
dataframe["volume"], self.s3_ma_fast
)
dataframe["s3_slow_ma"] = ta.EMA(dataframe["volume"] * dataframe["close"], self.s3_ma_slow) / ta.EMA(
dataframe["volume"], self.s3_ma_slow
)
# Volume weighted MACD
dataframe["fastMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], 12) / ta.EMA(dataframe["volume"], 12)
dataframe["slowMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], 26) / ta.EMA(dataframe["volume"], 26)
dataframe["vwmacd"] = dataframe["fastMA"] - dataframe["slowMA"]
dataframe["signal"] = ta.EMA(dataframe["vwmacd"], 9)
dataframe["hist"] = dataframe["vwmacd"] - dataframe["signal"]
return dataframe
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# basic buy methods to keep the strategy simple
if self.buy_signal_1:
conditions = [
dataframe["vwmacd"] < dataframe["signal"],
dataframe["low"] < dataframe["s1_ema_xxl"],
dataframe["close"] > dataframe["s1_ema_xxl"],
qtpylib.crossed_above(dataframe["s1_ema_sm"], dataframe["s1_ema_md"]),
dataframe["s1_ema_xs"] < dataframe["s1_ema_xl"],
dataframe["volume"] > 0,
]
dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1")
if self.buy_signal_2:
conditions = [
qtpylib.crossed_above(dataframe["s2_fib_lower_band"], dataframe["s2_bb_lower_band"]),
dataframe["close"] < dataframe["s2_ema"],
dataframe["volume"] > 0,
]
dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_2")
if self.buy_signal_3:
conditions = [
dataframe["low"] < dataframe["s3_bb_lowerband"],
dataframe["high"] > dataframe["s3_slow_ma"],
dataframe["high"] < dataframe["s3_ema_long"],
dataframe["volume"] > 0,
]
dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_3")
if not all([self.buy_signal_1, self.buy_signal_2, self.buy_signal_3]):
dataframe.loc[(), "buy"] = 0
return dataframe
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# This is essentailly ignored as we're using strict ROI / Stoploss / TTP sale scenarios
dataframe.loc[(), "sell"] = 0
return dataframe
================================================
FILE: alternative_configs/blacklisted_coins.json
================================================
// We have compiled a list of coins that we feel should be generally blacklisted
// Replace the section below in your main config
{
"pair_blacklist": [
// Exchange (delete as appropriate based on your exchange)
"(BNB|KCS)/.*",
// Major
"(BTC|ETH)/.*",
// Leverage
".*(_PREMIUM|BEAR|BULL|DOWN|HALF|HEDGE|UP|[1235][SL])/.*",
// Fiat
"(AUD|BRZ|CAD|CHF|EUR|GBP|HKD|IDRT|JPY|NGN|RUB|SGD|TRY|UAH|USD|ZAR)/.*",
// Stable
"(BUSD|CUSDT|DAI|PAX|PAXG|SUSD|TUSD|USDC|USDT|VAI)/.*",
// Fan coins and other pump and dumps
"(ACM|AFA|ALA|ALL|APL|ASR|ATM|BAR|CAI|CITY|FOR|GAL|GOZ|IBFK|JUV|LEG|LOCK-1|NAVI|NMR|NOV|OG|PFL|PSG|ROUSH|STV|TH|TRA|UCH|UFC|YBO)/.*",
"(CHZ|CTXC|HBAR|HORD|NMR|SHIB|SLP|XVS|ONG|ARDR)/.*",
]
}
================================================
FILE: alternative_configs/dynamic_coin_list.json
================================================
// Replace the sections below in your main config
// Caveat: This has only been tested with BUSD on Binance so far
{
"pair_whitelist": [
// As this will by dynamically generated, this section should now be empty
],
"pairlists":[
{
"method":"VolumePairList",
"number_assets": 100,
"sort_key": "quoteVolume",
"refresh_period": 1800,
"min_value": 3000000
},
{
"method": "AgeFilter",
"min_days_listed": 14
},
{
"method":"SpreadFilter",
"max_spread_ratio": 0.005
},
{
"method": "PriceFilter",
"low_price_ratio": 0.10,
"min_price": 0.001
},
{
"method":"RangeStabilityFilter",
"lookback_days": 3,
"min_rate_of_change": 0.01,
"refresh_period": 1440
},
{
"method":"VolatilityFilter",
"lookback_days": 4,
"min_volatility": 0.02,
"max_volatility": 0.75,
"refresh_period": 86400
},
{
"method": "VolumePairList",
"number_assets": 80,
"sort_key": "quoteVolume"
}
]
}
================================================
FILE: alternative_configs/whitelist_busd.json
================================================
{
"pair_whitelist": [
"1INCH/BUSD",
"AAVE/BUSD",
"AERGO/BUSD",
"ALGO/BUSD",
"ALICE/BUSD",
"ALPHA/BUSD",
"ANT/BUSD",
"AR/BUSD",
"ATA/BUSD",
"ATOM/BUSD",
"AUCTION/BUSD",
"AUDIO/BUSD",
"AVA/BUSD",
"AVAX/BUSD",
"AXS/BUSD",
"BAKE/BUSD",
"BAND/BUSD",
"BCH/BUSD",
"BCHA/BUSD",
"BEL/BUSD",
"BTT/BUSD",
"BZRX/BUSD",
"COMP/BUSD",
"COTI/BUSD",
"CREAM/BUSD",
"CRV/BUSD",
"CTK/BUSD",
"CTSI/BUSD",
"CVP/BUSD",
"DASH/BUSD",
"DATA/BUSD",
"DEGO/BUSD",
"DEXE/BUSD",
"DGB/BUSD",
"DOCK/BUSD",
"DODO/BUSD",
"DOGE/BUSD",
"DOT/BUSD",
"EGLD/BUSD",
"ENJ/BUSD",
"EPS/BUSD",
"FIL/BUSD",
"FIO/BUSD",
"FORTH/BUSD",
"FRONT/BUSD",
"FTM/BUSD",
"FXS/BUSD",
"GRT/BUSD",
"GTC/BUSD",
"HARD/BUSD",
"HOT/BUSD",
"ICP/BUSD",
"IDEX/BUSD",
"INJ/BUSD",
"IOST/BUSD",
"IOTX/BUSD",
"IQ/BUSD",
"KEEP/BUSD",
"KNC/BUSD",
"KSM/BUSD",
"LINA/BUSD",
"LINK/BUSD",
"LIT/BUSD",
"LTC/BUSD",
"LUNA/BUSD",
"MANA/BUSD",
"MATIC/BUSD",
"MDX/BUSD",
"MIR/BUSD",
"MKR/BUSD",
"NANO/BUSD",
"NEAR/BUSD",
"OCEAN/BUSD",
"ONE/BUSD",
"PERP/BUSD",
"PHA/BUSD",
"POLS/BUSD",
"POND/BUSD",
"PROM/BUSD",
"REEF/BUSD",
"RSR/BUSD",
"RUNE/BUSD",
"SAND/BUSD",
"SFP/BUSD",
"SHIB/BUSD",
"SKL/BUSD",
"SNX/BUSD",
"SOL/BUSD",
"SRM/BUSD",
"STMX/BUSD",
"SUPER/BUSD",
"SUSHI/BUSD",
"SXP/BUSD",
"THETA/BUSD",
"TKO/BUSD",
"TLM/BUSD",
"TVK/BUSD",
"TWT/BUSD",
"UFT/BUSD",
"UNI/BUSD",
"WAVES/BUSD",
"WRX/BUSD",
"XRP/BUSD",
"XTZ/BUSD",
"XVG/BUSD",
"XVS/BUSD",
"YFI/BUSD",
"ZEC/BUSD",
"ZIL/BUSD"
]
}
================================================
FILE: config-binance.json
================================================
{
"max_open_trades": 5,
"stake_currency": "BUSD",
"stake_amount": "unlimited",
"tradable_balance_ratio": 0.99,
"fiat_display_currency": "GBP",
"dry_run": false,
"cancel_open_orders_on_exit": false,
"order_types": {
"buy": "market",
"sell": "market",
"forcesell": "market",
"stoploss": "market",
"stoploss_on_exchange": false
},
"bid_strategy": {
"price_side": "ask",
"ask_last_balance": 0.0
},
"unfilledtimeout": {
"unit": "seconds",
"buy": 30,
"sell": 10
},
"ask_strategy": {
"price_side": "bid"
},
"telegram": {
"enabled": true,
"token": "",
"chat_id": ""
},
"exchange": {
"name": "binance",
"key": "",
"secret": "",
"ccxt_config": {"enableRateLimit": true},
"ccxt_async_config": {
"enableRateLimit": true,
"rateLimit": 100
},
"pair_whitelist": [
// Choose your whitelist from available options
],
"pair_blacklist": [
// Choose your blacklist from available options
]
},
"pairlists": [
{"method": "StaticPairList"},
{"method": "SpreadFilter", "max_spread_ratio": 0.005},
{
"method": "PriceFilter",
"low_price_ratio": 0.10,
"min_price": 0.001
},
{
"method": "RangeStabilityFilter",
"lookback_days": 3,
"min_rate_of_change": 0.1,
"refresh_period": 1800
},
{
"method": "VolatilityFilter",
"lookback_days": 3,
"min_volatility": 0.02,
"max_volatility": 0.75,
"refresh_period": 43200
},
{"method": "ShuffleFilter", "seed": 42}
],
"bot_name": "freqtrade-binance",
"initial_state": "running",
"forcebuy_enable": false,
"internals": {
"process_throttle_secs": 3
}
}
================================================
FILE: docker/Dockerfile.custom
================================================
FROM freqtradeorg/freqtrade:develop
COPY --chown=1000:1000 tests/requirements.txt /freqtrade
RUN pip install --user --no-cache-dir --no-build-isolation -r /freqtrade/requirements.txt
================================================
FILE: docker-compose.yml
================================================
---
version: '3'
services:
tests:
build:
context: .
dockerfile: "./docker/Dockerfile.custom"
container_name: freqtrade-backtesting
volumes:
- "./:/testing"
command: >
python -m pytest -ra -vv -s --log-cli-level=info --artifacts-path=artifacts/ ${EXTRA_ARGS:-tests/}
entrypoint: []
working_dir: /testing
backtesting:
build:
context: .
dockerfile: "./docker/Dockerfile.custom"
container_name: freqtrade-backtesting
volumes:
- "./user_data:/freqtrade/user_data"
- "./Apollo11.py:/freqtrade/Apollo11.py"
- "./Saturn5.py:/freqtrade/Saturn5.py"
command: >
backtesting
--timeframe=15m,
--timeframe-detail=5m
--enable-protections
--strategy-list ${STRATEGY_LIST:-Saturn5 Apollo11}
--timerange ${TIMERANGE:-20210601-20210701}
--config user_data/data/pairlists.json
--config user_data/data/pairlists-${STAKE_CURRENCY:-busd}.json
--config user_data/data/${EXCHANGE:-binance}-${STAKE_CURRENCY:-busd}-static.json
--max-open-trades ${MAX_OPEN_TRADES:-6}
--stake-amount ${STAKE_AMOUNT:-150}
================================================
FILE: tests/__init__.py
================================================
================================================
FILE: tests/backtests/__init__.py
================================================
================================================
FILE: tests/backtests/data.py
================================================
EXPECTED_RESULTS_DATA = (
# Binance - BUSD - Apollo11
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "busd",
"timerange": "20210801-20210901",
"max_drawdown": 60,
"winrate": 88,
},
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "busd",
"timerange": "20210901-20211001",
"max_drawdown": 148,
"winrate": 80,
},
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "busd",
"timerange": "20210801-20211001",
"max_drawdown": 134,
"winrate": 85,
},
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "busd",
"timerange": "20210101-20211001",
"max_drawdown": 740,
"winrate": 82,
},
# Binance - USDT - Apollo11
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210801-20210901",
"max_drawdown": 38,
"winrate": 88,
},
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210901-20211001",
"max_drawdown": 165,
"winrate": 80,
},
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210801-20211001",
"max_drawdown": 165,
"winrate": 84,
},
{
"exchange": "binance",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210101-20211001",
"max_drawdown": 761,
"winrate": 83,
},
# Binance - BUSD - Saturn5
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "busd",
"timerange": "20210801-20210901",
"max_drawdown": 41,
"winrate": 90,
},
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "busd",
"timerange": "20210901-20211001",
"max_drawdown": 224,
"winrate": 76,
},
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "busd",
"timerange": "20210801-20211001",
"max_drawdown": 244,
"winrate": 84,
},
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "busd",
"timerange": "20210101-20211001",
"max_drawdown": 760,
"winrate": 82,
},
# Binance - USDT - Saturn5
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210801-20210901",
"max_drawdown": 56,
"winrate": 88,
},
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210901-20211001",
"max_drawdown": 190,
"winrate": 73,
},
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210801-20211001",
"max_drawdown": 174,
"winrate": 83,
},
{
"exchange": "binance",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210101-20211001",
"max_drawdown": 629,
"winrate": 83,
},
# Kucoin - USDT - Apollo11
{
"exchange": "kucoin",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210801-20210901",
"max_drawdown": 51,
"winrate": 85,
},
{
"exchange": "kucoin",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210901-20211001",
"max_drawdown": 151,
"winrate": 79,
},
{
"exchange": "kucoin",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210801-20211001",
"max_drawdown": 162,
"winrate": 83,
},
{
"exchange": "kucoin",
"strategy": "Apollo11",
"stake_currency": "usdt",
"timerange": "20210101-20211001",
"max_drawdown": 748,
"winrate": 81,
},
# Kucoin - USDT - Saturn5
{
"exchange": "kucoin",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210801-20210901",
"max_drawdown": 64,
"winrate": 90,
},
{
"exchange": "kucoin",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210901-20211001",
"max_drawdown": 182,
"winrate": 76,
},
{
"exchange": "kucoin",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210801-20211001",
"max_drawdown": 162,
"winrate": 85,
},
{
"exchange": "kucoin",
"strategy": "Saturn5",
"stake_currency": "usdt",
"timerange": "20210101-20211001",
"max_drawdown": 734,
"winrate": 83,
},
)
================================================
FILE: tests/backtests/helpers.py
================================================
import json
import logging
import pprint
import shutil
import subprocess
from types import SimpleNamespace
import attr
from tests.backtests.data import EXPECTED_RESULTS_DATA
from tests.conftest import REPO_ROOT
log = logging.getLogger(__name__)
@attr.s(frozen=True)
class ProcessResult:
"""
This class serves the purpose of having a common result class which will hold the
resulting data from a subprocess command.
:keyword int exitcode:
The exitcode returned by the process
:keyword str stdout:
The ``stdout`` returned by the process
:keyword str stderr:
The ``stderr`` returned by the process
:keyword list,tuple cmdline:
The command line used to start the process
.. admonition:: Note
Cast :py:class:`~saltfactories.utils.processes.ProcessResult` to a string to pretty-print it.
"""
exitcode = attr.ib()
stdout = attr.ib()
stderr = attr.ib()
cmdline = attr.ib(default=None, kw_only=True)
@exitcode.validator
def _validate_exitcode(self, _, value):
if not isinstance(value, int):
raise ValueError(f"'exitcode' needs to be an integer, not '{type(value)}'")
def __str__(self):
message = self.__class__.__name__
if self.cmdline:
message += f"\n Command Line: {self.cmdline}"
if self.exitcode is not None:
message += f"\n Exitcode: {self.exitcode}"
if self.stdout or self.stderr:
message += "\n Process Output:"
if self.stdout:
message += f"\n >>>>> STDOUT >>>>>\n{self.stdout}\n <<<<< STDOUT <<<<<"
if self.stderr:
message += f"\n >>>>> STDERR >>>>>\n{self.stderr}\n <<<<< STDERR <<<<<"
return message + "\n"
class Backtest:
def __init__(self, request, stake_currency, strategy, exchange=None, timerange=None):
self.request = request
self.stake_currency = stake_currency
self.strategy = strategy
self.exchange = exchange
self.timerange = timerange
def __call__(
self,
pairlist=None,
max_open_trades=6,
stake_amount="150",
exchange=None,
strategy=None,
stake_currency=None,
):
if exchange is None:
exchange = self.exchange
if exchange is None:
raise RuntimeError(
f"No 'exchange' was passed when instantiating {self.__class__.__name__} or when calling it"
)
if strategy is None:
strategy = self.strategy
if strategy is None:
raise RuntimeError(
f"No 'strategy' was passed when instantiating {self.__class__.__name__} or when calling it"
)
if stake_currency is None:
stake_currency = self.stake_currency
if stake_currency is None:
raise RuntimeError(
f"No 'stake_currency' was passed when instantiating {self.__class__.__name__} or when calling it"
)
tmp_path = self.request.getfixturevalue("tmp_path")
exchange_config = f"user_data/data/{exchange}-{stake_currency}-static.json"
json_results_file = tmp_path / "backtest-results.json"
cmdline = [
"freqtrade",
"backtesting",
"--timeframe=15m",
"--timeframe-detail=5m",
"--enable-protections",
"--user-data=user_data",
f"--strategy-list={strategy}",
f"--timerange={self.timerange}",
f"--max-open-trades={max_open_trades}",
f"--stake-amount={stake_amount}",
"--config=user_data/data/pairlists.json",
f"--config=user_data/data/pairlists-{stake_currency}.json",
]
if pairlist is None:
cmdline.append(f"--config={exchange_config}")
else:
pairlist_config = {"exchange": {"name": exchange, "pair_whitelist": pairlist}}
pairlist_config_file = tmp_path / "test-pairlist.json"
pairlist_config_file.write(json.dumps(pairlist_config))
cmdline.append(f"--config={pairlist_config_file}")
cmdline.append(f"--export-filename={json_results_file}")
log.info("Running cmdline '%s' on '%s'", " ".join(cmdline), REPO_ROOT)
proc = subprocess.run(cmdline, check=False, shell=False, cwd=REPO_ROOT, text=True, capture_output=True)
ret = ProcessResult(
exitcode=proc.returncode,
stdout=proc.stdout.strip(),
stderr=proc.stderr.strip(),
cmdline=cmdline,
)
if ret.exitcode != 0:
log.info("Command Result:\n%s", ret)
else:
log.debug("Command Result:\n%s", ret)
assert ret.exitcode == 0
generated_results_file = list(tmp_path.rglob("backtest-results-*.json"))[0]
generated_json_ci_results_artifact_path = None
artifacts_path = self.request.config.option.artifacts_path
if artifacts_path:
artifacts_path = artifacts_path / exchange / stake_currency / strategy
artifacts_path.mkdir(parents=True, exist_ok=True)
if self.request.config.option.artifacts_path:
generated_json_results_artifact_path = artifacts_path / generated_results_file.name
shutil.copyfile(generated_results_file, generated_json_results_artifact_path)
generated_json_ci_results_artifact_path = artifacts_path / f"ci-results-{self.timerange}.json"
generated_txt_results_artifact_path = artifacts_path / f"backtest-output-{self.timerange}.txt"
generated_txt_results_artifact_path.write_text(ret.stdout.strip())
results_data = json.loads(generated_results_file.read_text())
ret = BacktestResults(
strategy=strategy,
stdout=ret.stdout.strip(),
stderr=ret.stderr.strip(),
raw_data=results_data,
)
if generated_json_ci_results_artifact_path:
generated_json_ci_results_artifact_path.write_text(json.dumps({self.timerange: ret._stats_pct}))
ret.log_info()
return ret
@attr.s(frozen=True)
class BacktestResults:
strategy: str = attr.ib()
stdout: str = attr.ib(repr=False)
stderr: str = attr.ib(repr=False)
raw_data: dict = attr.ib(repr=False)
_results: dict = attr.ib(init=False, repr=False)
_stats: dict = attr.ib(init=False, repr=False)
results: SimpleNamespace = attr.ib(init=False, repr=False)
full_stats: SimpleNamespace = attr.ib(init=False, repr=False)
_stats_pct: dict = attr.ib(init=False, repr=False)
stats_pct: SimpleNamespace = attr.ib(init=False, repr=True)
@_results.default
def _set__results(self):
return self.raw_data["strategy"][self.strategy]
@_stats.default
def _set_stats(self):
return self.raw_data["strategy_comparison"][0]
@results.default
def _set_results(self):
return json.loads(json.dumps(self._results), object_hook=lambda d: SimpleNamespace(**d))
@full_stats.default
def _set_full_stats(self):
return json.loads(json.dumps(self._stats), object_hook=lambda d: SimpleNamespace(**d))
@_stats_pct.default
def _set__stats_pct(self):
tags = {}
for trade in self.results.trades:
tag = f"{trade.buy_tag} wins / losses / force-sell"
profit = trade.profit_abs
force_sell = trade.sell_reason == "force_sell"
if tag not in tags:
tags[tag] = {"wins": 0, "losses": 0, "force_sell": 0}
if force_sell:
tags[tag]["force_sell"] += 1
elif profit > 0:
tags[tag]["wins"] += 1
else:
tags[tag]["losses"] += 1
for tag, data in tags.items():
tags[tag] = f"{data['wins']} / {data['losses']} / {data['force_sell']}"
return {
"duration_avg": self.full_stats.duration_avg,
"profit_sum_pct": self.full_stats.profit_sum_pct,
"profit_mean_pct": self.full_stats.profit_mean_pct,
"profit_total_pct": self.full_stats.profit_total_pct,
"max_drawdown": self.results.max_drawdown * 100,
"trades": self.full_stats.trades,
"winrate": round(self.full_stats.wins * 100.0 / self.full_stats.trades, 2),
**tags,
}
@stats_pct.default
def _set_stats_pct(self):
return json.loads(json.dumps(self._stats_pct), object_hook=lambda d: SimpleNamespace(**d))
def log_info(self):
data = {
"results": self._results,
"full_stats": self._stats,
"stats_pct": self._stats_pct,
}
log.debug("Backtest results:\n%s", pprint.pformat(data))
log.info(
"Backtests Stats PCTs(More info at the DEBUG log level): %s",
pprint.pformat(self._stats_pct),
)
@attr.s(frozen=True)
class ExpectedResult:
exchange = attr.ib()
strategy = attr.ib()
stake_currency = attr.ib()
timerange = attr.ib()
winrate = attr.ib()
max_drawdown = attr.ib()
@attr.s(frozen=True)
class ExpectedResults:
results = attr.ib()
@results.default
def _load_results(self):
results = []
for entry in EXPECTED_RESULTS_DATA:
results.append(ExpectedResult(**entry))
return tuple(results)
def timeranges(self):
entries = []
for result in self.results:
if result.timerange in entries:
continue
entries.append(result.timerange)
return entries
================================================
FILE: tests/backtests/test_winrate_and_drawdown.py
================================================
# pylint: disable=redefined-outer-name
import pytest
from tests.backtests.helpers import Backtest
from tests.backtests.helpers import ExpectedResults
from tests.conftest import REPO_ROOT
RESULTS = ExpectedResults()
@pytest.fixture(scope="session")
def stake_currency(request):
return request.config.getoption("--stake-currency")
@pytest.fixture(scope="session")
def strategy(request):
return request.config.getoption("--strategy")
@pytest.fixture(scope="session")
def exchange(request):
return request.config.getoption("--exchange")
@pytest.fixture(params=RESULTS.timeranges())
def timerange(request):
return request.param
@pytest.fixture
def expected_result(exchange, strategy, stake_currency, timerange):
for entry in RESULTS.results:
if entry.exchange != exchange:
continue
if entry.strategy != strategy:
continue
if entry.stake_currency != stake_currency:
continue
if entry.timerange != timerange:
continue
return entry
pytest.fail(f"Could not find expected_results for {exchange} using {stake_currency} for {strategy} and {timerange}")
@pytest.fixture
def backtest(request, stake_currency, strategy, timerange, exchange, expected_result):
exchange_data_dir = REPO_ROOT / "user_data" / "data" / expected_result.exchange
if not exchange_data_dir.is_dir():
pytest.fail(
f"There's no exchange data for {expected_result.exchange}. Make sure the repository submodule "
"is init/update. Check the repository README.md for more information."
)
if not list(exchange_data_dir.rglob("*.json.gz")):
pytest.fail(
f"There's no exchange data for {expected_result.exchange}. Make sure the repository submodule "
"is init/update. Check the repository README.md for more information."
)
instance = Backtest(
request,
stake_currency=stake_currency,
strategy=strategy,
timerange=timerange,
exchange=exchange,
)
ret = instance()
try:
yield ret
finally:
# Let's now make sure the numbers don't deviate much from what we expect
# so that we always keep these tight
errors = []
if ret.stats_pct.winrate - 1 > expected_result.winrate:
errors.append("winrate")
if ret.stats_pct.max_drawdown + 1 < expected_result.max_drawdown:
errors.append("max_drawdown")
if errors:
errmsg = (
f"Please update the {exchange}({stake_currency}) expected "
f"results for the {strategy} strategy during {timerange}."
)
if "max_drawdown" in errors:
old = expected_result.max_drawdown
new = int(ret.stats_pct.max_drawdown) + 1
errmsg += f" Set `max_drawdown` from {old} to {new}."
if "winrate" in errors:
old = expected_result.winrate
new = int(ret.stats_pct.winrate)
errmsg += f" Set `winrate` from {old} to {new}."
pytest.fail(errmsg)
def test_expected_values(backtest, expected_result, subtests, exchange, stake_currency, strategy, timerange):
errmsg = (
f"If expected, please update {exchange}({stake_currency}) expected "
f"results for the {strategy} strategy during {timerange}."
)
with subtests.test("Winrate"):
winrate_errmsg = f"Winrate results got worse. {errmsg} Set `winrate` to {int(backtest.stats_pct.winrate)}"
assert backtest.stats_pct.winrate >= expected_result.winrate, winrate_errmsg
with subtests.test("Max Drawdown"):
max_drawdown_errmsg = (
f"Max Drawdown results got worse. {errmsg} "
f"Set `max_drawdown` to {int(backtest.stats_pct.max_drawdown + 1)}"
)
assert backtest.stats_pct.max_drawdown <= expected_result.max_drawdown, max_drawdown_errmsg
================================================
FILE: tests/ci-requirements.txt
================================================
pygithub
================================================
FILE: tests/conftest.py
================================================
import sys
from pathlib import Path
# Make sure we can import the strategy module directly
REPO_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(REPO_ROOT))
def pytest_addoption(parser):
parser.addoption("--artifacts-path", default=None, help="Path to write generated test artifacts")
parser.addoption("--stake-currency", default="busd", help="Stake currency", choices=["usdt", "busd"])
parser.addoption("--strategy", default="Apollo11", help="Strategy to test", choices=["Apollo11", "Saturn5"])
parser.addoption("--exchange", default="binance", help="Exchange to test", choices=["binance", "kucoin"])
def pytest_configure(config):
if config.option.artifacts_path:
config.option.artifacts_path = Path(config.option.artifacts_path).resolve()
if not config.option.artifacts_path.is_dir():
config.option.artifacts_path.mkdir()
================================================
FILE: tests/requirements.txt
================================================
freqtrade
pandas-ta
pytest
pytest-mock
pytest-subtests
gitextract_9e686ag2/
├── .flake8
├── .github/
│ └── workflows/
│ ├── ci.yml
│ └── scripts/
│ ├── comment-ci-results.py
│ └── download-previous-artifacts.py
├── .gitmodules
├── .mypy.ini
├── .pre-commit-config.yaml
├── .pylintrc
├── Apollo11.py
├── README.md
├── Saturn5.py
├── alternative_configs/
│ ├── blacklisted_coins.json
│ ├── dynamic_coin_list.json
│ └── whitelist_busd.json
├── config-binance.json
├── docker/
│ └── Dockerfile.custom
├── docker-compose.yml
└── tests/
├── __init__.py
├── backtests/
│ ├── __init__.py
│ ├── data.py
│ ├── helpers.py
│ └── test_winrate_and_drawdown.py
├── ci-requirements.txt
├── conftest.py
└── requirements.txt
SYMBOL INDEX (49 symbols across 7 files)
FILE: .github/workflows/scripts/comment-ci-results.py
function delete_previous_comments (line 13) | def delete_previous_comments(commit, created_comment_ids, exchanges):
function build_row_line (line 32) | def build_row_line(*, current_value, previous_value, higher_is_better=Tr...
function get_value_for_report (line 61) | def get_value_for_report(*, results_data, exchange, currency, strategy, ...
function comment_results (line 68) | def comment_results(options, results_data):
function main (line 337) | def main():
FILE: .github/workflows/scripts/download-previous-artifacts.py
function get_artifact_url (line 14) | def get_artifact_url(workflow_run, name):
function download_previous_artifacts (line 21) | def download_previous_artifacts(repo, options):
function get_previous_releases (line 82) | def get_previous_releases(repo, latest_n_releases):
function main (line 91) | def main():
FILE: Apollo11.py
function to_minutes (line 12) | def to_minutes(**timdelta_kwargs):
class Apollo11 (line 16) | class Apollo11(IStrategy):
method protections (line 69) | def protections(self):
method populate_indicators (line 110) | def populate_indicators(self, dataframe: DataFrame, metadata: dict) ->...
method populate_buy_trend (line 156) | def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> ...
method populate_sell_trend (line 192) | def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) ->...
method custom_stoploss (line 197) | def custom_stoploss(
FILE: Saturn5.py
function to_minutes (line 10) | def to_minutes(**timdelta_kwargs):
class Saturn5 (line 14) | class Saturn5(IStrategy):
method protections (line 67) | def protections(self):
method populate_indicators (line 108) | def populate_indicators(self, dataframe: DataFrame, metadata: dict) ->...
method populate_buy_trend (line 154) | def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> ...
method populate_sell_trend (line 190) | def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) ->...
FILE: tests/backtests/helpers.py
class ProcessResult (line 17) | class ProcessResult:
method _validate_exitcode (line 39) | def _validate_exitcode(self, _, value):
method __str__ (line 43) | def __str__(self):
class Backtest (line 58) | class Backtest:
method __init__ (line 59) | def __init__(self, request, stake_currency, strategy, exchange=None, t...
method __call__ (line 66) | def __call__(
class BacktestResults (line 160) | class BacktestResults:
method _set__results (line 173) | def _set__results(self):
method _set_stats (line 177) | def _set_stats(self):
method _set_results (line 181) | def _set_results(self):
method _set_full_stats (line 185) | def _set_full_stats(self):
method _set__stats_pct (line 189) | def _set__stats_pct(self):
method _set_stats_pct (line 219) | def _set_stats_pct(self):
method log_info (line 222) | def log_info(self):
class ExpectedResult (line 236) | class ExpectedResult:
class ExpectedResults (line 246) | class ExpectedResults:
method _load_results (line 250) | def _load_results(self):
method timeranges (line 256) | def timeranges(self):
FILE: tests/backtests/test_winrate_and_drawdown.py
function stake_currency (line 12) | def stake_currency(request):
function strategy (line 17) | def strategy(request):
function exchange (line 22) | def exchange(request):
function timerange (line 27) | def timerange(request):
function expected_result (line 32) | def expected_result(exchange, strategy, stake_currency, timerange):
function backtest (line 47) | def backtest(request, stake_currency, strategy, timerange, exchange, exp...
function test_expected_values (line 93) | def test_expected_values(backtest, expected_result, subtests, exchange, ...
FILE: tests/conftest.py
function pytest_addoption (line 9) | def pytest_addoption(parser):
function pytest_configure (line 16) | def pytest_configure(config):
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (106K chars).
[
{
"path": ".flake8",
"chars": 124,
"preview": "[flake8]\n#ignore =\nmax-line-length = 120\nmax-complexity = 12\nexclude =\n .git,\n __pycache__,\n .eggs,\n user_da"
},
{
"path": ".github/workflows/ci.yml",
"chars": 5708,
"preview": "name: CI\n\non: [push, pull_request]\n\njobs:\n Pre-Commit:\n runs-on: ubuntu-20.04\n steps:\n\n - uses: actions/checko"
},
{
"path": ".github/workflows/scripts/comment-ci-results.py",
"chars": 20008,
"preview": "# pylint: disable=invalid-name\nimport argparse\nimport json\nimport os\nimport pathlib\nimport pprint\nimport sys\n\nimport git"
},
{
"path": ".github/workflows/scripts/download-previous-artifacts.py",
"chars": 5191,
"preview": "# pylint: disable=invalid-name,protected-access\nimport argparse\nimport json\nimport os\nimport pathlib\nimport pprint\nimpor"
},
{
"path": ".gitmodules",
"chars": 121,
"preview": "[submodule \"user_data/data\"]\n\tpath = user_data/data\n\turl = https://github.com/shanejones/goddard-data.git\n\tbranch = main"
},
{
"path": ".mypy.ini",
"chars": 74,
"preview": "[mypy]\nignore_missing_imports = True\n\n[mypy-tests.*]\nignore_errors = True\n"
},
{
"path": ".pre-commit-config.yaml",
"chars": 2131,
"preview": "---\nminimum_pre_commit_version: 1.15.2\nrepos:\n - repo: https://github.com/pre-commit/pre-commit-hooks\n rev: v4.0.1\n "
},
{
"path": ".pylintrc",
"chars": 18005,
"preview": "[MASTER]\n\n# A comma-separated list of package or module names from where C extensions may\n# be loaded. Extensions are lo"
},
{
"path": "Apollo11.py",
"chars": 8834,
"preview": "from datetime import datetime\nfrom datetime import timedelta\nfrom functools import reduce\n\nimport freqtrade.vendor.qtpyl"
},
{
"path": "README.md",
"chars": 4948,
"preview": "# Goddard\n\n**A collection of small, simple strategies for Freqtrade.** Simply add the strategy you choose in your strate"
},
{
"path": "Saturn5.py",
"chars": 7878,
"preview": "from datetime import timedelta\nfrom functools import reduce\n\nimport freqtrade.vendor.qtpylib.indicators as qtpylib\nimpor"
},
{
"path": "alternative_configs/blacklisted_coins.json",
"chars": 756,
"preview": "// We have compiled a list of coins that we feel should be generally blacklisted\n// Replace the section below in your ma"
},
{
"path": "alternative_configs/dynamic_coin_list.json",
"chars": 1066,
"preview": "// Replace the sections below in your main config\n// Caveat: This has only been tested with BUSD on Binance so far\n\n{\n "
},
{
"path": "alternative_configs/whitelist_busd.json",
"chars": 1842,
"preview": "{\n \"pair_whitelist\": [\n \"1INCH/BUSD\",\n \"AAVE/BUSD\",\n \"AERGO/BUSD\",\n \"ALGO/BUSD\",\n \"ALICE/BUSD\",\n \"ALP"
},
{
"path": "config-binance.json",
"chars": 1835,
"preview": "{\n \"max_open_trades\": 5,\n \"stake_currency\": \"BUSD\",\n \"stake_amount\": \"unlimited\",\n \"tradable_balance_ratio\": 0.99,\n "
},
{
"path": "docker/Dockerfile.custom",
"chars": 186,
"preview": "FROM freqtradeorg/freqtrade:develop\n\nCOPY --chown=1000:1000 tests/requirements.txt /freqtrade\n\nRUN pip install --user -"
},
{
"path": "docker-compose.yml",
"chars": 1144,
"preview": "---\nversion: '3'\nservices:\n tests:\n build:\n context: .\n dockerfile: \"./docker/Dockerfile.custom\"\n con"
},
{
"path": "tests/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/backtests/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/backtests/data.py",
"chars": 5085,
"preview": "EXPECTED_RESULTS_DATA = (\n # Binance - BUSD - Apollo11\n {\n \"exchange\": \"binance\",\n \"strategy\": \"Apol"
},
{
"path": "tests/backtests/helpers.py",
"chars": 9619,
"preview": "import json\nimport logging\nimport pprint\nimport shutil\nimport subprocess\nfrom types import SimpleNamespace\n\nimport attr\n"
},
{
"path": "tests/backtests/test_winrate_and_drawdown.py",
"chars": 3972,
"preview": "# pylint: disable=redefined-outer-name\nimport pytest\n\nfrom tests.backtests.helpers import Backtest\nfrom tests.backtests."
},
{
"path": "tests/ci-requirements.txt",
"chars": 9,
"preview": "pygithub\n"
},
{
"path": "tests/conftest.py",
"chars": 887,
"preview": "import sys\nfrom pathlib import Path\n\n# Make sure we can import the strategy module directly\nREPO_ROOT = Path(__file__).p"
},
{
"path": "tests/requirements.txt",
"chars": 55,
"preview": "freqtrade\npandas-ta\npytest\npytest-mock\npytest-subtests\n"
}
]
About this extraction
This page contains the full source code of the shanejones/goddard GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (97.1 KB), approximately 23.7k tokens, and a symbol index with 49 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.