[
  {
    "path": ".do/deploy.template.yaml",
    "content": "spec:\n  name: binance-trade-bot\n  workers:\n  - environment_slug: python\n    git:\n      branch: master\n      repo_clone_url: https://github.com/coinbookbrasil/binance-trade-bot.git\n    envs:\n    - key: API_KEY\n      scope: BUILD_TIME\n      value: \"API KEY BINANCE\"\n    - key: API_SECRET_KEY\n      scope: BUILD_TIME\n      value: \"API_SECRET_KEY\"\n    - key: CURRENT_COIN_SYMBOL\n      scope: BUILD_TIME\n      value: \"XMR\"\n    - key: BRIDGE_SYMBOL\n      scope: BUILD_TIME\n      value: \"USDT\"\n    - key: TLD\n      scope: BUILD_TIME\n      value: \"com\"\n    - key: SCOUT_MULTIPLIER\n      scope: BUILD_TIME\n      value: \"1\"\n    - key: HOURS_TO_KEEP_SCOUTING_HISTORY\n      scope: BUILD_TIME\n      value: \"1\"\n    - key: STRATEGY\n      scope: BUILD_TIME\n      value: \"default\"\n    - key: BUY_TIMEOUT\n      scope: BUILD_TIME\n      value: \"0\"\n    - key: SELL_TIMEOUT\n      scope: BUILD_TIME\n      value: \"0\"\n    - key: SUPPORTED_COIN_LIST\n      scope: BUILD_TIME\n      value: \"ADA ATOM BAT BTT DASH DOGE EOS ETC ICX IOTA NEO OMG ONT QTUM TRX VET XLM XMR\"\n    name: binance-trade-bot\n"
  },
  {
    "path": ".github/workflows/cicd.yaml",
    "content": "name: binance-trade-bot\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - \"*\"\n\njobs:\n  Lint:\n    runs-on: ubuntu-20.04\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Python\n      uses: actions/setup-python@v2\n      with:\n        python-version: 3.7\n    - id: changed-files\n      name: Get Changed Files\n      uses: dorny/paths-filter@v2\n      with:\n        token: ${{ github.token }}\n        list-files: shell\n        filters: |\n          repo:\n            - added|modified:\n              - '**'\n    - name: Set Cache Key\n      run: echo \"PY=$(python --version --version | sha256sum | cut -d' ' -f1)\" >> $GITHUB_ENV\n    - uses: actions/cache@v2\n      with:\n        path: ~/.cache/pre-commit\n        key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }}\n    - name: Check ALL Files On Branch\n      uses: pre-commit/action@v2.0.0\n      if: github.event_name != 'pull_request'\n    - name: Check Changed Files On PR\n      uses: pre-commit/action@v2.0.0\n      if: github.event_name == 'pull_request'\n      with:\n        extra_args: --files ${{ steps.changed-files.outputs.repo_files }}\n\n  Docker:\n    runs-on: ubuntu-latest\n    needs: Lint\n    steps:\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v1\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v1\n      - name: Login to DockerHub\n        if: github.event_name == 'push'\n        uses: docker/login-action@v1\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n      - name: Build and push\n        id: docker_build\n        uses: docker/build-push-action@v2\n        with:\n          platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7\n          push: ${{ github.event_name == 'push' }}\n          tags: ${{ github.repository }}:latest\n      - name: Image digest\n        run: echo ${{ steps.docker_build.outputs.digest }}\n"
  },
  {
    "path": ".gitignore",
    "content": "*.log\n.current_coin\n.current_coin_table\n*.pyc\n__pycache__\nnohup.out\nuser.cfg\n.idea/\n.vscode/\n.replit\nvenv/\ncrypto_trading.db\napprise.yml\n.DS_Store\n.bot/"
  },
  {
    "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.1.0\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- repo: local\n  hooks:\n  - id: sort-supported-coin-list\n    name: Sort Supported Coin List\n    entry: .pre-commit-hooks/sort-coins-file.py\n    language: python\n    files: ^supported_coin_list$\n\n- repo: https://github.com/asottile/pyupgrade\n  rev: v2.29.1\n  hooks:\n  - id: pyupgrade\n    name: Rewrite Code to be Py3.6+\n    args: [--py36-plus]\n\n- repo: https://github.com/pycqa/isort\n  rev: 5.11.5\n  hooks:\n  - id: isort\n    args: [--profile, black, --line-length, '120']\n\n- repo: https://github.com/psf/black\n  rev: 23.3.0\n  hooks:\n  - id: black\n    args: [-l, '120']\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: ^docs/.*\\.rst\n    additional_dependencies: [black==20.8b1]\n\n- repo: https://github.com/s0undt3ch/pre-commit-populate-pylint-requirements\n  rev: aed8c6a\n  hooks:\n  - id: populate-pylint-requirements\n    files: ^(dev-)?requirements\\.txt$\n    args: [requirements.txt, dev-requirements.txt]\n\n- repo: https://github.com/pre-commit/mirrors-pylint\n  rev: v3.0.0a5\n  hooks:\n  - id: pylint\n    name: PyLint\n    args: [--output-format=parseable, --rcfile=.pylintrc]\n    additional_dependencies:\n    - Flask==2.1.1\n    - apprise==0.9.5.1\n    - cachetools==4.2.2\n    - eventlet==0.30.2\n    - flask-cors==3.0.10\n    - flask-socketio==5.0.1\n    - gunicorn==20.1.0\n    - itsdangerous==2.0.1\n    - pylint-sqlalchemy\n    - python-binance==1.0.12\n    - python-socketio[client]==5.2.1\n    - schedule==1.1.0\n    - sqlalchemy==1.4.15\n    - sqlitedict==1.7.0\n    - unicorn-binance-websocket-api==1.34.2\n    - unicorn-fy==0.11.0\n"
  },
  {
    "path": ".pre-commit-hooks/sort-coins-file.py",
    "content": "#!/usr/bin/env python\n# pylint: skip-file\nimport pathlib\n\nREPO_ROOT = pathlib.Path(__name__).resolve().parent\nSUPPORTED_COIN_LIST = REPO_ROOT / \"supported_coin_list\"\n\n\ndef sort():\n    in_contents = SUPPORTED_COIN_LIST.read_text()\n    out_contents = \"\"\n    out_contents += \"\\n\".join(sorted(line.upper() for line in in_contents.splitlines()))\n    out_contents += \"\\n\"\n    if in_contents != out_contents:\n        SUPPORTED_COIN_LIST.write_text(out_contents)\n\n\nif __name__ == \"__main__\":\n    sort()\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-whitelist=\n\n# Specify a score threshold to be exceeded before program exits with error.\nfail-under=6.0\n\n# Add files or directories to the blacklist. They should be base names, not\n# paths.\nignore=CVS\n\n# Add files or directories matching the regex patterns to the blacklist. The\n# regex 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=pylint_sqlalchemy\n\n# Pickle collected data for later comparisons.\npersistent=yes\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=print-statement,\n        parameter-unpacking,\n        unpacking-in-except,\n        old-raise-syntax,\n        backtick,\n        long-suffix,\n        old-ne-operator,\n        old-octal-literal,\n        import-star-module-level,\n        non-ascii-bytes-literal,\n        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        apply-builtin,\n        basestring-builtin,\n        buffer-builtin,\n        cmp-builtin,\n        coerce-builtin,\n        execfile-builtin,\n        file-builtin,\n        long-builtin,\n        raw_input-builtin,\n        reduce-builtin,\n        standarderror-builtin,\n        unicode-builtin,\n        xrange-builtin,\n        coerce-method,\n        delslice-method,\n        getslice-method,\n        setslice-method,\n        no-absolute-import,\n        old-division,\n        dict-iter-method,\n        dict-view-method,\n        next-method-called,\n        metaclass-assignment,\n        indexing-exception,\n        raising-string,\n        reload-builtin,\n        oct-method,\n        hex-method,\n        nonzero-method,\n        cmp-method,\n        input-builtin,\n        round-builtin,\n        intern-builtin,\n        unichr-builtin,\n        map-builtin-not-iterating,\n        zip-builtin-not-iterating,\n        range-builtin-not-iterating,\n        filter-builtin-not-iterating,\n        using-cmp-argument,\n        eq-without-hash,\n        div-method,\n        idiv-method,\n        rdiv-method,\n        exception-message-attribute,\n        invalid-str-codec,\n        sys-max-int,\n        bad-python3-import,\n        deprecated-string-function,\n        deprecated-str-translate-call,\n        deprecated-itertools-function,\n        deprecated-types-field,\n        next-method-defined,\n        dict-items-not-iterating,\n        dict-keys-not-iterating,\n        dict-values-not-iterating,\n        deprecated-operator-function,\n        deprecated-urllib-function,\n        xreadlines-attribute,\n        deprecated-sys-function,\n        exception-escape,\n        comprehension-escape,\n        missing-module-docstring,\n        missing-class-docstring,\n        missing-function-docstring,\n        bad-continuation,\n        invalid-name,\n        duplicate-code\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=parseable\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\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 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           cv\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 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: en (aspell), en_AG\n# (hunspell), en_AU (hunspell), en_BS (hunspell), en_BW (hunspell), en_BZ\n# (hunspell), en_CA (hunspell), en_DK (hunspell), en_GB (hunspell), en_GH\n# (hunspell), en_HK (hunspell), en_IE (hunspell), en_IN (hunspell), en_JM\n# (hunspell), en_NA (hunspell), en_NG (hunspell), en_NZ (hunspell), en_SG\n# (hunspell), en_TT (hunspell), en_US (hunspell), en_ZA (hunspell), en_ZW\n# (hunspell), he (hspell), pt_BR (aspell), pt_PT (aspell).\nspelling-dict=\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,twisted.internet.reactor\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=\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# Ignore comments when computing similarities.\nignore-comments=yes\n\n# Ignore docstrings when computing similarities.\nignore-docstrings=yes\n\n# Ignore imports when computing similarities.\nignore-imports=no\n\n# Minimum lines number of a similarity.\nmin-similarity-lines=4\n\n\n[CLASSES]\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# Maximum number of arguments for function / method.\nmax-args=8\n\n# Maximum number of attributes for a class (see R0902).\nmax-attributes=12\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=optparse,tkinter.tix\n\n# Create a graph of external dependencies in the given file (report RP0402 must\n# not be disabled).\next-import-graph=\n\n# Create a graph of every (i.e. internal and external) dependencies in the\n# given file (report RP0402 must not be disabled).\nimport-graph=\n\n# Create a graph of internal dependencies in the given file (report RP0402 must\n# 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": ".user.cfg.example",
    "content": "[binance_user_config]\napi_key=vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\napi_secret_key=NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j\n\n# Starting coin, leave empty when it's the bridge.\n# It has to be in the supported_coin_list\ncurrent_coin=\n\n\n# Weather to use the testnet or not, default is False\ntestnet=false\n\n#Bridge coin of your choice\nbridge=USDT\n\n#com or us, depending on region\ntld=com\n\n#Defines how long the scout history is stored\nhourToKeepScoutHistory=1\n\n#Defines to use either scout_margin or scout_multiplier\nuse_margin=no\n\n# It's recommended to use something between 3-7 as scout_multiplier\nscout_multiplier=5\n\n#It's recommended to use something between 0.3 and 1.2 as scout_margin\nscout_margin=0.8\n\n# Controls how many seconds bot should wait between analysis of current prices\nscout_sleep_time=1\n\n# Pre-configured strategies are default and multiple_coins\nstrategy=default\n\n# Controls how many minutes to wait before cancelling a limit order (buy/sell) and returning to \"scout\" mode.\n# 0 means that the order will never be cancelled prematurely.\nbuy_timeout=20\nsell_timeout=20\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM --platform=$BUILDPLATFORM python:3.8 as builder\n\nWORKDIR /install\n\nRUN apt-get update && apt-get install -y rustc\n\nCOPY requirements.txt /requirements.txt\nRUN pip install --prefix=/install -r /requirements.txt\n\nFROM python:3.13.2-slim\n\nWORKDIR /app\n\nCOPY --from=builder /install /usr/local\nCOPY . .\n\nCMD [\"python\", \"-m\", \"binance_trade_bot\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Procfile",
    "content": "web: python -m binance_trade_bot\n"
  },
  {
    "path": "README.md",
    "content": "# Binance Trade Bot\n> An automated cryptocurrency trading bot for Binance\n\n## Author\nCreated by **Eden Gaon**\n\n[![Twitter Follow](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Follow%20%400xedeng)](https://twitter.com/shapeden)\n[![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=flat&logo=linkedin)](https://www.linkedin.com/in/eden-gaon-6956a219/)\n\n## Project Status\n[![GitHub Status](https://img.shields.io/github/workflow/status/edeng23/binance-trade-bot/binance-trade-bot?label=build)](https://github.com/edeng23/binance-trade-bot/actions)\n[![Docker Pulls](https://img.shields.io/docker/pulls/edeng23/binance-trade-bot)](https://hub.docker.com/r/edeng23/binance-trade-bot)\n\n## Quick Deploy\n[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/edeng23/binance-trade-bot)\n[![Deploy to DigitalOcean](https://mp-assets1.sfo2.digitaloceanspaces.com/deploy-to-do/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/coinbookbrasil/binance-trade-bot/tree/master&refcode=a076ff7a9a6a)\n\n## Community\nJoin our growing community on Telegram to discuss strategies, get help, or just chat!\n\n[![Telegram Chat](https://patrolavia.github.io/telegram-badge/chat.png)](https://t.me/binancetradebotchat)\n\n#### Community Telegram Chat\nhttps://t.me/binancetradebotchat\n\n## Why?\n\nThis project was inspired by the observation that all cryptocurrencies pretty much behave in the same way. When one spikes, they all spike, and when one takes a dive, they all do. _Pretty much_. Moreover, all coins follow Bitcoin's lead; the difference is their phase offset.\n\nSo, if coins are basically oscillating with respect to each other, it seems smart to trade the rising coin for the falling coin, and then trade back when the ratio is reversed.\n\n## How?\n\nThe trading is done in the Binance market platform, which of course, does not have markets for every altcoin pair. The workaround for this is to use a bridge currency that will complement missing pairs. The default bridge currency is Tether (USDT), which is stable by design and compatible with nearly every coin on the platform.\n\n<p align=\"center\">\n  Coin A → USDT → Coin B\n</p>\n\nThe way the bot takes advantage of the observed behaviour is to always downgrade from the \"strong\" coin to the \"weak\" coin, under the assumption that at some point the tables will turn. It will then return to the original coin, ultimately holding more of it than it did originally. This is done while taking into consideration the trading fees.\n\n<div align=\"center\">\n  <p><b>Coin A</b> → USDT → Coin B</p>\n  <p>Coin B → USDT → Coin C</p>\n  <p>...</p>\n  <p>Coin C → USDT → <b>Coin A</b></p>\n</div>\n\nThe bot jumps between a configured set of coins on the condition that it does not return to a coin unless it is profitable in respect to the amount held last. This means that we will never end up having less of a certain coin. The risk is that one of the coins may freefall relative to the others all of a sudden, attracting our reverse greedy algorithm.\n\n## Binance Setup\n\n-   Create a [Binance account](https://accounts.binance.com/register?ref=PGDFCE46) (Includes my referral link, I'll be super grateful if you use it).\n-   Enable Two-factor Authentication.\n-   Create a new API key.\n-   Get a cryptocurrency. If its symbol is not in the default list, add it.\n\n## Tool Setup\n\n### Install Python dependencies\n\nRun the following line in the terminal: `pip install -r requirements.txt`.\n\n### Create user configuration\n\nCreate a .cfg file named `user.cfg` based off `.user.cfg.example`, then add your API keys and current coin.\n\n**The configuration file consists of the following fields:**\n\n-   **api_key** - Binance API key generated in the Binance account setup stage.\n-   **api_secret_key** - Binance secret key generated in the Binance account setup stage.\n-   **testnet** - Default is false, whether to use the testnet or not\n-   **current_coin** - This is your starting coin of choice. This should be one of the coins from your supported coin list. If you want to start from your bridge currency, leave this field empty - the bot will select a random coin from your supported coin list and buy it.\n-   **bridge** - Your bridge currency of choice. Notice that different bridges will allow different sets of supported coins. For example, there may be a Binance particular-coin/USDT pair but no particular-coin/BUSD pair.\n-   **tld** - 'com' or 'us', depending on your region. Default is 'com'.\n-   **hourToKeepScoutHistory** - Controls how many hours of scouting values are kept in the database. After the amount of time specified has passed, the information will be deleted.\n-   **scout_sleep_time** - Controls how many seconds are waited between each scout.\n-   **use_margin** - 'yes' to use scout_margin. 'no' to use scout_multiplier.\n-   **scout_multiplier** - Controls the value by which the difference between the current state of coin ratios and previous state of ratios is multiplied. For bigger values, the bot will wait for bigger margins to arrive before making a trade.\n-   **scout_margin** - Minimum percentage coin gain per trade. 0.8 translates to a scout multiplier of 5 at 0.1% fee.\n-   **strategy** - The trading strategy to use. See [`binance_trade_bot/strategies`](binance_trade_bot/strategies/README.md) for more information\n-   **buy_timeout/sell_timeout** - Controls how many minutes to wait before cancelling a limit order (buy/sell) and returning to \"scout\" mode. 0 means that the order will never be cancelled prematurely.\n-   **scout_sleep_time** - Controls how many seconds bot should wait between analysis of current prices. Since the bot now operates on websockets this value should be set to something low (like 1), the reasons to set it above 1 are when you observe high CPU usage by bot or you got api errors about requests weight limit.\n\n#### Environment Variables\n\nAll of the options provided in `user.cfg` can also be configured using environment variables.\n\n```\nCURRENT_COIN_SYMBOL:\nSUPPORTED_COIN_LIST: \"XLM TRX ICX EOS IOTA ONT QTUM ETC ADA XMR DASH NEO ATOM DOGE VET BAT OMG BTT\"\nBRIDGE_SYMBOL: USDT\nAPI_KEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\nAPI_SECRET_KEY: NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j\nSCOUT_MULTIPLIER: 5\nSCOUT_SLEEP_TIME: 1\nTLD: com\nSTRATEGY: default\nBUY_TIMEOUT: 0\nSELL_TIMEOUT: 0\n```\n\n### Paying Fees with BNB\nYou can [use BNB to pay for any fees on the Binance platform](https://www.binance.com/en/support/faq/115000583311-Using-BNB-to-Pay-for-Fees), which will reduce all fees by 25%. In order to support this benefit, the bot will always perform the following operations:\n-   Automatically detect that you have BNB fee payment enabled.\n-   Make sure that you have enough BNB in your account to pay the fee of the inspected trade.\n-   Take into consideration the discount when calculating the trade threshold.\n\n### Notifications with Apprise\n\nApprise allows the bot to send notifications to all of the most popular notification services available such as: Telegram, Discord, Slack, Amazon SNS, Gotify, etc.\n\nTo set this up you need to create a apprise.yml file in the config directory.\n\nThere is an example version of this file to get you started.\n\nIf you are interested in running a Telegram bot, more information can be found at [Telegram's official documentation](https://core.telegram.org/bots).\n\n### Run the bot\n\n```shell\npython -m binance_trade_bot\n```\n\n### Run the server that returns the information\n\n```shell\n python -m binance_trade_bot.api_server\n ```\n\n\n### Docker\n\nThe official image is available [here](https://hub.docker.com/r/edeng23/binance-trade-bot) and will update on every new change.\n\n```shell\ndocker-compose up\n```\n\nIf you only want to start the SQLite browser\n\n```shell\ndocker-compose up -d sqlitebrowser\n```\n\n## Backtesting\n\nYou can test the bot on historic data to see how it performs.\n\n```shell\npython backtest.py\n```\n\nFeel free to modify that file to test and compare different settings and time periods\n\n## Developing\n\nTo make sure your code is properly formatted before making a pull request,\nremember to install [pre-commit](https://pre-commit.com/):\n\n```shell\npip install pre-commit\npre-commit install\n```\n\nThe scouting algorithm is unlikely to be changed. If you'd like to contribute an alternative\nmethod, [add a new strategy](binance_trade_bot/strategies/README.md).\n\n## Related Projects\n\nThanks to a group of talented developers, there is now a [Telegram bot for remotely managing this project](https://github.com/lorcalhost/BTB-manager-telegram).\n\n## Support the Project\n\n<a href=\"https://www.buymeacoffee.com/edeng\" target=\"_blank\"><img src=\"https://cdn.buymeacoffee.com/buttons/default-orange.png\" alt=\"Buy Me A Coffee\" height=\"41\" width=\"174\"></a>\n\n## Join the Chat\n\n-   **Discord**: [Invite Link](https://discord.gg/m4TNaxreCN)\n\n## FAQ\n\nA list of answers to what seem to be the most frequently asked questions can be found in our discord server, in the corresponding channel.\n\n<p align=\"center\">\n  <img src = \"https://usercontent2.hubstatic.com/6061829.jpg\">\n</p>\n\n## Want to build a bot from scratch?\n\n- Check out [CCXT](https://github.com/ccxt/ccxt)  for more than 100 crypto exchanges with a unified trading API.\n- Check out [Python-Binance](https://github.com/sammchardy/python-binance) for a complete Python Wrapper.\n\n\n## Disclaimer\n\nThis project is for informational purposes only. You should not construe any\nsuch information or other material as legal, tax, investment, financial, or\nother advice. Nothing contained here constitutes a solicitation, recommendation,\nendorsement, or offer by me or any third party service provider to buy or sell\nany securities or other financial instruments in this or in any other\njurisdiction in which such solicitation or offer would be unlawful under the\nsecurities laws of such jurisdiction.\n\nIf you plan to use real money, USE AT YOUR OWN RISK.\n\nUnder no circumstances will I be held responsible or liable in any way for any\nclaims, damages, losses, expenses, costs, or liabilities whatsoever, including,\nwithout limitation, any direct or indirect damages for loss of profits.\n"
  },
  {
    "path": "app.json",
    "content": "{\n    \"name\": \"binance-trade-bot\",\n    \"description\": \"Binance Trader\",\n    \"logo\": \"https://cdn.freebiesupply.com/logos/large/2x/binance-coin-logo-png-transparent.png\",\n    \"repository\": \"https://github.com/edeng23/binance-trade-bot\",\n\t\"formation\": {\n    \"worker\": {\n      \"quantity\": 1,\n      \"size\": \"free\"\n    }\n\t},\n    \"keywords\": [\"python\", \"binance\",\"trading\",\"trader\",\"bot\",\"market\",\"maker\",\"algo\",\"crypto\"],\n    \"env\": {\n      \"API_KEY\": {\n        \"description\": \"Binance API key generated in the Binance account setup stage\",\n        \"required\": true\n      },\n      \"API_SECRET_KEY\": {\n        \"description\": \"Binance secret key generated in the Binance account setup stage\",\n        \"required\": true\n      },\n      \"CURRENT_COIN_SYMBOL\": {\n        \"description\": \"This is your starting coin of choice. This should be one of the coins from your supported coin list. If you want to start from your bridge currency, leave this field empty - the bot will select a random coin from your supported coin list and buy it\",\n\t\t\"required\": false,\n\t      \"value\": \"XMR\"\n      },\n      \"BRIDGE_SYMBOL\": {\n        \"description\": \"Your bridge currency of choice. Notice that different bridges will allow different sets of supported coins. For example, there may be a Binance particular-coin/USDT pair but no particular-coin/BUSD pair\",\n        \"required\": true,\n\t\t\"value\": \"USDT\"\n      },\n      \"TLD\": {\n        \"description\": \"'com' or 'us', depending on your region. Default is 'com'\",\n        \"required\": true,\n\t\t\"value\": \"com\"\n      },\n      \"SCOUT_MULTIPLIER\": {\n        \"description\": \"Controls the value by which the difference between the current state of coin ratios and previous state of ratios is multiplied. For bigger values, the bot will wait for bigger margins to arrive before making a trade\",\n        \"required\": true,\n\t\t\"value\": \"5\"\n      },\n      \"SCOUT_SLEEP_TIME\": {\n        \"description\": \"Controls how many seconds are waited between each scout\",\n        \"required\": true,\n\t\t\"value\": \"1\"\n      },\n      \"HOURS_TO_KEEP_SCOUTING_HISTORY\": {\n        \"description\": \"Controls how many hours of scouting values are kept in the database. After the amount of time specified has passed, the information will be deleted.\",\n        \"required\": true,\n\t\t\"value\": \"1\"\n      },\n      \"STRATEGY\": {\n        \"description\": \"The trading strategy to use. See binance_trade_bot/strategies for more information. Options: default or multiple_coins\",\n        \"required\": true,\n\t\t\"value\": \"default\"\n      },\n      \"BUY_TIMEOUT\": {\n        \"description\": \"Controls how many minutes to wait before cancelling a limit order (buy/sell) and returning to 'scout' mode. 0 means that the order will never be cancelled prematurely\",\n        \"required\": true,\n\t\t\"value\": \"0\"\n      },\n      \"SELL_TIMEOUT\": {\n        \"description\": \"Controls how many minutes to wait before cancelling a limit order (buy/sell) and returning to 'scout' mode. 0 means that the order will never be cancelled prematurely\",\n        \"required\": true,\n\t\t\"value\": \"0\"\n      },\n      \"SUPPORTED_COIN_LIST\": {\n        \"description\": \"Supported coin list\",\n        \"required\": true,\n\t\t\"value\": \"ADA ATOM BAT BTT DASH DOGE EOS ETC ICX IOTA NEO OMG ONT QTUM TRX VET XLM XMR\"\n      }\n    }\n  }\n"
  },
  {
    "path": "backtest.py",
    "content": "from datetime import datetime\n\nfrom binance_trade_bot import backtest\n\nif __name__ == \"__main__\":\n    history = []\n    for manager in backtest(datetime(2021, 1, 1), datetime.now()):\n        btc_value = manager.collate_coins(\"BTC\")\n        bridge_value = manager.collate_coins(manager.config.BRIDGE.symbol)\n        history.append((btc_value, bridge_value))\n        btc_diff = round((btc_value - history[0][0]) / history[0][0] * 100, 3)\n        bridge_diff = round((bridge_value - history[0][1]) / history[0][1] * 100, 3)\n        print(\"------\")\n        print(\"TIME:\", manager.datetime)\n        print(\"BALANCES:\", manager.balances)\n        print(\"BTC VALUE:\", btc_value, f\"({btc_diff}%)\")\n        print(f\"{manager.config.BRIDGE.symbol} VALUE:\", bridge_value, f\"({bridge_diff}%)\")\n        print(\"------\")\n"
  },
  {
    "path": "binance_trade_bot/__init__.py",
    "content": "from .backtest import backtest\nfrom .binance_api_manager import BinanceAPIManager\nfrom .crypto_trading import main as run_trader\n"
  },
  {
    "path": "binance_trade_bot/__main__.py",
    "content": "from .crypto_trading import main\n\nif __name__ == \"__main__\":\n    try:\n        main()\n    except KeyboardInterrupt:\n        pass\n"
  },
  {
    "path": "binance_trade_bot/api_server.py",
    "content": "import re\nfrom datetime import datetime, timedelta\nfrom itertools import groupby\nfrom typing import List, Tuple\n\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\nfrom flask_socketio import SocketIO, emit\nfrom sqlalchemy import func\nfrom sqlalchemy.orm import Session\n\nfrom .config import Config\nfrom .database import Database\nfrom .logger import Logger\nfrom .models import Coin, CoinValue, CurrentCoin, Pair, ScoutHistory, Trade\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\nsocketio = SocketIO(app, cors_allowed_origins=\"*\")\n\n\nlogger = Logger(\"api_server\")\nconfig = Config()\ndb = Database(logger, config)\n\n\ndef filter_period(query, model):  # pylint: disable=inconsistent-return-statements\n    period = request.args.get(\"period\", \"all\")\n\n    if period == \"all\":\n        return query\n\n    num = float(re.search(r\"(\\d*)[shdwm]\", \"1d\").group(1))\n\n    if \"s\" in period:\n        return query.filter(model.datetime >= datetime.now() - timedelta(seconds=num))\n    if \"h\" in period:\n        return query.filter(model.datetime >= datetime.now() - timedelta(hours=num))\n    if \"d\" in period:\n        return query.filter(model.datetime >= datetime.now() - timedelta(days=num))\n    if \"w\" in period:\n        return query.filter(model.datetime >= datetime.now() - timedelta(weeks=num))\n    if \"m\" in period:\n        return query.filter(model.datetime >= datetime.now() - timedelta(days=28 * num))\n\n\n@app.route(\"/api/value_history/<coin>\")\n@app.route(\"/api/value_history\")\ndef value_history(coin: str = None):\n    session: Session\n    with db.db_session() as session:\n        query = session.query(CoinValue).order_by(CoinValue.coin_id.asc(), CoinValue.datetime.asc())\n\n        query = filter_period(query, CoinValue)\n\n        if coin:\n            values: List[CoinValue] = query.filter(CoinValue.coin_id == coin).all()\n            return jsonify([entry.info() for entry in values])\n\n        coin_values = groupby(query.all(), key=lambda cv: cv.coin)\n        return jsonify({coin.symbol: [entry.info() for entry in history] for coin, history in coin_values})\n\n\n@app.route(\"/api/total_value_history\")\ndef total_value_history():\n    session: Session\n    with db.db_session() as session:\n        query = session.query(\n            CoinValue.datetime,\n            func.sum(CoinValue.btc_value),\n            func.sum(CoinValue.usd_value),\n        ).group_by(CoinValue.datetime)\n\n        query = filter_period(query, CoinValue)\n\n        total_values: List[Tuple[datetime, float, float]] = query.all()\n        return jsonify([{\"datetime\": tv[0], \"btc\": tv[1], \"usd\": tv[2]} for tv in total_values])\n\n\n@app.route(\"/api/trade_history\")\ndef trade_history():\n    session: Session\n    with db.db_session() as session:\n        query = session.query(Trade).order_by(Trade.datetime.asc())\n\n        query = filter_period(query, Trade)\n\n        trades: List[Trade] = query.all()\n        return jsonify([trade.info() for trade in trades])\n\n\n@app.route(\"/api/scouting_history\")\ndef scouting_history():\n    _current_coin = db.get_current_coin()\n    coin = _current_coin.symbol if _current_coin is not None else None\n    session: Session\n    with db.db_session() as session:\n        query = (\n            session.query(ScoutHistory)\n            .join(ScoutHistory.pair)\n            .filter(Pair.from_coin_id == coin)\n            .order_by(ScoutHistory.datetime.asc())\n        )\n\n        query = filter_period(query, ScoutHistory)\n\n        scouts: List[ScoutHistory] = query.all()\n        return jsonify([scout.info() for scout in scouts])\n\n\n@app.route(\"/api/current_coin\")\ndef current_coin():\n    coin = db.get_current_coin()\n    return coin.info() if coin else None\n\n\n@app.route(\"/api/current_coin_history\")\ndef current_coin_history():\n    session: Session\n    with db.db_session() as session:\n        query = session.query(CurrentCoin)\n\n        query = filter_period(query, CurrentCoin)\n\n        current_coins: List[CurrentCoin] = query.all()\n        return jsonify([cc.info() for cc in current_coins])\n\n\n@app.route(\"/api/coins\")\ndef coins():\n    session: Session\n    with db.db_session() as session:\n        _current_coin = session.merge(db.get_current_coin())\n        _coins: List[Coin] = session.query(Coin).all()\n        return jsonify([{**coin.info(), \"is_current\": coin == _current_coin} for coin in _coins])\n\n\n@app.route(\"/api/pairs\")\ndef pairs():\n    session: Session\n    with db.db_session() as session:\n        all_pairs: List[Pair] = session.query(Pair).all()\n        return jsonify([pair.info() for pair in all_pairs])\n\n\n@socketio.on(\"update\", namespace=\"/backend\")\ndef handle_my_custom_event(json):\n    emit(\"update\", json, namespace=\"/frontend\", broadcast=True)\n\n\nif __name__ == \"__main__\":\n    socketio.run(app, debug=True, port=5123)\n"
  },
  {
    "path": "binance_trade_bot/auto_trader.py",
    "content": "from datetime import datetime\nfrom typing import Dict, List\n\nfrom sqlalchemy.orm import Session\n\nfrom .binance_api_manager import BinanceAPIManager\nfrom .config import Config\nfrom .database import Database\nfrom .logger import Logger\nfrom .models import Coin, CoinValue, Pair\n\n\nclass AutoTrader:\n    def __init__(\n        self,\n        binance_manager: BinanceAPIManager,\n        database: Database,\n        logger: Logger,\n        config: Config,\n    ):\n        self.manager = binance_manager\n        self.db = database\n        self.logger = logger\n        self.config = config\n\n    def initialize(self):\n        self.initialize_trade_thresholds()\n\n    def transaction_through_bridge(self, pair: Pair):\n        \"\"\"\n        Jump from the source coin to the destination coin through bridge coin\n        \"\"\"\n        can_sell = False\n        balance = self.manager.get_currency_balance(pair.from_coin.symbol)\n        from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE)\n\n        if balance and balance * from_coin_price > self.manager.get_min_notional(\n            pair.from_coin.symbol, self.config.BRIDGE.symbol\n        ):\n            can_sell = True\n        else:\n            self.logger.info(\"Skipping sell\")\n\n        if can_sell and self.manager.sell_alt(pair.from_coin, self.config.BRIDGE) is None:\n            self.logger.info(\"Couldn't sell, going back to scouting mode...\")\n            return None\n\n        result = self.manager.buy_alt(pair.to_coin, self.config.BRIDGE)\n        if result is not None:\n            self.db.set_current_coin(pair.to_coin)\n            self.update_trade_threshold(pair.to_coin, result.price)\n            return result\n\n        self.logger.info(\"Couldn't buy, going back to scouting mode...\")\n        return None\n\n    def update_trade_threshold(self, coin: Coin, coin_price: float):\n        \"\"\"\n        Update all the coins with the threshold of buying the current held coin\n        \"\"\"\n\n        if coin_price is None:\n            self.logger.info(f\"Skipping update... current coin {coin + self.config.BRIDGE} not found\")\n            return\n\n        session: Session\n        with self.db.db_session() as session:\n            for pair in session.query(Pair).filter(Pair.to_coin == coin):\n                from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE)\n\n                if from_coin_price is None:\n                    self.logger.info(f\"Skipping update for coin {pair.from_coin + self.config.BRIDGE} not found\")\n                    continue\n\n                pair.ratio = from_coin_price / coin_price\n\n    def initialize_trade_thresholds(self):\n        \"\"\"\n        Initialize the buying threshold of all the coins for trading between them\n        \"\"\"\n        session: Session\n        with self.db.db_session() as session:\n            for pair in session.query(Pair).filter(Pair.ratio.is_(None)).all():\n                if not pair.from_coin.enabled or not pair.to_coin.enabled:\n                    continue\n                self.logger.info(f\"Initializing {pair.from_coin} vs {pair.to_coin}\")\n\n                from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE)\n                if from_coin_price is None:\n                    self.logger.info(f\"Skipping initializing {pair.from_coin + self.config.BRIDGE}, symbol not found\")\n                    continue\n\n                to_coin_price = self.manager.get_ticker_price(pair.to_coin + self.config.BRIDGE)\n                if to_coin_price is None:\n                    self.logger.info(f\"Skipping initializing {pair.to_coin + self.config.BRIDGE}, symbol not found\")\n                    continue\n\n                pair.ratio = from_coin_price / to_coin_price\n\n    def scout(self):\n        \"\"\"\n        Scout for potential jumps from the current coin to another coin\n        \"\"\"\n        raise NotImplementedError()\n\n    def _get_ratios(self, coin: Coin, coin_price):\n        \"\"\"\n        Given a coin, get the current price ratio for every other enabled coin\n        \"\"\"\n        ratio_dict: Dict[Pair, float] = {}\n\n        for pair in self.db.get_pairs_from(coin):\n            optional_coin_price = self.manager.get_ticker_price(pair.to_coin + self.config.BRIDGE)\n\n            if optional_coin_price is None:\n                self.logger.info(f\"Skipping scouting... optional coin {pair.to_coin + self.config.BRIDGE} not found\")\n                continue\n\n            self.db.log_scout(pair, pair.ratio, coin_price, optional_coin_price)\n\n            # Obtain (current coin)/(optional coin)\n            coin_opt_coin_ratio = coin_price / optional_coin_price\n\n            # Fees\n            from_fee = self.manager.get_fee(pair.from_coin, self.config.BRIDGE, True)\n            to_fee = self.manager.get_fee(pair.to_coin, self.config.BRIDGE, False)\n            transaction_fee = from_fee + to_fee - from_fee * to_fee\n\n            if self.config.USE_MARGIN == \"yes\":\n                ratio_dict[pair] = (\n                    (1 - transaction_fee) * coin_opt_coin_ratio / pair.ratio - 1 - self.config.SCOUT_MARGIN / 100\n                )\n            else:\n                ratio_dict[pair] = (\n                    coin_opt_coin_ratio - transaction_fee * self.config.SCOUT_MULTIPLIER * coin_opt_coin_ratio\n                ) - pair.ratio\n        return ratio_dict\n\n    def _jump_to_best_coin(self, coin: Coin, coin_price: float):\n        \"\"\"\n        Given a coin, search for a coin to jump to\n        \"\"\"\n        ratio_dict = self._get_ratios(coin, coin_price)\n\n        # keep only ratios bigger than zero\n        ratio_dict = {k: v for k, v in ratio_dict.items() if v > 0}\n\n        # if we have any viable options, pick the one with the biggest ratio\n        if ratio_dict:\n            best_pair = max(ratio_dict, key=ratio_dict.get)\n            self.logger.info(f\"Will be jumping from {coin} to {best_pair.to_coin_id}\")\n            self.transaction_through_bridge(best_pair)\n\n    def bridge_scout(self):\n        \"\"\"\n        If we have any bridge coin leftover, buy a coin with it that we won't immediately trade out of\n        \"\"\"\n        bridge_balance = self.manager.get_currency_balance(self.config.BRIDGE.symbol)\n\n        for coin in self.db.get_coins():\n            current_coin_price = self.manager.get_ticker_price(coin + self.config.BRIDGE)\n\n            if current_coin_price is None:\n                continue\n\n            ratio_dict = self._get_ratios(coin, current_coin_price)\n            if not any(v > 0 for v in ratio_dict.values()):\n                # There will only be one coin where all the ratios are negative. When we find it, buy it if we can\n                if bridge_balance > self.manager.get_min_notional(coin.symbol, self.config.BRIDGE.symbol):\n                    self.logger.info(f\"Will be purchasing {coin} using bridge coin\")\n                    self.manager.buy_alt(coin, self.config.BRIDGE)\n                    return coin\n        return None\n\n    def update_values(self):\n        \"\"\"\n        Log current value state of all altcoin balances against BTC and USDT in DB.\n        \"\"\"\n        now = datetime.now()\n\n        session: Session\n        with self.db.db_session() as session:\n            coins: List[Coin] = session.query(Coin).all()\n            for coin in coins:\n                balance = self.manager.get_currency_balance(coin.symbol)\n                if balance == 0:\n                    continue\n                usd_value = self.manager.get_ticker_price(coin + \"USDT\")\n                btc_value = self.manager.get_ticker_price(coin + \"BTC\")\n                cv = CoinValue(coin, balance, usd_value, btc_value, datetime=now)\n                session.add(cv)\n                self.db.send_update(cv)\n"
  },
  {
    "path": "binance_trade_bot/backtest.py",
    "content": "from collections import defaultdict\nfrom datetime import datetime, timedelta\nfrom traceback import format_exc\nfrom typing import Dict\n\nfrom sqlitedict import SqliteDict\n\nfrom .binance_api_manager import BinanceAPIManager\nfrom .binance_stream_manager import BinanceOrder\nfrom .config import Config\nfrom .database import Database\nfrom .logger import Logger\nfrom .models import Coin, Pair\nfrom .strategies import get_strategy\n\ncache = SqliteDict(\"data/backtest_cache.db\")\n\n\nclass MockBinanceManager(BinanceAPIManager):\n    def __init__(\n        self,\n        config: Config,\n        db: Database,\n        logger: Logger,\n        start_date: datetime = None,\n        start_balances: Dict[str, float] = None,\n    ):\n        super().__init__(config, db, logger)\n        self.config = config\n        self.datetime = start_date or datetime(2021, 1, 1)\n        self.balances = start_balances or {config.BRIDGE.symbol: 100}\n\n    def setup_websockets(self):\n        pass  # No websockets are needed for backtesting\n\n    def increment(self, interval=1):\n        self.datetime += timedelta(minutes=interval)\n\n    def get_fee(self, origin_coin: Coin, target_coin: Coin, selling: bool):\n        return 0.00075\n\n    def get_ticker_price(self, ticker_symbol: str):\n        \"\"\"\n        Get ticker price of a specific coin\n        \"\"\"\n        target_date = self.datetime.strftime(\"%d %b %Y %H:%M:%S\")\n        key = f\"{ticker_symbol} - {target_date}\"\n        val = cache.get(key, None)\n        if val is None:\n            end_date = self.datetime + timedelta(minutes=1000)\n            if end_date > datetime.now():\n                end_date = datetime.now()\n            end_date = end_date.strftime(\"%d %b %Y %H:%M:%S\")\n            self.logger.info(f\"Fetching prices for {ticker_symbol} between {self.datetime} and {end_date}\")\n            for result in self.binance_client.get_historical_klines(\n                ticker_symbol, \"1m\", target_date, end_date, limit=1000\n            ):\n                date = datetime.utcfromtimestamp(result[0] / 1000).strftime(\"%d %b %Y %H:%M:%S\")\n                price = float(result[1])\n                cache[f\"{ticker_symbol} - {date}\"] = price\n            cache.commit()\n            val = cache.get(key, None)\n        return val\n\n    def get_currency_balance(self, currency_symbol: str, force=False):\n        \"\"\"\n        Get balance of a specific coin\n        \"\"\"\n        return self.balances.get(currency_symbol, 0)\n\n    def buy_alt(self, origin_coin: Coin, target_coin: Coin):\n        origin_symbol = origin_coin.symbol\n        target_symbol = target_coin.symbol\n\n        target_balance = self.get_currency_balance(target_symbol)\n        from_coin_price = self.get_ticker_price(origin_symbol + target_symbol)\n\n        order_quantity = self._buy_quantity(origin_symbol, target_symbol, target_balance, from_coin_price)\n        target_quantity = order_quantity * from_coin_price\n        self.balances[target_symbol] -= target_quantity\n        self.balances[origin_symbol] = self.balances.get(origin_symbol, 0) + order_quantity * (\n            1 - self.get_fee(origin_coin, target_coin, False)\n        )\n        self.logger.info(\n            f\"Bought {origin_symbol}, balance now: {self.balances[origin_symbol]} - bridge: \"\n            f\"{self.balances[target_symbol]}\"\n        )\n\n        event = defaultdict(\n            lambda: None,\n            order_price=from_coin_price,\n            cumulative_quote_asset_transacted_quantity=0,\n        )\n\n        return BinanceOrder(event)\n\n    def sell_alt(self, origin_coin: Coin, target_coin: Coin):\n        origin_symbol = origin_coin.symbol\n        target_symbol = target_coin.symbol\n\n        origin_balance = self.get_currency_balance(origin_symbol)\n        from_coin_price = self.get_ticker_price(origin_symbol + target_symbol)\n\n        order_quantity = self._sell_quantity(origin_symbol, target_symbol, origin_balance)\n        target_quantity = order_quantity * from_coin_price\n        self.balances[target_symbol] = self.balances.get(target_symbol, 0) + target_quantity * (\n            1 - self.get_fee(origin_coin, target_coin, True)\n        )\n        self.balances[origin_symbol] -= order_quantity\n        self.logger.info(\n            f\"Sold {origin_symbol}, balance now: {self.balances[origin_symbol]} - bridge: \"\n            f\"{self.balances[target_symbol]}\"\n        )\n        return {\"price\": from_coin_price}\n\n    def collate_coins(self, target_symbol: str):\n        total = 0\n        for coin, balance in self.balances.items():\n            if coin == target_symbol:\n                total += balance\n                continue\n            if coin == self.config.BRIDGE.symbol:\n                price = self.get_ticker_price(target_symbol + coin)\n                if price is None:\n                    continue\n                total += balance / price\n            else:\n                price = self.get_ticker_price(coin + target_symbol)\n                if price is None:\n                    continue\n                total += price * balance\n        return total\n\n\nclass MockDatabase(Database):\n    def __init__(self, logger: Logger, config: Config):\n        super().__init__(logger, config, \"sqlite:///\")\n\n    def log_scout(\n        self,\n        pair: Pair,\n        target_ratio: float,\n        current_coin_price: float,\n        other_coin_price: float,\n    ):\n        pass\n\n\ndef backtest(\n    start_date: datetime = None,\n    end_date: datetime = None,\n    interval=1,\n    yield_interval=100,\n    start_balances: Dict[str, float] = None,\n    starting_coin: str = None,\n    config: Config = None,\n):\n    \"\"\"\n\n    :param config: Configuration object to use\n    :param start_date: Date to  backtest from\n    :param end_date: Date to backtest up to\n    :param interval: Number of virtual minutes between each scout\n    :param yield_interval: After how many intervals should the manager be yielded\n    :param start_balances: A dictionary of initial coin values. Default: {BRIDGE: 100}\n    :param starting_coin: The coin to start on. Default: first coin in coin list\n\n    :return: The final coin balances\n    \"\"\"\n    config = config or Config()\n    logger = Logger(\"backtesting\", enable_notifications=False)\n\n    end_date = end_date or datetime.today()\n\n    db = MockDatabase(logger, config)\n    db.create_database()\n    db.set_coins(config.SUPPORTED_COIN_LIST)\n    manager = MockBinanceManager(config, db, logger, start_date, start_balances)\n\n    starting_coin = db.get_coin(starting_coin or config.SUPPORTED_COIN_LIST[0])\n    if manager.get_currency_balance(starting_coin.symbol) == 0:\n        manager.buy_alt(starting_coin, config.BRIDGE)\n    db.set_current_coin(starting_coin)\n\n    strategy = get_strategy(config.STRATEGY)\n    if strategy is None:\n        logger.error(\"Invalid strategy name\")\n        return manager\n    trader = strategy(manager, db, logger, config)\n    trader.initialize()\n\n    yield manager\n\n    n = 1\n    try:\n        while manager.datetime < end_date:\n            try:\n                trader.scout()\n            except Exception:  # pylint: disable=broad-except\n                logger.warning(format_exc())\n            manager.increment(interval)\n            if n % yield_interval == 0:\n                yield manager\n            n += 1\n    except KeyboardInterrupt:\n        pass\n    cache.close()\n    return manager\n"
  },
  {
    "path": "binance_trade_bot/binance_api_manager.py",
    "content": "import math\nimport time\nimport traceback\nfrom typing import Dict, Optional\n\nfrom binance.client import Client\nfrom binance.exceptions import BinanceAPIException\nfrom cachetools import TTLCache, cached\n\nfrom .binance_stream_manager import BinanceCache, BinanceOrder, BinanceStreamManager, OrderGuard\nfrom .config import Config\nfrom .database import Database\nfrom .logger import Logger\nfrom .models import Coin\n\n\nclass BinanceAPIManager:\n    def __init__(self, config: Config, db: Database, logger: Logger, testnet = False):\n        # initializing the client class calls `ping` API endpoint, verifying the connection\n        self.binance_client = Client(\n            config.BINANCE_API_KEY,\n            config.BINANCE_API_SECRET_KEY,\n            tld=config.BINANCE_TLD,\n            testnet=testnet,\n        )\n        self.db = db\n        self.logger = logger\n        self.config = config\n        self.testnet = testnet\n\n        self.cache = BinanceCache()\n        self.stream_manager: Optional[BinanceStreamManager] = None\n        self.setup_websockets()\n\n    def setup_websockets(self):\n        self.stream_manager = BinanceStreamManager(\n            self.cache,\n            self.config,\n            self.binance_client,\n            self.logger,\n        )\n\n    @cached(cache=TTLCache(maxsize=1, ttl=43200))\n    def get_trade_fees(self) -> Dict[str, float]:\n        if not self.testnet:\n            return {ticker[\"symbol\"]: float(ticker[\"takerCommission\"]) for ticker in self.binance_client.get_trade_fee()}\n\n\n        ## testnet does not provide trade fee API, emulating it\n        exchange_info = self.binance_client.get_exchange_info()\n        symbols = exchange_info[\"symbols\"]\n        return {\n            symbol[\"symbol\"]: 0.001\n            for symbol in symbols\n        }\n\n\n    @cached(cache=TTLCache(maxsize=1, ttl=60))\n    def get_using_bnb_for_fees(self):\n        return self.binance_client.get_bnb_burn_spot_margin()[\"spotBNBBurn\"]\n\n    def get_fee(self, origin_coin: Coin, target_coin: Coin, selling: bool):\n        base_fee = self.get_trade_fees()[origin_coin + target_coin]\n        if not self.testnet:\n            if not self.get_using_bnb_for_fees():\n                return base_fee\n\n        # The discount is only applied if we have enough BNB to cover the fee\n        amount_trading = (\n            self._sell_quantity(origin_coin.symbol, target_coin.symbol)\n            if selling\n            else self._buy_quantity(origin_coin.symbol, target_coin.symbol)\n        )\n\n        fee_amount = amount_trading * base_fee * 0.75\n        if origin_coin.symbol == \"BNB\":\n            fee_amount_bnb = fee_amount\n        else:\n            origin_price = self.get_ticker_price(origin_coin + Coin(\"BNB\"))\n            if origin_price is None:\n                return base_fee\n            fee_amount_bnb = fee_amount * origin_price\n\n        bnb_balance = self.get_currency_balance(\"BNB\")\n\n        if bnb_balance >= fee_amount_bnb:\n            return base_fee * 0.75\n        return base_fee\n\n    def get_account(self):\n        \"\"\"\n        Get account information\n        \"\"\"\n        return self.binance_client.get_account()\n\n    def get_ticker_price(self, ticker_symbol: str):\n        \"\"\"\n        Get ticker price of a specific coin\n        \"\"\"\n        price = self.cache.ticker_values.get(ticker_symbol, None)\n        if price is None and ticker_symbol not in self.cache.non_existent_tickers:\n            self.cache.ticker_values = {\n                ticker[\"symbol\"]: float(ticker[\"price\"]) for ticker in self.binance_client.get_symbol_ticker()\n            }\n            self.logger.debug(f\"Fetched all ticker prices: {self.cache.ticker_values}\")\n            price = self.cache.ticker_values.get(ticker_symbol, None)\n            if price is None:\n                self.logger.info(f\"Ticker does not exist: {ticker_symbol} - will not be fetched from now on\")\n                self.cache.non_existent_tickers.add(ticker_symbol)\n\n        return price\n\n    def get_currency_balance(self, currency_symbol: str, force=False) -> float:\n        \"\"\"\n        Get balance of a specific coin\n        \"\"\"\n        with self.cache.open_balances() as cache_balances:\n            balance = cache_balances.get(currency_symbol, None)\n            if force or balance is None:\n                cache_balances.clear()\n                cache_balances.update(\n                    {\n                        currency_balance[\"asset\"]: float(currency_balance[\"free\"])\n                        for currency_balance in self.binance_client.get_account()[\"balances\"]\n                    }\n                )\n                self.logger.debug(f\"Fetched all balances: {cache_balances}\")\n                if currency_symbol not in cache_balances:\n                    cache_balances[currency_symbol] = 0.0\n                    return 0.0\n                return cache_balances.get(currency_symbol, 0.0)\n\n            return balance\n\n    def retry(self, func, *args, **kwargs):\n        for attempt in range(20):\n            try:\n                return func(*args, **kwargs)\n            except Exception:  # pylint: disable=broad-except\n                self.logger.warning(f\"Failed to Buy/Sell. Trying Again (attempt {attempt}/20)\")\n                if attempt == 0:\n                    self.logger.warning(traceback.format_exc())\n                time.sleep(1)\n        return None\n\n    def get_symbol_filter(self, origin_symbol: str, target_symbol: str, filter_type: str):\n        return next(\n            _filter\n            for _filter in self.binance_client.get_symbol_info(origin_symbol + target_symbol)[\"filters\"]\n            if _filter[\"filterType\"] == filter_type\n        )\n\n    @cached(cache=TTLCache(maxsize=2000, ttl=43200))\n    def get_alt_tick(self, origin_symbol: str, target_symbol: str):\n        step_size = self.get_symbol_filter(origin_symbol, target_symbol, \"LOT_SIZE\")[\"stepSize\"]\n        if step_size.find(\"1\") == 0:\n            return 1 - step_size.find(\".\")\n        return step_size.find(\"1\") - 1\n\n    @cached(cache=TTLCache(maxsize=2000, ttl=43200))\n    def get_min_notional(self, origin_symbol: str, target_symbol: str):\n        return float(self.get_symbol_filter(origin_symbol, target_symbol, \"NOTIONAL\")[\"minNotional\"])\n\n    def _wait_for_order(\n        self, order_id, origin_symbol: str, target_symbol: str\n    ) -> Optional[BinanceOrder]:  # pylint: disable=unsubscriptable-object\n        while True:\n            order_status: BinanceOrder = self.cache.orders.get(order_id, None)\n            if order_status is not None:\n                break\n            self.logger.debug(f\"Waiting for order {order_id} to be created\")\n            time.sleep(1)\n\n        self.logger.debug(f\"Order created: {order_status}\")\n\n        while order_status.status != \"FILLED\":\n            try:\n                order_status = self.cache.orders.get(order_id, None)\n\n                self.logger.debug(f\"Waiting for order {order_id} to be filled\")\n\n                if self._should_cancel_order(order_status):\n                    cancel_order = None\n                    while cancel_order is None:\n                        cancel_order = self.binance_client.cancel_order(\n                            symbol=origin_symbol + target_symbol, orderId=order_id\n                        )\n                    self.logger.info(\"Order timeout, canceled...\")\n\n                    # sell partially\n                    if order_status.status == \"PARTIALLY_FILLED\" and order_status.side == \"BUY\":\n                        self.logger.info(\"Sell partially filled amount\")\n\n                        order_quantity = self._sell_quantity(origin_symbol, target_symbol)\n                        partially_order = None\n                        while partially_order is None:\n                            partially_order = self.binance_client.order_market_sell(\n                                symbol=origin_symbol + target_symbol,\n                                quantity=order_quantity,\n                            )\n\n                    self.logger.info(\"Going back to scouting mode...\")\n                    return None\n\n                if order_status.status == \"CANCELED\":\n                    self.logger.info(\"Order is canceled, going back to scouting mode...\")\n                    return None\n\n                time.sleep(1)\n            except BinanceAPIException as e:\n                self.logger.info(e)\n                time.sleep(1)\n            except Exception as e:  # pylint: disable=broad-except\n                self.logger.info(f\"Unexpected Error: {e}\")\n                time.sleep(1)\n\n        self.logger.debug(f\"Order filled: {order_status}\")\n        return order_status\n\n    def wait_for_order(\n        self, order_id, origin_symbol: str, target_symbol: str, order_guard: OrderGuard\n    ) -> Optional[BinanceOrder]:  # pylint: disable=unsubscriptable-object\n        with order_guard:\n            return self._wait_for_order(order_id, origin_symbol, target_symbol)\n\n    def _should_cancel_order(self, order_status):\n        minutes = (time.time() - order_status.time / 1000) / 60\n        timeout = 0\n\n        if order_status.side == \"SELL\":\n            timeout = float(self.config.SELL_TIMEOUT)\n        else:\n            timeout = float(self.config.BUY_TIMEOUT)\n\n        if timeout and minutes > timeout and order_status.status == \"NEW\":\n            return True\n\n        if timeout and minutes > timeout and order_status.status == \"PARTIALLY_FILLED\":\n            if order_status.side == \"SELL\":\n                return True\n\n            if order_status.side == \"BUY\":\n                current_price = self.get_ticker_price(order_status.symbol)\n                if float(current_price) * (1 - 0.001) > float(order_status.price):\n                    return True\n\n        return False\n\n    def buy_alt(self, origin_coin: Coin, target_coin: Coin) -> BinanceOrder:\n        return self.retry(self._buy_alt, origin_coin, target_coin)\n\n    def _buy_quantity(\n        self,\n        origin_symbol: str,\n        target_symbol: str,\n        target_balance: float = None,\n        from_coin_price: float = None,\n    ):\n        target_balance = target_balance or self.get_currency_balance(target_symbol)\n        from_coin_price = from_coin_price or self.get_ticker_price(origin_symbol + target_symbol)\n\n        origin_tick = self.get_alt_tick(origin_symbol, target_symbol)\n        return math.floor(target_balance * 10**origin_tick / from_coin_price) / float(10**origin_tick)\n\n    def _buy_alt(self, origin_coin: Coin, target_coin: Coin):  # pylint: disable=too-many-locals\n        \"\"\"\n        Buy altcoin\n        \"\"\"\n        trade_log = self.db.start_trade_log(origin_coin, target_coin, False)\n        origin_symbol = origin_coin.symbol\n        target_symbol = target_coin.symbol\n\n        with self.cache.open_balances() as balances:\n            balances.clear()\n\n        origin_balance = self.get_currency_balance(origin_symbol)\n        target_balance = self.get_currency_balance(target_symbol)\n        pair_info = self.binance_client.get_symbol_info(origin_symbol + target_symbol)\n        from_coin_price = self.get_ticker_price(origin_symbol + target_symbol)\n        from_coin_price_s = \"{:0.0{}f}\".format(from_coin_price, pair_info[\"quotePrecision\"])\n\n        order_quantity = self._buy_quantity(origin_symbol, target_symbol, target_balance, from_coin_price)\n        order_quantity_s = \"{:0.0{}f}\".format(order_quantity, pair_info[\"baseAssetPrecision\"])\n\n        self.logger.info(f\"BUY QTY {order_quantity}\")\n\n        # Try to buy until successful\n        order = None\n        order_guard = self.stream_manager.acquire_order_guard()\n        while order is None:\n            try:\n                order = self.binance_client.order_limit_buy(\n                    symbol=origin_symbol + target_symbol,\n                    quantity=order_quantity_s,\n                    price=from_coin_price_s,\n                )\n                self.logger.info(order)\n            except BinanceAPIException as e:\n                self.logger.info(e)\n                time.sleep(1)\n            except Exception as e:  # pylint: disable=broad-except\n                self.logger.warning(f\"Unexpected Error: {e}\")\n\n        trade_log.set_ordered(origin_balance, target_balance, order_quantity)\n\n        order_guard.set_order(origin_symbol, target_symbol, int(order[\"orderId\"]))\n        order = self.wait_for_order(order[\"orderId\"], origin_symbol, target_symbol, order_guard)\n\n        if order is None:\n            return None\n\n        self.logger.info(f\"Bought {origin_symbol}\")\n\n        trade_log.set_complete(order.cumulative_quote_qty)\n\n        return order\n\n    def sell_alt(self, origin_coin: Coin, target_coin: Coin) -> BinanceOrder:\n        return self.retry(self._sell_alt, origin_coin, target_coin)\n\n    def _sell_quantity(self, origin_symbol: str, target_symbol: str, origin_balance: float = None):\n        origin_balance = origin_balance or self.get_currency_balance(origin_symbol)\n\n        origin_tick = self.get_alt_tick(origin_symbol, target_symbol)\n        return math.floor(origin_balance * 10**origin_tick) / float(10**origin_tick)\n\n    def _sell_alt(self, origin_coin: Coin, target_coin: Coin):  # pylint: disable=too-many-locals\n        \"\"\"\n        Sell altcoin\n        \"\"\"\n        trade_log = self.db.start_trade_log(origin_coin, target_coin, True)\n        origin_symbol = origin_coin.symbol\n        target_symbol = target_coin.symbol\n\n        with self.cache.open_balances() as balances:\n            balances.clear()\n\n        origin_balance = self.get_currency_balance(origin_symbol)\n        target_balance = self.get_currency_balance(target_symbol)\n\n        pair_info = self.binance_client.get_symbol_info(origin_symbol + target_symbol)\n        from_coin_price = self.get_ticker_price(origin_symbol + target_symbol)\n        from_coin_price_s = \"{:0.0{}f}\".format(from_coin_price, pair_info[\"quotePrecision\"])\n\n        order_quantity = self._sell_quantity(origin_symbol, target_symbol, origin_balance)\n        order_quantity_s = \"{:0.0{}f}\".format(order_quantity, pair_info[\"baseAssetPrecision\"])\n        self.logger.info(f\"Selling {order_quantity} of {origin_symbol}\")\n\n        self.logger.info(f\"Balance is {origin_balance}\")\n        order = None\n        order_guard = self.stream_manager.acquire_order_guard()\n        while order is None:\n            # Should sell at calculated price to avoid lost coin\n            order = self.binance_client.order_limit_sell(\n                symbol=origin_symbol + target_symbol,\n                quantity=(order_quantity_s),\n                price=from_coin_price_s,\n            )\n\n        self.logger.info(\"order\")\n        self.logger.info(order)\n\n        trade_log.set_ordered(origin_balance, target_balance, order_quantity)\n\n        order_guard.set_order(origin_symbol, target_symbol, int(order[\"orderId\"]))\n        order = self.wait_for_order(order[\"orderId\"], origin_symbol, target_symbol, order_guard)\n\n        if order is None:\n            return None\n\n        new_balance = self.get_currency_balance(origin_symbol)\n        while new_balance >= origin_balance:\n            new_balance = self.get_currency_balance(origin_symbol, True)\n\n        self.logger.info(f\"Sold {origin_symbol}\")\n\n        trade_log.set_complete(order.cumulative_quote_qty)\n\n        return order\n"
  },
  {
    "path": "binance_trade_bot/binance_stream_manager.py",
    "content": "import sys\nimport threading\nimport time\nfrom contextlib import contextmanager\nfrom typing import Dict, Set, Tuple\n\nimport binance.client\nfrom binance.exceptions import BinanceAPIException, BinanceRequestException\nfrom unicorn_binance_websocket_api import BinanceWebSocketApiManager\n\nfrom .config import Config\nfrom .logger import Logger\n\n\nclass BinanceOrder:  # pylint: disable=too-few-public-methods\n    def __init__(self, report):\n        self.event = report\n        self.symbol = report[\"symbol\"]\n        self.side = report[\"side\"]\n        self.order_type = report[\"order_type\"]\n        self.id = report[\"order_id\"]\n        self.cumulative_quote_qty = float(report[\"cumulative_quote_asset_transacted_quantity\"])\n        self.status = report[\"current_order_status\"]\n        self.price = float(report[\"order_price\"])\n        self.time = report[\"transaction_time\"]\n\n    def __repr__(self):\n        return f\"<BinanceOrder {self.event}>\"\n\n\nclass BinanceCache:  # pylint: disable=too-few-public-methods\n    ticker_values: Dict[str, float] = {}\n    _balances: Dict[str, float] = {}\n    _balances_mutex: threading.Lock = threading.Lock()\n    non_existent_tickers: Set[str] = set()\n    orders: Dict[str, BinanceOrder] = {}\n\n    @contextmanager\n    def open_balances(self):\n        with self._balances_mutex:\n            yield self._balances\n\n\nclass OrderGuard:\n    def __init__(self, pending_orders: Set[Tuple[str, int]], mutex: threading.Lock):\n        self.pending_orders = pending_orders\n        self.mutex = mutex\n        # lock immediately because OrderGuard\n        # should be entered and put tag that shouldn't be missed\n        self.mutex.acquire()\n        self.tag = None\n\n    def set_order(self, origin_symbol: str, target_symbol: str, order_id: int):\n        self.tag = (origin_symbol + target_symbol, order_id)\n\n    def __enter__(self):\n        try:\n            if self.tag is None:\n                raise Exception(\"OrderGuard wasn't properly set\")\n            self.pending_orders.add(self.tag)\n        finally:\n            self.mutex.release()\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        self.pending_orders.remove(self.tag)\n\n\nclass BinanceStreamManager:\n    def __init__(\n        self,\n        cache: BinanceCache,\n        config: Config,\n        binance_client: binance.client.Client,\n        logger: Logger,\n    ):\n        self.cache = cache\n        self.logger = logger\n        exchange_name = f\"binance.{config.BINANCE_TLD}\"\n        if config.TESTNET:\n            exchange_name += \"-testnet\"\n        self.bw_api_manager = BinanceWebSocketApiManager(\n            output_default=\"UnicornFy\",\n            enable_stream_signal_buffer=True,\n            exchange=exchange_name,\n        )\n        self.bw_api_manager.create_stream(\n            [\"arr\"],\n            [\"!miniTicker\"],\n            api_key=config.BINANCE_API_KEY,\n            api_secret=config.BINANCE_API_SECRET_KEY,\n        )\n        self.bw_api_manager.create_stream(\n            [\"arr\"],\n            [\"!userData\"],\n            api_key=config.BINANCE_API_KEY,\n            api_secret=config.BINANCE_API_SECRET_KEY,\n        )\n        self.binance_client = binance_client\n        self.pending_orders: Set[Tuple[str, int]] = set()\n        self.pending_orders_mutex: threading.Lock = threading.Lock()\n        self._processorThread = threading.Thread(target=self._stream_processor)\n        self._processorThread.start()\n\n    def acquire_order_guard(self):\n        return OrderGuard(self.pending_orders, self.pending_orders_mutex)\n\n    def _fetch_pending_orders(self):\n        pending_orders: Set[Tuple[str, int]]\n        with self.pending_orders_mutex:\n            pending_orders = self.pending_orders.copy()\n        for symbol, order_id in pending_orders:\n            order = None\n            while True:\n                try:\n                    order = self.binance_client.get_order(symbol=symbol, orderId=order_id)\n                except (BinanceRequestException, BinanceAPIException) as e:\n                    self.logger.error(f\"Got exception during fetching pending order: {e}\")\n                if order is not None:\n                    break\n                time.sleep(1)\n            fake_report = {\n                \"symbol\": order[\"symbol\"],\n                \"side\": order[\"side\"],\n                \"order_type\": order[\"type\"],\n                \"order_id\": order[\"orderId\"],\n                \"cumulative_quote_asset_transacted_quantity\": float(order[\"cummulativeQuoteQty\"]),\n                \"current_order_status\": order[\"status\"],\n                \"order_price\": float(order[\"price\"]),\n                \"transaction_time\": order[\"time\"],\n            }\n            self.logger.info(\n                f\"Pending order {order_id} for symbol {symbol} fetched:\\n{fake_report}\",\n                False,\n            )\n            self.cache.orders[fake_report[\"order_id\"]] = BinanceOrder(fake_report)\n\n    def _invalidate_balances(self):\n        with self.cache.open_balances() as balances:\n            balances.clear()\n\n    def _stream_processor(self):\n        while True:\n            if self.bw_api_manager.is_manager_stopping():\n                sys.exit()\n\n            stream_signal = self.bw_api_manager.pop_stream_signal_from_stream_signal_buffer()\n            stream_data = self.bw_api_manager.pop_stream_data_from_stream_buffer()\n\n            if stream_signal is not False:\n                signal_type = stream_signal[\"type\"]\n                stream_id = stream_signal[\"stream_id\"]\n                if signal_type == \"CONNECT\":\n                    stream_info = self.bw_api_manager.get_stream_info(stream_id)\n                    if \"!userData\" in stream_info[\"markets\"]:\n                        self.logger.debug(\"Connect for userdata arrived\", False)\n                        self._fetch_pending_orders()\n                        self._invalidate_balances()\n            if stream_data is not False:\n                self._process_stream_data(stream_data)\n            if stream_data is False and stream_signal is False:\n                time.sleep(0.01)\n\n    def _process_stream_data(self, stream_data):\n        event_type = stream_data[\"event_type\"]\n        if event_type == \"executionReport\":  # !userData\n            self.logger.debug(f\"execution report: {stream_data}\")\n            order = BinanceOrder(stream_data)\n            self.cache.orders[order.id] = order\n        elif event_type == \"balanceUpdate\":  # !userData\n            self.logger.debug(f\"Balance update: {stream_data}\")\n            with self.cache.open_balances() as balances:\n                asset = stream_data[\"asset\"]\n                if asset in balances:\n                    del balances[stream_data[\"asset\"]]\n        elif event_type in (\n            \"outboundAccountPosition\",\n            \"outboundAccountInfo\",\n        ):  # !userData\n            self.logger.debug(f\"{event_type}: {stream_data}\")\n            with self.cache.open_balances() as balances:\n                for bal in stream_data[\"balances\"]:\n                    balances[bal[\"asset\"]] = float(bal[\"free\"])\n        elif event_type == \"24hrMiniTicker\":\n            for event in stream_data[\"data\"]:\n                self.cache.ticker_values[event[\"symbol\"]] = float(event[\"close_price\"])\n        else:\n            self.logger.error(f\"Unknown event type found: {event_type}\\n{stream_data}\")\n\n    def close(self):\n        self.bw_api_manager.stop_manager_with_all_streams()\n"
  },
  {
    "path": "binance_trade_bot/config.py",
    "content": "# Config consts\nimport configparser\nimport os\n\nfrom .models import Coin\n\nCFG_FL_NAME = \"user.cfg\"\nUSER_CFG_SECTION = \"binance_user_config\"\n\n\nclass Config:  # pylint: disable=too-few-public-methods,too-many-instance-attributes\n    def __init__(self):\n        # Init config\n        config = configparser.ConfigParser()\n        config[\"DEFAULT\"] = {\n            \"bridge\": \"USDT\",\n            \"use_margin\": \"no\",\n            \"scout_multiplier\": \"5\",\n            \"scout_margin\": \"0.8\",\n            \"scout_sleep_time\": \"5\",\n            \"hourToKeepScoutHistory\": \"1\",\n            \"tld\": \"com\",\n            \"strategy\": \"default\",\n            \"sell_timeout\": \"0\",\n            \"buy_timeout\": \"0\",\n            \"testnet\": False,\n        }\n\n        if not os.path.exists(CFG_FL_NAME):\n            print(\"No configuration file (user.cfg) found! See README. Assuming default config...\")\n            config[USER_CFG_SECTION] = {}\n        else:\n            config.read(CFG_FL_NAME)\n\n        self.BRIDGE_SYMBOL = os.environ.get(\"BRIDGE_SYMBOL\") or config.get(USER_CFG_SECTION, \"bridge\")\n        self.BRIDGE = Coin(self.BRIDGE_SYMBOL, False)\n        self.TESTNET = os.environ.get(\"TESTNET\") or config.getboolean(USER_CFG_SECTION, \"testnet\")\n\n        # Prune settings\n        self.SCOUT_HISTORY_PRUNE_TIME = float(\n            os.environ.get(\"HOURS_TO_KEEP_SCOUTING_HISTORY\") or config.get(USER_CFG_SECTION, \"hourToKeepScoutHistory\")\n        )\n\n        # Get config for scout\n        self.SCOUT_MULTIPLIER = float(\n            os.environ.get(\"SCOUT_MULTIPLIER\") or config.get(USER_CFG_SECTION, \"scout_multiplier\")\n        )\n        self.SCOUT_SLEEP_TIME = int(\n            os.environ.get(\"SCOUT_SLEEP_TIME\") or config.get(USER_CFG_SECTION, \"scout_sleep_time\")\n        )\n\n        # Get config for binance\n        self.BINANCE_API_KEY = os.environ.get(\"API_KEY\") or config.get(USER_CFG_SECTION, \"api_key\")\n        self.BINANCE_API_SECRET_KEY = os.environ.get(\"API_SECRET_KEY\") or config.get(USER_CFG_SECTION, \"api_secret_key\")\n        self.BINANCE_TLD = os.environ.get(\"TLD\") or config.get(USER_CFG_SECTION, \"tld\")\n\n        # Get supported coin list from the environment\n        supported_coin_list = [\n            coin.strip() for coin in os.environ.get(\"SUPPORTED_COIN_LIST\", \"\").split() if coin.strip()\n        ]\n        # Get supported coin list from supported_coin_list file\n        if not supported_coin_list and os.path.exists(\"supported_coin_list\"):\n            with open(\"supported_coin_list\") as rfh:\n                for line in rfh:\n                    line = line.strip()\n                    if not line or line.startswith(\"#\") or line in supported_coin_list:\n                        continue\n                    supported_coin_list.append(line)\n        self.SUPPORTED_COIN_LIST = supported_coin_list\n\n        self.CURRENT_COIN_SYMBOL = os.environ.get(\"CURRENT_COIN_SYMBOL\") or config.get(USER_CFG_SECTION, \"current_coin\")\n\n        self.STRATEGY = os.environ.get(\"STRATEGY\") or config.get(USER_CFG_SECTION, \"strategy\")\n\n        self.SELL_TIMEOUT = os.environ.get(\"SELL_TIMEOUT\") or config.get(USER_CFG_SECTION, \"sell_timeout\")\n        self.BUY_TIMEOUT = os.environ.get(\"BUY_TIMEOUT\") or config.get(USER_CFG_SECTION, \"buy_timeout\")\n\n        self.USE_MARGIN = os.environ.get(\"USE_MARGIN\") or config.get(USER_CFG_SECTION, \"use_margin\")\n        self.SCOUT_MARGIN = float(os.environ.get(\"SCOUT_MARGIN\") or config.get(USER_CFG_SECTION, \"scout_margin\"))\n"
  },
  {
    "path": "binance_trade_bot/crypto_trading.py",
    "content": "#!python3\nimport time\n\nfrom .binance_api_manager import BinanceAPIManager\nfrom .config import Config\nfrom .database import Database\nfrom .logger import Logger\nfrom .scheduler import SafeScheduler\nfrom .strategies import get_strategy\n\n\ndef main():\n    logger = Logger()\n    logger.info(\"Starting\")\n\n    config = Config()\n    db = Database(logger, config)\n    manager = BinanceAPIManager(config, db, logger, config.TESTNET)\n    # check if we can access API feature that require valid config\n    try:\n        _ = manager.get_account()\n    except Exception as e:  # pylint: disable=broad-except\n        logger.error(\"Couldn't access Binance API - API keys may be wrong or lack sufficient permissions\")\n        logger.error(e)\n        return\n    strategy = get_strategy(config.STRATEGY)\n    if strategy is None:\n        logger.error(\"Invalid strategy name\")\n        return\n    trader = strategy(manager, db, logger, config)\n    logger.info(f\"Chosen strategy: {config.STRATEGY}\")\n\n    logger.info(\"Creating database schema if it doesn't already exist\")\n    db.create_database()\n\n    db.set_coins(config.SUPPORTED_COIN_LIST)\n    db.migrate_old_state()\n\n    trader.initialize()\n\n    schedule = SafeScheduler(logger)\n    schedule.every(config.SCOUT_SLEEP_TIME).seconds.do(trader.scout).tag(\"scouting\")\n    schedule.every(1).minutes.do(trader.update_values).tag(\"updating value history\")\n    schedule.every(1).minutes.do(db.prune_scout_history).tag(\"pruning scout history\")\n    schedule.every(1).hours.do(db.prune_value_history).tag(\"pruning value history\")\n    try:\n        while True:\n            schedule.run_pending()\n            time.sleep(1)\n    finally:\n        manager.stream_manager.close()"
  },
  {
    "path": "binance_trade_bot/database.py",
    "content": "import json\nimport os\nimport time\nfrom contextlib import contextmanager\nfrom datetime import datetime, timedelta\nfrom typing import List, Optional, Union\n\nfrom socketio import Client\nfrom socketio.exceptions import ConnectionError as SocketIOConnectionError\nfrom sqlalchemy import create_engine, func\nfrom sqlalchemy.orm import Session, scoped_session, sessionmaker\n\nfrom .config import Config\nfrom .logger import Logger\nfrom .models import *  # pylint: disable=wildcard-import\n\n\nclass Database:\n    def __init__(self, logger: Logger, config: Config, uri=\"sqlite:///data/crypto_trading.db\"):\n        self.logger = logger\n        self.config = config\n        self.engine = create_engine(uri)\n        self.SessionMaker = sessionmaker(bind=self.engine)\n        self.socketio_client = Client()\n\n    def socketio_connect(self):\n        if self.socketio_client.connected and self.socketio_client.namespaces:\n            return True\n        try:\n            if not self.socketio_client.connected:\n                self.socketio_client.connect(\"http://api:5123\", namespaces=[\"/backend\"])\n            while not self.socketio_client.connected or not self.socketio_client.namespaces:\n                time.sleep(0.1)\n            return True\n        except SocketIOConnectionError:\n            return False\n\n    @contextmanager\n    def db_session(self):\n        \"\"\"\n        Creates a context with an open SQLAlchemy session.\n        \"\"\"\n        session: Session = scoped_session(self.SessionMaker)\n        yield session\n        session.commit()\n        session.close()\n\n    def set_coins(self, symbols: List[str]):\n        session: Session\n\n        # Add coins to the database and set them as enabled or not\n        with self.db_session() as session:\n            # For all the coins in the database, if the symbol no longer appears\n            # in the config file, set the coin as disabled\n            coins: List[Coin] = session.query(Coin).all()\n            for coin in coins:\n                if coin.symbol not in symbols:\n                    coin.enabled = False\n\n            # For all the symbols in the config file, add them to the database\n            # if they don't exist\n            for symbol in symbols:\n                coin = next((coin for coin in coins if coin.symbol == symbol), None)\n                if coin is None:\n                    session.add(Coin(symbol))\n                else:\n                    coin.enabled = True\n\n        # For all the combinations of coins in the database, add a pair to the database\n        with self.db_session() as session:\n            coins: List[Coin] = session.query(Coin).filter(Coin.enabled).all()\n            for from_coin in coins:\n                for to_coin in coins:\n                    if from_coin != to_coin:\n                        pair = session.query(Pair).filter(Pair.from_coin == from_coin, Pair.to_coin == to_coin).first()\n                        if pair is None:\n                            session.add(Pair(from_coin, to_coin))\n\n    def get_coins(self, only_enabled=True) -> List[Coin]:\n        session: Session\n        with self.db_session() as session:\n            if only_enabled:\n                coins = session.query(Coin).filter(Coin.enabled).all()\n            else:\n                coins = session.query(Coin).all()\n            session.expunge_all()\n            return coins\n\n    def get_coin(self, coin: Union[Coin, str]) -> Coin:\n        if isinstance(coin, Coin):\n            return coin\n        session: Session\n        with self.db_session() as session:\n            coin = session.query(Coin).get(coin)\n            session.expunge(coin)\n            return coin\n\n    def set_current_coin(self, coin: Union[Coin, str]):\n        coin = self.get_coin(coin)\n        session: Session\n        with self.db_session() as session:\n            if isinstance(coin, Coin):\n                coin = session.merge(coin)\n            cc = CurrentCoin(coin)\n            session.add(cc)\n            self.send_update(cc)\n\n    def get_current_coin(self) -> Optional[Coin]:\n        session: Session\n        with self.db_session() as session:\n            current_coin = session.query(CurrentCoin).order_by(CurrentCoin.datetime.desc()).first()\n            if current_coin is None:\n                return None\n            coin = current_coin.coin\n            session.expunge(coin)\n            return coin\n\n    def get_pair(self, from_coin: Union[Coin, str], to_coin: Union[Coin, str]):\n        from_coin = self.get_coin(from_coin)\n        to_coin = self.get_coin(to_coin)\n        session: Session\n        with self.db_session() as session:\n            pair: Pair = session.query(Pair).filter(Pair.from_coin == from_coin, Pair.to_coin == to_coin).first()\n            session.expunge(pair)\n            return pair\n\n    def get_pairs_from(self, from_coin: Union[Coin, str], only_enabled=True) -> List[Pair]:\n        from_coin = self.get_coin(from_coin)\n        session: Session\n        with self.db_session() as session:\n            pairs = session.query(Pair).filter(Pair.from_coin == from_coin)\n            if only_enabled:\n                pairs = pairs.filter(Pair.enabled.is_(True))\n            pairs = pairs.all()\n            session.expunge_all()\n            return pairs\n\n    def get_pairs(self, only_enabled=True) -> List[Pair]:\n        session: Session\n        with self.db_session() as session:\n            pairs = session.query(Pair)\n            if only_enabled:\n                pairs = pairs.filter(Pair.enabled.is_(True))\n            pairs = pairs.all()\n            session.expunge_all()\n            return pairs\n\n    def log_scout(\n        self,\n        pair: Pair,\n        target_ratio: float,\n        current_coin_price: float,\n        other_coin_price: float,\n    ):\n        session: Session\n        with self.db_session() as session:\n            pair = session.merge(pair)\n            sh = ScoutHistory(pair, target_ratio, current_coin_price, other_coin_price)\n            session.add(sh)\n            self.send_update(sh)\n\n    def prune_scout_history(self):\n        time_diff = datetime.now() - timedelta(hours=self.config.SCOUT_HISTORY_PRUNE_TIME)\n        session: Session\n        with self.db_session() as session:\n            session.query(ScoutHistory).filter(ScoutHistory.datetime < time_diff).delete()\n\n    def prune_value_history(self):\n        session: Session\n        with self.db_session() as session:\n            # Sets the first entry for each coin for each hour as 'hourly'\n            hourly_entries: List[CoinValue] = (\n                session.query(CoinValue).group_by(CoinValue.coin_id, func.strftime(\"%H\", CoinValue.datetime)).all()\n            )\n            for entry in hourly_entries:\n                entry.interval = Interval.HOURLY\n\n            # Sets the first entry for each coin for each day as 'daily'\n            daily_entries: List[CoinValue] = (\n                session.query(CoinValue).group_by(CoinValue.coin_id, func.date(CoinValue.datetime)).all()\n            )\n            for entry in daily_entries:\n                entry.interval = Interval.DAILY\n\n            # Sets the first entry for each coin for each month as 'weekly'\n            # (Sunday is the start of the week)\n            weekly_entries: List[CoinValue] = (\n                session.query(CoinValue).group_by(CoinValue.coin_id, func.strftime(\"%Y-%W\", CoinValue.datetime)).all()\n            )\n            for entry in weekly_entries:\n                entry.interval = Interval.WEEKLY\n\n            # The last 24 hours worth of minutely entries will be kept, so\n            # count(coins) * 1440 entries\n            time_diff = datetime.now() - timedelta(hours=24)\n            session.query(CoinValue).filter(\n                CoinValue.interval == Interval.MINUTELY, CoinValue.datetime < time_diff\n            ).delete()\n\n            # The last 28 days worth of hourly entries will be kept, so count(coins) * 672 entries\n            time_diff = datetime.now() - timedelta(days=28)\n            session.query(CoinValue).filter(\n                CoinValue.interval == Interval.HOURLY, CoinValue.datetime < time_diff\n            ).delete()\n\n            # The last years worth of daily entries will be kept, so count(coins) * 365 entries\n            time_diff = datetime.now() - timedelta(days=365)\n            session.query(CoinValue).filter(\n                CoinValue.interval == Interval.DAILY, CoinValue.datetime < time_diff\n            ).delete()\n\n            # All weekly entries will be kept forever\n\n    def create_database(self):\n        Base.metadata.create_all(self.engine)\n\n    def start_trade_log(self, from_coin: Coin, to_coin: Coin, selling: bool):\n        return TradeLog(self, from_coin, to_coin, selling)\n\n    def send_update(self, model):\n        if not self.socketio_connect():\n            return\n\n        self.socketio_client.emit(\n            \"update\",\n            {\"table\": model.__tablename__, \"data\": model.info()},\n            namespace=\"/backend\",\n        )\n\n    def migrate_old_state(self):\n        \"\"\"\n        For migrating from old dotfile format to SQL db. This method should be removed in\n        the future.\n        \"\"\"\n        if os.path.isfile(\".current_coin\"):\n            with open(\".current_coin\") as f:\n                coin = f.read().strip()\n                self.logger.info(f\".current_coin file found, loading current coin {coin}\")\n                self.set_current_coin(coin)\n            os.rename(\".current_coin\", \".current_coin.old\")\n            self.logger.info(f\".current_coin renamed to .current_coin.old - You can now delete this file\")\n\n        if os.path.isfile(\".current_coin_table\"):\n            with open(\".current_coin_table\") as f:\n                self.logger.info(f\".current_coin_table file found, loading into database\")\n                table: dict = json.load(f)\n                session: Session\n                with self.db_session() as session:\n                    for from_coin, to_coin_dict in table.items():\n                        for to_coin, ratio in to_coin_dict.items():\n                            if from_coin == to_coin:\n                                continue\n                            pair = session.merge(self.get_pair(from_coin, to_coin))\n                            pair.ratio = ratio\n                            session.add(pair)\n\n            os.rename(\".current_coin_table\", \".current_coin_table.old\")\n            self.logger.info(\".current_coin_table renamed to .current_coin_table.old - \" \"You can now delete this file\")\n\n\nclass TradeLog:\n    def __init__(self, db: Database, from_coin: Coin, to_coin: Coin, selling: bool):\n        self.db = db\n        session: Session\n        with self.db.db_session() as session:\n            from_coin = session.merge(from_coin)\n            to_coin = session.merge(to_coin)\n            self.trade = Trade(from_coin, to_coin, selling)\n            session.add(self.trade)\n            # Flush so that SQLAlchemy fills in the id column\n            session.flush()\n            self.db.send_update(self.trade)\n\n    def set_ordered(self, alt_starting_balance, crypto_starting_balance, alt_trade_amount):\n        session: Session\n        with self.db.db_session() as session:\n            trade: Trade = session.merge(self.trade)\n            trade.alt_starting_balance = alt_starting_balance\n            trade.alt_trade_amount = alt_trade_amount\n            trade.crypto_starting_balance = crypto_starting_balance\n            trade.state = TradeState.ORDERED\n            self.db.send_update(trade)\n\n    def set_complete(self, crypto_trade_amount):\n        session: Session\n        with self.db.db_session() as session:\n            trade: Trade = session.merge(self.trade)\n            trade.crypto_trade_amount = crypto_trade_amount\n            trade.state = TradeState.COMPLETE\n            self.db.send_update(trade)\n\n\nif __name__ == \"__main__\":\n    database = Database(Logger(), Config())\n    database.create_database()\n"
  },
  {
    "path": "binance_trade_bot/logger.py",
    "content": "import logging.handlers\n\nfrom .notifications import NotificationHandler\n\n\nclass Logger:\n    Logger = None\n    NotificationHandler = None\n\n    def __init__(self, logging_service=\"crypto_trading\", enable_notifications=True):\n        # Logger setup\n        self.Logger = logging.getLogger(f\"{logging_service}_logger\")\n        self.Logger.setLevel(logging.DEBUG)\n        self.Logger.propagate = False\n        formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n        # default is \"logs/crypto_trading.log\"\n        fh = logging.FileHandler(f\"logs/{logging_service}.log\")\n        fh.setLevel(logging.DEBUG)\n        fh.setFormatter(formatter)\n        self.Logger.addHandler(fh)\n\n        # logging to console\n        ch = logging.StreamHandler()\n        ch.setLevel(logging.INFO)\n        ch.setFormatter(formatter)\n        self.Logger.addHandler(ch)\n\n        # notification handler\n        self.NotificationHandler = NotificationHandler(enable_notifications)\n\n    def log(self, message, level=\"info\", notification=True):\n        if level == \"info\":\n            self.Logger.info(message)\n        elif level == \"warning\":\n            self.Logger.warning(message)\n        elif level == \"error\":\n            self.Logger.error(message)\n        elif level == \"debug\":\n            self.Logger.debug(message)\n\n        if notification and self.NotificationHandler.enabled:\n            self.NotificationHandler.send_notification(str(message))\n\n    def info(self, message, notification=True):\n        self.log(message, \"info\", notification)\n\n    def warning(self, message, notification=True):\n        self.log(message, \"warning\", notification)\n\n    def error(self, message, notification=True):\n        self.log(message, \"error\", notification)\n\n    def debug(self, message, notification=False):\n        self.log(message, \"debug\", notification)\n"
  },
  {
    "path": "binance_trade_bot/models/__init__.py",
    "content": "from .base import Base\nfrom .coin import Coin\nfrom .coin_value import CoinValue, Interval\nfrom .current_coin import CurrentCoin\nfrom .pair import Pair\nfrom .scout_history import ScoutHistory\nfrom .trade import Trade, TradeState\n"
  },
  {
    "path": "binance_trade_bot/models/base.py",
    "content": "from sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n"
  },
  {
    "path": "binance_trade_bot/models/coin.py",
    "content": "from sqlalchemy import Boolean, Column, String\n\nfrom .base import Base\n\n\nclass Coin(Base):\n    __tablename__ = \"coins\"\n    symbol = Column(String, primary_key=True)\n    enabled = Column(Boolean)\n\n    def __init__(self, symbol, enabled=True):\n        self.symbol = symbol\n        self.enabled = enabled\n\n    def __add__(self, other):\n        if isinstance(other, str):\n            return self.symbol + other\n        if isinstance(other, Coin):\n            return self.symbol + other.symbol\n        raise TypeError(f\"unsupported operand type(s) for +: 'Coin' and '{type(other)}'\")\n\n    def __repr__(self):\n        return f\"[{self.symbol}]\"\n\n    def info(self):\n        return {\"symbol\": self.symbol, \"enabled\": self.enabled}\n"
  },
  {
    "path": "binance_trade_bot/models/coin_value.py",
    "content": "import enum\nfrom datetime import datetime as _datetime\n\nfrom sqlalchemy import Column, DateTime, Enum, Float, ForeignKey, Integer, String\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom sqlalchemy.orm import relationship\n\nfrom .base import Base\nfrom .coin import Coin\n\n\nclass Interval(enum.Enum):\n    MINUTELY = \"MINUTELY\"\n    HOURLY = \"HOURLY\"\n    DAILY = \"DAILY\"\n    WEEKLY = \"WEEKLY\"\n\n\nclass CoinValue(Base):\n    __tablename__ = \"coin_value\"\n\n    id = Column(Integer, primary_key=True)\n\n    coin_id = Column(String, ForeignKey(\"coins.symbol\"))\n    coin = relationship(\"Coin\")\n\n    balance = Column(Float)\n    usd_price = Column(Float)\n    btc_price = Column(Float)\n\n    interval = Column(Enum(Interval))\n\n    datetime = Column(DateTime)\n\n    def __init__(\n        self,\n        coin: Coin,\n        balance: float,\n        usd_price: float,\n        btc_price: float,\n        interval=Interval.MINUTELY,\n        datetime: _datetime = None,\n    ):\n        self.coin = coin\n        self.balance = balance\n        self.usd_price = usd_price\n        self.btc_price = btc_price\n        self.interval = interval\n        self.datetime = datetime or _datetime.now()\n\n    @hybrid_property\n    def usd_value(self):\n        if self.usd_price is None:\n            return None\n        return self.balance * self.usd_price\n\n    @usd_value.expression\n    def usd_value(self):\n        return self.balance * self.usd_price\n\n    @hybrid_property\n    def btc_value(self):\n        if self.btc_price is None:\n            return None\n        return self.balance * self.btc_price\n\n    @btc_value.expression\n    def btc_value(self):\n        return self.balance * self.btc_price\n\n    def info(self):\n        return {\n            \"balance\": self.balance,\n            \"usd_value\": self.usd_value,\n            \"btc_value\": self.btc_value,\n            \"datetime\": self.datetime.isoformat(),\n        }\n"
  },
  {
    "path": "binance_trade_bot/models/current_coin.py",
    "content": "from datetime import datetime\n\nfrom sqlalchemy import Column, DateTime, ForeignKey, Integer, String\nfrom sqlalchemy.orm import relationship\n\nfrom .base import Base\nfrom .coin import Coin\n\n\nclass CurrentCoin(Base):  # pylint: disable=too-few-public-methods\n    __tablename__ = \"current_coin_history\"\n    id = Column(Integer, primary_key=True)\n    coin_id = Column(String, ForeignKey(\"coins.symbol\"))\n    coin = relationship(\"Coin\")\n    datetime = Column(DateTime)\n\n    def __init__(self, coin: Coin):\n        self.coin = coin\n        self.datetime = datetime.utcnow()\n\n    def info(self):\n        return {\"datetime\": self.datetime.isoformat(), \"coin\": self.coin.info()}\n"
  },
  {
    "path": "binance_trade_bot/models/pair.py",
    "content": "from sqlalchemy import Column, Float, ForeignKey, Integer, String, func, or_, select\nfrom sqlalchemy.orm import column_property, relationship\n\nfrom .base import Base\nfrom .coin import Coin\n\n\nclass Pair(Base):\n    __tablename__ = \"pairs\"\n\n    id = Column(Integer, primary_key=True)\n\n    from_coin_id = Column(String, ForeignKey(\"coins.symbol\"))\n    from_coin = relationship(\"Coin\", foreign_keys=[from_coin_id], lazy=\"joined\")\n\n    to_coin_id = Column(String, ForeignKey(\"coins.symbol\"))\n    to_coin = relationship(\"Coin\", foreign_keys=[to_coin_id], lazy=\"joined\")\n\n    ratio = Column(Float)\n\n    enabled = column_property(\n        select([func.count(Coin.symbol) == 2])\n        .where(or_(Coin.symbol == from_coin_id, Coin.symbol == to_coin_id))\n        .where(Coin.enabled.is_(True))\n        .scalar_subquery()\n    )\n\n    def __init__(self, from_coin: Coin, to_coin: Coin, ratio=None):\n        self.from_coin = from_coin\n        self.to_coin = to_coin\n        self.ratio = ratio\n\n    def __repr__(self):\n        return f\"<{self.from_coin_id}->{self.to_coin_id} :: {self.ratio}>\"\n\n    def info(self):\n        return {\n            \"from_coin\": self.from_coin.info(),\n            \"to_coin\": self.to_coin.info(),\n            \"ratio\": self.ratio,\n        }\n"
  },
  {
    "path": "binance_trade_bot/models/scout_history.py",
    "content": "from datetime import datetime\n\nfrom sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom sqlalchemy.orm import relationship\n\nfrom .base import Base\nfrom .pair import Pair\n\n\nclass ScoutHistory(Base):\n    __tablename__ = \"scout_history\"\n\n    id = Column(Integer, primary_key=True)\n\n    pair_id = Column(String, ForeignKey(\"pairs.id\"))\n    pair = relationship(\"Pair\")\n\n    target_ratio = Column(Float)\n    current_coin_price = Column(Float)\n    other_coin_price = Column(Float)\n\n    datetime = Column(DateTime)\n\n    def __init__(\n        self,\n        pair: Pair,\n        target_ratio: float,\n        current_coin_price: float,\n        other_coin_price: float,\n    ):\n        self.pair = pair\n        self.target_ratio = target_ratio\n        self.current_coin_price = current_coin_price\n        self.other_coin_price = other_coin_price\n        self.datetime = datetime.utcnow()\n\n    @hybrid_property\n    def current_ratio(self):\n        return self.current_coin_price / self.other_coin_price\n\n    def info(self):\n        return {\n            \"from_coin\": self.pair.from_coin.info(),\n            \"to_coin\": self.pair.to_coin.info(),\n            \"current_ratio\": self.current_ratio,\n            \"target_ratio\": self.target_ratio,\n            \"current_coin_price\": self.current_coin_price,\n            \"other_coin_price\": self.other_coin_price,\n            \"datetime\": self.datetime.isoformat(),\n        }\n"
  },
  {
    "path": "binance_trade_bot/models/trade.py",
    "content": "import enum\nfrom datetime import datetime\n\nfrom sqlalchemy import Boolean, Column, DateTime, Enum, Float, ForeignKey, Integer, String\nfrom sqlalchemy.orm import relationship\n\nfrom .base import Base\nfrom .coin import Coin\n\n\nclass TradeState(enum.Enum):\n    STARTING = \"STARTING\"\n    ORDERED = \"ORDERED\"\n    COMPLETE = \"COMPLETE\"\n\n\nclass Trade(Base):  # pylint: disable=too-few-public-methods\n    __tablename__ = \"trade_history\"\n\n    id = Column(Integer, primary_key=True)\n\n    alt_coin_id = Column(String, ForeignKey(\"coins.symbol\"))\n    alt_coin = relationship(\"Coin\", foreign_keys=[alt_coin_id], lazy=\"joined\")\n\n    crypto_coin_id = Column(String, ForeignKey(\"coins.symbol\"))\n    crypto_coin = relationship(\"Coin\", foreign_keys=[crypto_coin_id], lazy=\"joined\")\n\n    selling = Column(Boolean)\n\n    state = Column(Enum(TradeState))\n\n    alt_starting_balance = Column(Float)\n    alt_trade_amount = Column(Float)\n    crypto_starting_balance = Column(Float)\n    crypto_trade_amount = Column(Float)\n\n    datetime = Column(DateTime)\n\n    def __init__(self, alt_coin: Coin, crypto_coin: Coin, selling: bool):\n        self.alt_coin = alt_coin\n        self.crypto_coin = crypto_coin\n        self.state = TradeState.STARTING\n        self.selling = selling\n        self.datetime = datetime.utcnow()\n\n    def info(self):\n        return {\n            \"id\": self.id,\n            \"alt_coin\": self.alt_coin.info(),\n            \"crypto_coin\": self.crypto_coin.info(),\n            \"selling\": self.selling,\n            \"state\": self.state.value,\n            \"alt_starting_balance\": self.alt_starting_balance,\n            \"alt_trade_amount\": self.alt_trade_amount,\n            \"crypto_starting_balance\": self.crypto_starting_balance,\n            \"crypto_trade_amount\": self.crypto_trade_amount,\n            \"datetime\": self.datetime.isoformat(),\n        }\n"
  },
  {
    "path": "binance_trade_bot/notifications.py",
    "content": "import queue\nimport threading\nfrom os import path\n\nimport apprise\n\nAPPRISE_CONFIG_PATH = \"config/apprise.yml\"\n\n\nclass NotificationHandler:\n    def __init__(self, enabled=True):\n        if enabled and path.exists(APPRISE_CONFIG_PATH):\n            self.apobj = apprise.Apprise()\n            config = apprise.AppriseConfig()\n            config.add(APPRISE_CONFIG_PATH)\n            self.apobj.add(config)\n            self.queue = queue.Queue()\n            self.start_worker()\n            self.enabled = True\n        else:\n            self.enabled = False\n\n    def start_worker(self):\n        threading.Thread(target=self.process_queue, daemon=True).start()\n\n    def process_queue(self):\n        while True:\n            message, attachments = self.queue.get()\n\n            if attachments:\n                self.apobj.notify(body=message, attach=attachments)\n            else:\n                self.apobj.notify(body=message)\n            self.queue.task_done()\n\n    def send_notification(self, message, attachments=None):\n        if self.enabled:\n            self.queue.put((message, attachments or []))\n"
  },
  {
    "path": "binance_trade_bot/scheduler.py",
    "content": "import datetime\nimport logging\nfrom traceback import format_exc\n\nfrom schedule import Job, Scheduler\n\n\nclass SafeScheduler(Scheduler):\n    \"\"\"\n    An implementation of Scheduler that catches jobs that fail, logs their\n    exception tracebacks as errors, and keeps going.\n\n    Use this to run jobs that may or may not crash without worrying about\n    whether other jobs will run or if they'll crash the entire script.\n    \"\"\"\n\n    def __init__(self, logger: logging.Logger, rerun_immediately=True):\n        self.logger = logger\n        self.rerun_immediately = rerun_immediately\n\n        super().__init__()\n\n    def _run_job(self, job: Job):\n        try:\n            super()._run_job(job)\n        except Exception:  # pylint: disable=broad-except\n            self.logger.error(f\"Error while {next(iter(job.tags))}...\\n{format_exc()}\")\n            job.last_run = datetime.datetime.now()\n            if not self.rerun_immediately:\n                # Reschedule the job for the next time it was meant to run, instead of\n                # letting it run\n                # next tick\n                job._schedule_next_run()  # pylint: disable=protected-access\n"
  },
  {
    "path": "binance_trade_bot/strategies/README.md",
    "content": "# Strategies\nYou can add your own strategy to this folder. The filename must end with `_strategy.py`,\nand contain the following:\n\n```python\nfrom binance_trade_bot.auto_trader import AutoTrader\n\nclass Strategy(AutoTrader):\n\n    def scout(self):\n        # Your custom scout method\n\n```\n\nThen, set your `strategy` configuration to your strategy name. If you named your file\n`custom_strategy.py`, you'd need to put `strategy=custom` in your config file.\n\nYou can put your strategy in a subfolder, and the bot will still find it. If you'd like to\nshare your strategy with others, try using git submodules.\n\nSome premade strategies are listed below:\n## `default`\n\n## `multiple_coins`\nThe bot is less likely to get stuck\n"
  },
  {
    "path": "binance_trade_bot/strategies/__init__.py",
    "content": "import importlib\nimport os\n\n\ndef get_strategy(name):\n    for dirpath, _, filenames in os.walk(os.path.dirname(__file__)):\n        filename: str\n        for filename in filenames:\n            if filename.endswith(\"_strategy.py\"):\n                if filename.replace(\"_strategy.py\", \"\") == name:\n                    spec = importlib.util.spec_from_file_location(name, os.path.join(dirpath, filename))\n                    module = importlib.util.module_from_spec(spec)\n                    spec.loader.exec_module(module)\n                    return module.Strategy\n    return None\n"
  },
  {
    "path": "binance_trade_bot/strategies/default_strategy.py",
    "content": "import random\nimport sys\nfrom datetime import datetime\n\nfrom binance_trade_bot.auto_trader import AutoTrader\n\n\nclass Strategy(AutoTrader):\n    def initialize(self):\n        super().initialize()\n        self.initialize_current_coin()\n\n    def scout(self):\n        \"\"\"\n        Scout for potential jumps from the current coin to another coin\n        \"\"\"\n        current_coin = self.db.get_current_coin()\n        # Display on the console, the current coin+Bridge, so users can see *some* activity and not think the bot has\n        # stopped. Not logging though to reduce log size.\n        print(\n            f\"{datetime.now()} - CONSOLE - INFO - I am scouting the best trades. \"\n            f\"Current coin: {current_coin + self.config.BRIDGE} \",\n            end=\"\\r\",\n        )\n\n        current_coin_price = self.manager.get_ticker_price(current_coin + self.config.BRIDGE)\n\n        if current_coin_price is None:\n            self.logger.info(f\"Skipping scouting... current coin {current_coin + self.config.BRIDGE} not found\")\n            return\n\n        self._jump_to_best_coin(current_coin, current_coin_price)\n\n    def bridge_scout(self):\n        current_coin = self.db.get_current_coin()\n        if self.manager.get_currency_balance(current_coin.symbol) > self.manager.get_min_notional(\n            current_coin.symbol, self.config.BRIDGE.symbol\n        ):\n            # Only scout if we don't have enough of the current coin\n            return\n        new_coin = super().bridge_scout()\n        if new_coin is not None:\n            self.db.set_current_coin(new_coin)\n\n    def initialize_current_coin(self):\n        \"\"\"\n        Decide what is the current coin, and set it up in the DB.\n        \"\"\"\n        if self.db.get_current_coin() is None:\n            current_coin_symbol = self.config.CURRENT_COIN_SYMBOL\n            if not current_coin_symbol:\n                current_coin_symbol = random.choice(self.config.SUPPORTED_COIN_LIST)\n\n            self.logger.info(f\"Setting initial coin to {current_coin_symbol}\")\n\n            if current_coin_symbol not in self.config.SUPPORTED_COIN_LIST:\n                sys.exit(\"***\\nERROR!\\nSince there is no backup file, a proper coin name must be provided at init\\n***\")\n            self.db.set_current_coin(current_coin_symbol)\n\n            # if we don't have a configuration, we selected a coin at random... Buy it so we can start trading.\n            if self.config.CURRENT_COIN_SYMBOL == \"\":\n                current_coin = self.db.get_current_coin()\n                self.logger.info(f\"Purchasing {current_coin} to begin trading\")\n                self.manager.buy_alt(current_coin, self.config.BRIDGE)\n                self.logger.info(\"Ready to start trading\")\n"
  },
  {
    "path": "binance_trade_bot/strategies/multiple_coins_strategy.py",
    "content": "from datetime import datetime\n\nfrom binance_trade_bot.auto_trader import AutoTrader\n\n\nclass Strategy(AutoTrader):\n    def scout(self):\n        \"\"\"\n        Scout for potential jumps from the current coin to another coin\n        \"\"\"\n        have_coin = False\n\n        # last coin bought\n        current_coin = self.db.get_current_coin()\n        current_coin_symbol = \"\"\n\n        if current_coin is not None:\n            current_coin_symbol = current_coin.symbol\n\n        for coin in self.db.get_coins():\n            current_coin_balance = self.manager.get_currency_balance(coin.symbol)\n            coin_price = self.manager.get_ticker_price(coin + self.config.BRIDGE)\n\n            if coin_price is None:\n                self.logger.info(f\"Skipping scouting... current coin {coin + self.config.BRIDGE} not found\")\n                continue\n\n            min_notional = self.manager.get_min_notional(coin.symbol, self.config.BRIDGE.symbol)\n\n            if coin.symbol != current_coin_symbol and coin_price * current_coin_balance < min_notional:\n                continue\n\n            have_coin = True\n\n            # Display on the console, the current coin+Bridge, so users can see *some* activity and not think the bot\n            # has stopped. Not logging though to reduce log size.\n            print(\n                f\"{datetime.now()} - CONSOLE - INFO - I am scouting the best trades. \"\n                f\"Current coin: {coin + self.config.BRIDGE} \",\n                end=\"\\r\",\n            )\n\n            self._jump_to_best_coin(coin, coin_price)\n\n        if not have_coin:\n            self.bridge_scout()\n"
  },
  {
    "path": "config/apprise_example.yml",
    "content": "# Define version\nversion: 1\n\n# Define your URLs (Mandatory!)\n# URLs should start with - (remove the comment symbol #)\n# Replace the values with your tokens/ids\n# For example a telegram URL would look like:\n# - tgram://123456789:AABx8iXjE5C-vG4SDhf6ARgdFgxYxhuHb4A/-606743502\n# Rename the file to `apprise.yml`\nurls:\n  # - tgram://TOKEN/CHAT_ID\n  # - discord://WebhookID/WebhookToken/\n  # - slack://tokenA/tokenB/tokenC\n  # More options here: https://github.com/caronc/apprise\n"
  },
  {
    "path": "dev-requirements.txt",
    "content": "pylint-sqlalchemy\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3\"\n\nservices:\n  crypto-trading:\n    image: edeng23/binance-trade-bot\n    container_name: binance_trader\n    working_dir: /app\n    volumes:\n      - ./user.cfg:/app/user.cfg\n      - ./supported_coin_list:/app/supported_coin_list\n      - ./data:/app/data\n      - ./logs:/app/logs\n      - ./config:/app/config\n    command: python -m binance_trade_bot\n    environment:\n      - PYTHONUNBUFFERED=1\n\n  api:\n    image: edeng23/binance-trade-bot\n    container_name: binance_trader_api\n    working_dir: /app\n    volumes:\n      - ./user.cfg:/app/user.cfg\n      - ./data:/app/data\n      - ./logs:/app/logs\n    ports:\n      - 5123:5123\n    command: gunicorn binance_trade_bot.api_server:app -k eventlet -w 1 --threads 1 -b 0.0.0.0:5123\n    depends_on:\n      - crypto-trading\n\n  sqlitebrowser:\n    image: ghcr.io/linuxserver/sqlitebrowser\n    container_name: sqlitebrowser\n    environment:\n      - PUID=1000\n      - PGID=1000\n      - TZ=Europe/Berlin\n    volumes:\n      - ./data/config:/config\n      - ./data:/data\n    ports:\n      - 3000:3000\n"
  },
  {
    "path": "logs/.gitkeep",
    "content": ""
  },
  {
    "path": "requirements.txt",
    "content": "python-binance==1.0.27\nsqlalchemy==1.4.15\nschedule==1.1.0\napprise==0.9.5.1\nFlask==2.3.2\ngunicorn==20.1.0\nflask-cors==3.0.10\nflask-socketio==5.0.1\neventlet==0.30.2\npython-socketio[client]==5.2.1\ncachetools==4.2.2\nsqlitedict==1.7.0\nunicorn-binance-websocket-api==1.34.2\nunicorn-fy==0.11.0\nitsdangerous==2.0.1\nWerkzeug==2.0.3"
  },
  {
    "path": "runtime.txt",
    "content": "python-3.8.11\n"
  },
  {
    "path": "supported_coin_list",
    "content": "ADA\nATOM\nBAT\nBTTC\nDASH\nDOGE\nEOS\nETC\nICX\nIOTA\nNEO\nOMG\nONT\nQTUM\nTRX\nVET\nXLM\nXMR\n"
  }
]