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