├── .do └── deploy.template.yaml ├── .github └── workflows │ └── cicd.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── .pre-commit-hooks └── sort-coins-file.py ├── .pylintrc ├── .user.cfg.example ├── Dockerfile ├── LICENSE ├── Procfile ├── README.md ├── app.json ├── backtest.py ├── binance_trade_bot ├── __init__.py ├── __main__.py ├── api_server.py ├── auto_trader.py ├── backtest.py ├── binance_api_manager.py ├── binance_stream_manager.py ├── config.py ├── crypto_trading.py ├── database.py ├── logger.py ├── models │ ├── __init__.py │ ├── base.py │ ├── coin.py │ ├── coin_value.py │ ├── current_coin.py │ ├── pair.py │ ├── scout_history.py │ └── trade.py ├── notifications.py ├── scheduler.py └── strategies │ ├── README.md │ ├── __init__.py │ ├── default_strategy.py │ └── multiple_coins_strategy.py ├── config └── apprise_example.yml ├── data └── .gitignore ├── dev-requirements.txt ├── docker-compose.yml ├── logs └── .gitkeep ├── requirements.txt ├── runtime.txt └── supported_coin_list /.do/deploy.template.yaml: -------------------------------------------------------------------------------- 1 | spec: 2 | name: binance-trade-bot 3 | workers: 4 | - environment_slug: python 5 | git: 6 | branch: master 7 | repo_clone_url: https://github.com/coinbookbrasil/binance-trade-bot.git 8 | envs: 9 | - key: API_KEY 10 | scope: BUILD_TIME 11 | value: "API KEY BINANCE" 12 | - key: API_SECRET_KEY 13 | scope: BUILD_TIME 14 | value: "API_SECRET_KEY" 15 | - key: CURRENT_COIN_SYMBOL 16 | scope: BUILD_TIME 17 | value: "XMR" 18 | - key: BRIDGE_SYMBOL 19 | scope: BUILD_TIME 20 | value: "USDT" 21 | - key: TLD 22 | scope: BUILD_TIME 23 | value: "com" 24 | - key: SCOUT_MULTIPLIER 25 | scope: BUILD_TIME 26 | value: "1" 27 | - key: HOURS_TO_KEEP_SCOUTING_HISTORY 28 | scope: BUILD_TIME 29 | value: "1" 30 | - key: STRATEGY 31 | scope: BUILD_TIME 32 | value: "default" 33 | - key: BUY_TIMEOUT 34 | scope: BUILD_TIME 35 | value: "0" 36 | - key: SELL_TIMEOUT 37 | scope: BUILD_TIME 38 | value: "0" 39 | - key: SUPPORTED_COIN_LIST 40 | scope: BUILD_TIME 41 | value: "ADA ATOM BAT BTT DASH DOGE EOS ETC ICX IOTA NEO OMG ONT QTUM TRX VET XLM XMR" 42 | name: binance-trade-bot 43 | -------------------------------------------------------------------------------- /.github/workflows/cicd.yaml: -------------------------------------------------------------------------------- 1 | name: binance-trade-bot 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - "*" 9 | 10 | jobs: 11 | Lint: 12 | runs-on: ubuntu-20.04 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Set up Python 16 | uses: actions/setup-python@v2 17 | with: 18 | python-version: 3.7 19 | - id: changed-files 20 | name: Get Changed Files 21 | uses: dorny/paths-filter@v2 22 | with: 23 | token: ${{ github.token }} 24 | list-files: shell 25 | filters: | 26 | repo: 27 | - added|modified: 28 | - '**' 29 | - name: Set Cache Key 30 | run: echo "PY=$(python --version --version | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV 31 | - uses: actions/cache@v2 32 | with: 33 | path: ~/.cache/pre-commit 34 | key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }} 35 | - name: Check ALL Files On Branch 36 | uses: pre-commit/action@v2.0.0 37 | if: github.event_name != 'pull_request' 38 | - name: Check Changed Files On PR 39 | uses: pre-commit/action@v2.0.0 40 | if: github.event_name == 'pull_request' 41 | with: 42 | extra_args: --files ${{ steps.changed-files.outputs.repo_files }} 43 | 44 | Docker: 45 | runs-on: ubuntu-latest 46 | needs: Lint 47 | steps: 48 | - name: Set up QEMU 49 | uses: docker/setup-qemu-action@v1 50 | - name: Set up Docker Buildx 51 | uses: docker/setup-buildx-action@v1 52 | - name: Login to DockerHub 53 | if: github.event_name == 'push' 54 | uses: docker/login-action@v1 55 | with: 56 | username: ${{ secrets.DOCKERHUB_USERNAME }} 57 | password: ${{ secrets.DOCKERHUB_TOKEN }} 58 | - name: Build and push 59 | id: docker_build 60 | uses: docker/build-push-action@v2 61 | with: 62 | platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7 63 | push: ${{ github.event_name == 'push' }} 64 | tags: ${{ github.repository }}:latest 65 | - name: Image digest 66 | run: echo ${{ steps.docker_build.outputs.digest }} 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .current_coin 3 | .current_coin_table 4 | *.pyc 5 | __pycache__ 6 | nohup.out 7 | user.cfg 8 | .idea/ 9 | .vscode/ 10 | .replit 11 | venv/ 12 | crypto_trading.db 13 | apprise.yml 14 | .DS_Store 15 | .bot/ -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | minimum_pre_commit_version: 1.15.2 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v4.1.0 6 | hooks: 7 | - id: check-merge-conflict # Check for files that contain merge conflict strings. 8 | - id: trailing-whitespace # Trims trailing whitespace. 9 | args: [--markdown-linebreak-ext=md] 10 | - id: mixed-line-ending # Replaces or checks mixed line ending. 11 | args: [--fix=lf] 12 | - id: end-of-file-fixer # Makes sure files end in a newline and only a newline. 13 | - id: check-merge-conflict # Check for files that contain merge conflict strings. 14 | - id: check-ast # Simply check whether files parse as valid python. 15 | 16 | - repo: local 17 | hooks: 18 | - id: sort-supported-coin-list 19 | name: Sort Supported Coin List 20 | entry: .pre-commit-hooks/sort-coins-file.py 21 | language: python 22 | files: ^supported_coin_list$ 23 | 24 | - repo: https://github.com/asottile/pyupgrade 25 | rev: v2.29.1 26 | hooks: 27 | - id: pyupgrade 28 | name: Rewrite Code to be Py3.6+ 29 | args: [--py36-plus] 30 | 31 | - repo: https://github.com/pycqa/isort 32 | rev: 5.11.5 33 | hooks: 34 | - id: isort 35 | args: [--profile, black, --line-length, '120'] 36 | 37 | - repo: https://github.com/psf/black 38 | rev: 23.3.0 39 | hooks: 40 | - id: black 41 | args: [-l, '120'] 42 | 43 | - repo: https://github.com/asottile/blacken-docs 44 | rev: v1.11.0 45 | hooks: 46 | - id: blacken-docs 47 | args: [--skip-errors] 48 | files: ^docs/.*\.rst 49 | additional_dependencies: [black==20.8b1] 50 | 51 | - repo: https://github.com/s0undt3ch/pre-commit-populate-pylint-requirements 52 | rev: aed8c6a 53 | hooks: 54 | - id: populate-pylint-requirements 55 | files: ^(dev-)?requirements\.txt$ 56 | args: [requirements.txt, dev-requirements.txt] 57 | 58 | - repo: https://github.com/pre-commit/mirrors-pylint 59 | rev: v3.0.0a5 60 | hooks: 61 | - id: pylint 62 | name: PyLint 63 | args: [--output-format=parseable, --rcfile=.pylintrc] 64 | additional_dependencies: 65 | - Flask==2.1.1 66 | - apprise==0.9.5.1 67 | - cachetools==4.2.2 68 | - eventlet==0.30.2 69 | - flask-cors==3.0.10 70 | - flask-socketio==5.0.1 71 | - gunicorn==20.1.0 72 | - itsdangerous==2.0.1 73 | - pylint-sqlalchemy 74 | - python-binance==1.0.12 75 | - python-socketio[client]==5.2.1 76 | - schedule==1.1.0 77 | - sqlalchemy==1.4.15 78 | - sqlitedict==1.7.0 79 | - unicorn-binance-websocket-api==1.34.2 80 | - unicorn-fy==0.11.0 81 | -------------------------------------------------------------------------------- /.pre-commit-hooks/sort-coins-file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # pylint: skip-file 3 | import pathlib 4 | 5 | REPO_ROOT = pathlib.Path(__name__).resolve().parent 6 | SUPPORTED_COIN_LIST = REPO_ROOT / "supported_coin_list" 7 | 8 | 9 | def sort(): 10 | in_contents = SUPPORTED_COIN_LIST.read_text() 11 | out_contents = "" 12 | out_contents += "\n".join(sorted(line.upper() for line in in_contents.splitlines())) 13 | out_contents += "\n" 14 | if in_contents != out_contents: 15 | SUPPORTED_COIN_LIST.write_text(out_contents) 16 | 17 | 18 | if __name__ == "__main__": 19 | sort() 20 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # A comma-separated list of package or module names from where C extensions may 4 | # be loaded. Extensions are loading into the active Python interpreter and may 5 | # run arbitrary code. 6 | extension-pkg-whitelist= 7 | 8 | # Specify a score threshold to be exceeded before program exits with error. 9 | fail-under=6.0 10 | 11 | # Add files or directories to the blacklist. They should be base names, not 12 | # paths. 13 | ignore=CVS 14 | 15 | # Add files or directories matching the regex patterns to the blacklist. The 16 | # regex matches against base names, not paths. 17 | ignore-patterns= 18 | 19 | # Python code to execute, usually for sys.path manipulation such as 20 | # pygtk.require(). 21 | #init-hook= 22 | 23 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 24 | # number of processors available to use. 25 | jobs=1 26 | 27 | # Control the amount of potential inferred values when inferring a single 28 | # object. This can help the performance when dealing with large functions or 29 | # complex, nested conditions. 30 | limit-inference-results=100 31 | 32 | # List of plugins (as comma separated values of python module names) to load, 33 | # usually to register additional checkers. 34 | load-plugins=pylint_sqlalchemy 35 | 36 | # Pickle collected data for later comparisons. 37 | persistent=yes 38 | 39 | # When enabled, pylint would attempt to guess common misconfiguration and emit 40 | # user-friendly hints instead of false-positive error messages. 41 | suggestion-mode=yes 42 | 43 | # Allow loading of arbitrary C extensions. Extensions are imported into the 44 | # active Python interpreter and may run arbitrary code. 45 | unsafe-load-any-extension=no 46 | 47 | 48 | [MESSAGES CONTROL] 49 | 50 | # Only show warnings with the listed confidence levels. Leave empty to show 51 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. 52 | confidence= 53 | 54 | # Disable the message, report, category or checker with the given id(s). You 55 | # can either give multiple identifiers separated by comma (,) or put this 56 | # option multiple times (only on the command line, not in the configuration 57 | # file where it should appear only once). You can also use "--disable=all" to 58 | # disable everything first and then reenable specific checks. For example, if 59 | # you want to run only the similarities checker, you can use "--disable=all 60 | # --enable=similarities". If you want to run only the classes checker, but have 61 | # no Warning level messages displayed, use "--disable=all --enable=classes 62 | # --disable=W". 63 | disable=print-statement, 64 | parameter-unpacking, 65 | unpacking-in-except, 66 | old-raise-syntax, 67 | backtick, 68 | long-suffix, 69 | old-ne-operator, 70 | old-octal-literal, 71 | import-star-module-level, 72 | non-ascii-bytes-literal, 73 | raw-checker-failed, 74 | bad-inline-option, 75 | locally-disabled, 76 | file-ignored, 77 | suppressed-message, 78 | useless-suppression, 79 | deprecated-pragma, 80 | use-symbolic-message-instead, 81 | apply-builtin, 82 | basestring-builtin, 83 | buffer-builtin, 84 | cmp-builtin, 85 | coerce-builtin, 86 | execfile-builtin, 87 | file-builtin, 88 | long-builtin, 89 | raw_input-builtin, 90 | reduce-builtin, 91 | standarderror-builtin, 92 | unicode-builtin, 93 | xrange-builtin, 94 | coerce-method, 95 | delslice-method, 96 | getslice-method, 97 | setslice-method, 98 | no-absolute-import, 99 | old-division, 100 | dict-iter-method, 101 | dict-view-method, 102 | next-method-called, 103 | metaclass-assignment, 104 | indexing-exception, 105 | raising-string, 106 | reload-builtin, 107 | oct-method, 108 | hex-method, 109 | nonzero-method, 110 | cmp-method, 111 | input-builtin, 112 | round-builtin, 113 | intern-builtin, 114 | unichr-builtin, 115 | map-builtin-not-iterating, 116 | zip-builtin-not-iterating, 117 | range-builtin-not-iterating, 118 | filter-builtin-not-iterating, 119 | using-cmp-argument, 120 | eq-without-hash, 121 | div-method, 122 | idiv-method, 123 | rdiv-method, 124 | exception-message-attribute, 125 | invalid-str-codec, 126 | sys-max-int, 127 | bad-python3-import, 128 | deprecated-string-function, 129 | deprecated-str-translate-call, 130 | deprecated-itertools-function, 131 | deprecated-types-field, 132 | next-method-defined, 133 | dict-items-not-iterating, 134 | dict-keys-not-iterating, 135 | dict-values-not-iterating, 136 | deprecated-operator-function, 137 | deprecated-urllib-function, 138 | xreadlines-attribute, 139 | deprecated-sys-function, 140 | exception-escape, 141 | comprehension-escape, 142 | missing-module-docstring, 143 | missing-class-docstring, 144 | missing-function-docstring, 145 | bad-continuation, 146 | invalid-name, 147 | duplicate-code 148 | 149 | # Enable the message, report, category or checker with the given id(s). You can 150 | # either give multiple identifier separated by comma (,) or put this option 151 | # multiple time (only on the command line, not in the configuration file where 152 | # it should appear only once). See also the "--disable" option for examples. 153 | enable=c-extension-no-member 154 | 155 | 156 | [REPORTS] 157 | 158 | # Python expression which should return a score less than or equal to 10. You 159 | # have access to the variables 'error', 'warning', 'refactor', and 'convention' 160 | # which contain the number of messages in each category, as well as 'statement' 161 | # which is the total number of statements analyzed. This score is used by the 162 | # global evaluation report (RP0004). 163 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 164 | 165 | # Template used to display messages. This is a python new-style format string 166 | # used to format the message information. See doc for all details. 167 | #msg-template= 168 | 169 | # Set the output format. Available formats are text, parseable, colorized, json 170 | # and msvs (visual studio). You can also give a reporter class, e.g. 171 | # mypackage.mymodule.MyReporterClass. 172 | output-format=parseable 173 | 174 | # Tells whether to display a full report or only the messages. 175 | reports=no 176 | 177 | # Activate the evaluation score. 178 | score=yes 179 | 180 | 181 | [REFACTORING] 182 | 183 | # Maximum number of nested blocks for function / method body 184 | max-nested-blocks=5 185 | 186 | # Complete name of functions that never returns. When checking for 187 | # inconsistent-return-statements if a never returning function is called then 188 | # it will be considered as an explicit return statement and no message will be 189 | # printed. 190 | never-returning-functions=sys.exit 191 | 192 | 193 | [FORMAT] 194 | 195 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 196 | expected-line-ending-format= 197 | 198 | # Regexp for a line that is allowed to be longer than the limit. 199 | ignore-long-lines=^\s*(# )?<?https?://\S+>?$ 200 | 201 | # Number of spaces of indent required inside a hanging or continued line. 202 | indent-after-paren=4 203 | 204 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 205 | # tab). 206 | indent-string=' ' 207 | 208 | # Maximum number of characters on a single line. 209 | max-line-length=120 210 | 211 | # Maximum number of lines in a module. 212 | max-module-lines=1000 213 | 214 | # Allow the body of a class to be on the same line as the declaration if body 215 | # contains single statement. 216 | single-line-class-stmt=no 217 | 218 | # Allow the body of an if to be on the same line as the test if there is no 219 | # else. 220 | single-line-if-stmt=no 221 | 222 | 223 | [MISCELLANEOUS] 224 | 225 | # List of note tags to take in consideration, separated by a comma. 226 | notes=FIXME, 227 | XXX, 228 | TODO 229 | 230 | # Regular expression of note tags to take in consideration. 231 | #notes-rgx= 232 | 233 | 234 | [BASIC] 235 | 236 | # Naming style matching correct argument names. 237 | argument-naming-style=snake_case 238 | 239 | # Regular expression matching correct argument names. Overrides argument- 240 | # naming-style. 241 | #argument-rgx= 242 | 243 | # Naming style matching correct attribute names. 244 | attr-naming-style=snake_case 245 | 246 | # Regular expression matching correct attribute names. Overrides attr-naming- 247 | # style. 248 | #attr-rgx= 249 | 250 | # Bad variable names which should always be refused, separated by a comma. 251 | bad-names=foo, 252 | bar, 253 | baz, 254 | toto, 255 | tutu, 256 | tata 257 | 258 | # Bad variable names regexes, separated by a comma. If names match any regex, 259 | # they will always be refused 260 | bad-names-rgxs= 261 | 262 | # Naming style matching correct class attribute names. 263 | class-attribute-naming-style=any 264 | 265 | # Regular expression matching correct class attribute names. Overrides class- 266 | # attribute-naming-style. 267 | #class-attribute-rgx= 268 | 269 | # Naming style matching correct class names. 270 | class-naming-style=PascalCase 271 | 272 | # Regular expression matching correct class names. Overrides class-naming- 273 | # style. 274 | #class-rgx= 275 | 276 | # Naming style matching correct constant names. 277 | const-naming-style=UPPER_CASE 278 | 279 | # Regular expression matching correct constant names. Overrides const-naming- 280 | # style. 281 | #const-rgx= 282 | 283 | # Minimum line length for functions/classes that require docstrings, shorter 284 | # ones are exempt. 285 | docstring-min-length=-1 286 | 287 | # Naming style matching correct function names. 288 | function-naming-style=snake_case 289 | 290 | # Regular expression matching correct function names. Overrides function- 291 | # naming-style. 292 | #function-rgx= 293 | 294 | # Good variable names which should always be accepted, separated by a comma. 295 | good-names=i, 296 | j, 297 | k, 298 | ex, 299 | Run, 300 | _, 301 | cv 302 | 303 | # Good variable names regexes, separated by a comma. If names match any regex, 304 | # they will always be accepted 305 | good-names-rgxs= 306 | 307 | # Include a hint for the correct naming format with invalid-name. 308 | include-naming-hint=no 309 | 310 | # Naming style matching correct inline iteration names. 311 | inlinevar-naming-style=any 312 | 313 | # Regular expression matching correct inline iteration names. Overrides 314 | # inlinevar-naming-style. 315 | #inlinevar-rgx= 316 | 317 | # Naming style matching correct method names. 318 | method-naming-style=snake_case 319 | 320 | # Regular expression matching correct method names. Overrides method-naming- 321 | # style. 322 | #method-rgx= 323 | 324 | # Naming style matching correct module names. 325 | module-naming-style=snake_case 326 | 327 | # Regular expression matching correct module names. Overrides module-naming- 328 | # style. 329 | #module-rgx= 330 | 331 | # Colon-delimited sets of names that determine each other's naming style when 332 | # the name regexes allow several styles. 333 | name-group= 334 | 335 | # Regular expression which should only match function or class names that do 336 | # not require a docstring. 337 | no-docstring-rgx=^_ 338 | 339 | # List of decorators that produce properties, such as abc.abstractproperty. Add 340 | # to this list to register other decorators that produce valid properties. 341 | # These decorators are taken in consideration only for invalid-name. 342 | property-classes=abc.abstractproperty 343 | 344 | # Naming style matching correct variable names. 345 | variable-naming-style=snake_case 346 | 347 | # Regular expression matching correct variable names. Overrides variable- 348 | # naming-style. 349 | #variable-rgx= 350 | 351 | 352 | [STRING] 353 | 354 | # This flag controls whether inconsistent-quotes generates a warning when the 355 | # character used as a quote delimiter is used inconsistently within a module. 356 | check-quote-consistency=no 357 | 358 | # This flag controls whether the implicit-str-concat should generate a warning 359 | # on implicit string concatenation in sequences defined over several lines. 360 | check-str-concat-over-line-jumps=no 361 | 362 | 363 | [VARIABLES] 364 | 365 | # List of additional names supposed to be defined in builtins. Remember that 366 | # you should avoid defining new builtins when possible. 367 | additional-builtins= 368 | 369 | # Tells whether unused global variables should be treated as a violation. 370 | allow-global-unused-variables=yes 371 | 372 | # List of strings which can identify a callback function by name. A callback 373 | # name must start or end with one of those strings. 374 | callbacks=cb_, 375 | _cb 376 | 377 | # A regular expression matching the name of dummy variables (i.e. expected to 378 | # not be used). 379 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 380 | 381 | # Argument names that match this expression will be ignored. Default to name 382 | # with leading underscore. 383 | ignored-argument-names=_.*|^ignored_|^unused_ 384 | 385 | # Tells whether we should check for unused import in __init__ files. 386 | init-import=no 387 | 388 | # List of qualified module names which can have objects that can redefine 389 | # builtins. 390 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 391 | 392 | 393 | [LOGGING] 394 | 395 | # The type of string formatting that logging methods do. `old` means using % 396 | # formatting, `new` is for `{}` formatting. 397 | logging-format-style=old 398 | 399 | # Logging modules to check that the string format arguments are in logging 400 | # function parameter format. 401 | logging-modules=logging 402 | 403 | 404 | [SPELLING] 405 | 406 | # Limits count of emitted suggestions for spelling mistakes. 407 | max-spelling-suggestions=4 408 | 409 | # Spelling dictionary name. Available dictionaries: en (aspell), en_AG 410 | # (hunspell), en_AU (hunspell), en_BS (hunspell), en_BW (hunspell), en_BZ 411 | # (hunspell), en_CA (hunspell), en_DK (hunspell), en_GB (hunspell), en_GH 412 | # (hunspell), en_HK (hunspell), en_IE (hunspell), en_IN (hunspell), en_JM 413 | # (hunspell), en_NA (hunspell), en_NG (hunspell), en_NZ (hunspell), en_SG 414 | # (hunspell), en_TT (hunspell), en_US (hunspell), en_ZA (hunspell), en_ZW 415 | # (hunspell), he (hspell), pt_BR (aspell), pt_PT (aspell). 416 | spelling-dict= 417 | 418 | # List of comma separated words that should not be checked. 419 | spelling-ignore-words= 420 | 421 | # A path to a file that contains the private dictionary; one word per line. 422 | spelling-private-dict-file= 423 | 424 | # Tells whether to store unknown words to the private dictionary (see the 425 | # --spelling-private-dict-file option) instead of raising a message. 426 | spelling-store-unknown-words=no 427 | 428 | 429 | [TYPECHECK] 430 | 431 | # List of decorators that produce context managers, such as 432 | # contextlib.contextmanager. Add to this list to register other decorators that 433 | # produce valid context managers. 434 | contextmanager-decorators=contextlib.contextmanager 435 | 436 | # List of members which are set dynamically and missed by pylint inference 437 | # system, and so shouldn't trigger E1101 when accessed. Python regular 438 | # expressions are accepted. 439 | generated-members= 440 | 441 | # Tells whether missing members accessed in mixin class should be ignored. A 442 | # mixin class is detected if its name ends with "mixin" (case insensitive). 443 | ignore-mixin-members=yes 444 | 445 | # Tells whether to warn about missing members when the owner of the attribute 446 | # is inferred to be None. 447 | ignore-none=yes 448 | 449 | # This flag controls whether pylint should warn about no-member and similar 450 | # checks whenever an opaque object is returned when inferring. The inference 451 | # can return multiple potential results while evaluating a Python object, but 452 | # some branches might not be evaluated, which results in partial inference. In 453 | # that case, it might be useful to still emit no-member and other checks for 454 | # the rest of the inferred objects. 455 | ignore-on-opaque-inference=yes 456 | 457 | # List of class names for which member attributes should not be checked (useful 458 | # for classes with dynamically set attributes). This supports the use of 459 | # qualified names. 460 | ignored-classes=optparse.Values,thread._local,_thread._local,twisted.internet.reactor 461 | 462 | # List of module names for which member attributes should not be checked 463 | # (useful for modules/projects where namespaces are manipulated during runtime 464 | # and thus existing member attributes cannot be deduced by static analysis). It 465 | # supports qualified module names, as well as Unix pattern matching. 466 | ignored-modules= 467 | 468 | # Show a hint with possible names when a member name was not found. The aspect 469 | # of finding the hint is based on edit distance. 470 | missing-member-hint=yes 471 | 472 | # The minimum edit distance a name should have in order to be considered a 473 | # similar match for a missing member name. 474 | missing-member-hint-distance=1 475 | 476 | # The total number of similar names that should be taken in consideration when 477 | # showing a hint for a missing member. 478 | missing-member-max-choices=1 479 | 480 | # List of decorators that change the signature of a decorated function. 481 | signature-mutators= 482 | 483 | 484 | [SIMILARITIES] 485 | 486 | # Ignore comments when computing similarities. 487 | ignore-comments=yes 488 | 489 | # Ignore docstrings when computing similarities. 490 | ignore-docstrings=yes 491 | 492 | # Ignore imports when computing similarities. 493 | ignore-imports=no 494 | 495 | # Minimum lines number of a similarity. 496 | min-similarity-lines=4 497 | 498 | 499 | [CLASSES] 500 | 501 | # List of method names used to declare (i.e. assign) instance attributes. 502 | defining-attr-methods=__init__, 503 | __new__, 504 | setUp, 505 | __post_init__ 506 | 507 | # List of member names, which should be excluded from the protected access 508 | # warning. 509 | exclude-protected=_asdict, 510 | _fields, 511 | _replace, 512 | _source, 513 | _make 514 | 515 | # List of valid names for the first argument in a class method. 516 | valid-classmethod-first-arg=cls 517 | 518 | # List of valid names for the first argument in a metaclass class method. 519 | valid-metaclass-classmethod-first-arg=cls 520 | 521 | 522 | [DESIGN] 523 | 524 | # Maximum number of arguments for function / method. 525 | max-args=8 526 | 527 | # Maximum number of attributes for a class (see R0902). 528 | max-attributes=12 529 | 530 | # Maximum number of boolean expressions in an if statement (see R0916). 531 | max-bool-expr=5 532 | 533 | # Maximum number of branch for function / method body. 534 | max-branches=12 535 | 536 | # Maximum number of locals for function / method body. 537 | max-locals=15 538 | 539 | # Maximum number of parents for a class (see R0901). 540 | max-parents=7 541 | 542 | # Maximum number of public methods for a class (see R0904). 543 | max-public-methods=20 544 | 545 | # Maximum number of return / yield for function / method body. 546 | max-returns=6 547 | 548 | # Maximum number of statements in function / method body. 549 | max-statements=50 550 | 551 | # Minimum number of public methods for a class (see R0903). 552 | min-public-methods=2 553 | 554 | 555 | [IMPORTS] 556 | 557 | # List of modules that can be imported at any level, not just the top level 558 | # one. 559 | allow-any-import-level= 560 | 561 | # Allow wildcard imports from modules that define __all__. 562 | allow-wildcard-with-all=no 563 | 564 | # Analyse import fallback blocks. This can be used to support both Python 2 and 565 | # 3 compatible code, which means that the block might have code that exists 566 | # only in one or another interpreter, leading to false positives when analysed. 567 | analyse-fallback-blocks=no 568 | 569 | # Deprecated modules which should not be used, separated by a comma. 570 | deprecated-modules=optparse,tkinter.tix 571 | 572 | # Create a graph of external dependencies in the given file (report RP0402 must 573 | # not be disabled). 574 | ext-import-graph= 575 | 576 | # Create a graph of every (i.e. internal and external) dependencies in the 577 | # given file (report RP0402 must not be disabled). 578 | import-graph= 579 | 580 | # Create a graph of internal dependencies in the given file (report RP0402 must 581 | # not be disabled). 582 | int-import-graph= 583 | 584 | # Force import order to recognize a module as part of the standard 585 | # compatibility libraries. 586 | known-standard-library= 587 | 588 | # Force import order to recognize a module as part of a third party library. 589 | known-third-party=enchant 590 | 591 | # Couples of modules and preferred modules, separated by a comma. 592 | preferred-modules= 593 | 594 | 595 | [EXCEPTIONS] 596 | 597 | # Exceptions that will emit a warning when being caught. Defaults to 598 | # "BaseException, Exception". 599 | overgeneral-exceptions=BaseException, 600 | Exception 601 | -------------------------------------------------------------------------------- /.user.cfg.example: -------------------------------------------------------------------------------- 1 | [binance_user_config] 2 | api_key=vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A 3 | api_secret_key=NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j 4 | 5 | # Starting coin, leave empty when it's the bridge. 6 | # It has to be in the supported_coin_list 7 | current_coin= 8 | 9 | 10 | # Weather to use the testnet or not, default is False 11 | testnet=false 12 | 13 | #Bridge coin of your choice 14 | bridge=USDT 15 | 16 | #com or us, depending on region 17 | tld=com 18 | 19 | #Defines how long the scout history is stored 20 | hourToKeepScoutHistory=1 21 | 22 | #Defines to use either scout_margin or scout_multiplier 23 | use_margin=no 24 | 25 | # It's recommended to use something between 3-7 as scout_multiplier 26 | scout_multiplier=5 27 | 28 | #It's recommended to use something between 0.3 and 1.2 as scout_margin 29 | scout_margin=0.8 30 | 31 | # Controls how many seconds bot should wait between analysis of current prices 32 | scout_sleep_time=1 33 | 34 | # Pre-configured strategies are default and multiple_coins 35 | strategy=default 36 | 37 | # Controls how many minutes to wait before cancelling a limit order (buy/sell) and returning to "scout" mode. 38 | # 0 means that the order will never be cancelled prematurely. 39 | buy_timeout=20 40 | sell_timeout=20 41 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=$BUILDPLATFORM python:3.8 as builder 2 | 3 | WORKDIR /install 4 | 5 | RUN apt-get update && apt-get install -y rustc 6 | 7 | COPY requirements.txt /requirements.txt 8 | RUN pip install --prefix=/install -r /requirements.txt 9 | 10 | FROM python:3.13.2-slim 11 | 12 | WORKDIR /app 13 | 14 | COPY --from=builder /install /usr/local 15 | COPY . . 16 | 17 | CMD ["python", "-m", "binance_trade_bot"] 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | <one line to give the program's name and a brief idea of what it does.> 635 | Copyright (C) <year> <name of author> 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see <https://www.gnu.org/licenses/>. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | <program> Copyright (C) <year> <name of author> 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | <https://www.gnu.org/licenses/>. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | <https://www.gnu.org/licenses/why-not-lgpl.html>. 675 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: python -m binance_trade_bot 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Binance Trade Bot 2 | > An automated cryptocurrency trading bot for Binance 3 | 4 | ## Author 5 | Created by **Eden Gaon** 6 | 7 | [](https://twitter.com/shapeden) 8 | [](https://www.linkedin.com/in/eden-gaon-6956a219/) 9 | 10 | ## Project Status 11 | [](https://github.com/edeng23/binance-trade-bot/actions) 12 | [](https://hub.docker.com/r/edeng23/binance-trade-bot) 13 | 14 | ## Quick Deploy 15 | [](https://heroku.com/deploy?template=https://github.com/edeng23/binance-trade-bot) 16 | [](https://cloud.digitalocean.com/apps/new?repo=https://github.com/coinbookbrasil/binance-trade-bot/tree/master&refcode=a076ff7a9a6a) 17 | 18 | ## Community 19 | Join our growing community on Telegram to discuss strategies, get help, or just chat! 20 | 21 | [](https://t.me/binancetradebotchat) 22 | 23 | #### Community Telegram Chat 24 | https://t.me/binancetradebotchat 25 | 26 | ## Why? 27 | 28 | This 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. 29 | 30 | So, 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. 31 | 32 | ## How? 33 | 34 | The 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. 35 | 36 | <p align="center"> 37 | Coin A → USDT → Coin B 38 | </p> 39 | 40 | The 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. 41 | 42 | <div align="center"> 43 | <p><b>Coin A</b> → USDT → Coin B</p> 44 | <p>Coin B → USDT → Coin C</p> 45 | <p>...</p> 46 | <p>Coin C → USDT → <b>Coin A</b></p> 47 | </div> 48 | 49 | The 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. 50 | 51 | ## Binance Setup 52 | 53 | - Create a [Binance account](https://accounts.binance.com/register?ref=PGDFCE46) (Includes my referral link, I'll be super grateful if you use it). 54 | - Enable Two-factor Authentication. 55 | - Create a new API key. 56 | - Get a cryptocurrency. If its symbol is not in the default list, add it. 57 | 58 | ## Tool Setup 59 | 60 | ### Install Python dependencies 61 | 62 | Run the following line in the terminal: `pip install -r requirements.txt`. 63 | 64 | ### Create user configuration 65 | 66 | Create a .cfg file named `user.cfg` based off `.user.cfg.example`, then add your API keys and current coin. 67 | 68 | **The configuration file consists of the following fields:** 69 | 70 | - **api_key** - Binance API key generated in the Binance account setup stage. 71 | - **api_secret_key** - Binance secret key generated in the Binance account setup stage. 72 | - **testnet** - Default is false, whether to use the testnet or not 73 | - **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. 74 | - **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. 75 | - **tld** - 'com' or 'us', depending on your region. Default is 'com'. 76 | - **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. 77 | - **scout_sleep_time** - Controls how many seconds are waited between each scout. 78 | - **use_margin** - 'yes' to use scout_margin. 'no' to use scout_multiplier. 79 | - **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. 80 | - **scout_margin** - Minimum percentage coin gain per trade. 0.8 translates to a scout multiplier of 5 at 0.1% fee. 81 | - **strategy** - The trading strategy to use. See [`binance_trade_bot/strategies`](binance_trade_bot/strategies/README.md) for more information 82 | - **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. 83 | - **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. 84 | 85 | #### Environment Variables 86 | 87 | All of the options provided in `user.cfg` can also be configured using environment variables. 88 | 89 | ``` 90 | CURRENT_COIN_SYMBOL: 91 | SUPPORTED_COIN_LIST: "XLM TRX ICX EOS IOTA ONT QTUM ETC ADA XMR DASH NEO ATOM DOGE VET BAT OMG BTT" 92 | BRIDGE_SYMBOL: USDT 93 | API_KEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A 94 | API_SECRET_KEY: NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j 95 | SCOUT_MULTIPLIER: 5 96 | SCOUT_SLEEP_TIME: 1 97 | TLD: com 98 | STRATEGY: default 99 | BUY_TIMEOUT: 0 100 | SELL_TIMEOUT: 0 101 | ``` 102 | 103 | ### Paying Fees with BNB 104 | You 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: 105 | - Automatically detect that you have BNB fee payment enabled. 106 | - Make sure that you have enough BNB in your account to pay the fee of the inspected trade. 107 | - Take into consideration the discount when calculating the trade threshold. 108 | 109 | ### Notifications with Apprise 110 | 111 | Apprise allows the bot to send notifications to all of the most popular notification services available such as: Telegram, Discord, Slack, Amazon SNS, Gotify, etc. 112 | 113 | To set this up you need to create a apprise.yml file in the config directory. 114 | 115 | There is an example version of this file to get you started. 116 | 117 | If you are interested in running a Telegram bot, more information can be found at [Telegram's official documentation](https://core.telegram.org/bots). 118 | 119 | ### Run the bot 120 | 121 | ```shell 122 | python -m binance_trade_bot 123 | ``` 124 | 125 | ### Run the server that returns the information 126 | 127 | ```shell 128 | python -m binance_trade_bot.api_server 129 | ``` 130 | 131 | 132 | ### Docker 133 | 134 | The official image is available [here](https://hub.docker.com/r/edeng23/binance-trade-bot) and will update on every new change. 135 | 136 | ```shell 137 | docker-compose up 138 | ``` 139 | 140 | If you only want to start the SQLite browser 141 | 142 | ```shell 143 | docker-compose up -d sqlitebrowser 144 | ``` 145 | 146 | ## Backtesting 147 | 148 | You can test the bot on historic data to see how it performs. 149 | 150 | ```shell 151 | python backtest.py 152 | ``` 153 | 154 | Feel free to modify that file to test and compare different settings and time periods 155 | 156 | ## Developing 157 | 158 | To make sure your code is properly formatted before making a pull request, 159 | remember to install [pre-commit](https://pre-commit.com/): 160 | 161 | ```shell 162 | pip install pre-commit 163 | pre-commit install 164 | ``` 165 | 166 | The scouting algorithm is unlikely to be changed. If you'd like to contribute an alternative 167 | method, [add a new strategy](binance_trade_bot/strategies/README.md). 168 | 169 | ## Related Projects 170 | 171 | Thanks to a group of talented developers, there is now a [Telegram bot for remotely managing this project](https://github.com/lorcalhost/BTB-manager-telegram). 172 | 173 | ## Support the Project 174 | 175 | <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> 176 | 177 | ## Join the Chat 178 | 179 | - **Discord**: [Invite Link](https://discord.gg/m4TNaxreCN) 180 | 181 | ## FAQ 182 | 183 | A list of answers to what seem to be the most frequently asked questions can be found in our discord server, in the corresponding channel. 184 | 185 | <p align="center"> 186 | <img src = "https://usercontent2.hubstatic.com/6061829.jpg"> 187 | </p> 188 | 189 | ## Want to build a bot from scratch? 190 | 191 | - Check out [CCXT](https://github.com/ccxt/ccxt) for more than 100 crypto exchanges with a unified trading API. 192 | - Check out [Python-Binance](https://github.com/sammchardy/python-binance) for a complete Python Wrapper. 193 | 194 | 195 | ## Disclaimer 196 | 197 | This project is for informational purposes only. You should not construe any 198 | such information or other material as legal, tax, investment, financial, or 199 | other advice. Nothing contained here constitutes a solicitation, recommendation, 200 | endorsement, or offer by me or any third party service provider to buy or sell 201 | any securities or other financial instruments in this or in any other 202 | jurisdiction in which such solicitation or offer would be unlawful under the 203 | securities laws of such jurisdiction. 204 | 205 | If you plan to use real money, USE AT YOUR OWN RISK. 206 | 207 | Under no circumstances will I be held responsible or liable in any way for any 208 | claims, damages, losses, expenses, costs, or liabilities whatsoever, including, 209 | without limitation, any direct or indirect damages for loss of profits. 210 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "binance-trade-bot", 3 | "description": "Binance Trader", 4 | "logo": "https://cdn.freebiesupply.com/logos/large/2x/binance-coin-logo-png-transparent.png", 5 | "repository": "https://github.com/edeng23/binance-trade-bot", 6 | "formation": { 7 | "worker": { 8 | "quantity": 1, 9 | "size": "free" 10 | } 11 | }, 12 | "keywords": ["python", "binance","trading","trader","bot","market","maker","algo","crypto"], 13 | "env": { 14 | "API_KEY": { 15 | "description": "Binance API key generated in the Binance account setup stage", 16 | "required": true 17 | }, 18 | "API_SECRET_KEY": { 19 | "description": "Binance secret key generated in the Binance account setup stage", 20 | "required": true 21 | }, 22 | "CURRENT_COIN_SYMBOL": { 23 | "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", 24 | "required": false, 25 | "value": "XMR" 26 | }, 27 | "BRIDGE_SYMBOL": { 28 | "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", 29 | "required": true, 30 | "value": "USDT" 31 | }, 32 | "TLD": { 33 | "description": "'com' or 'us', depending on your region. Default is 'com'", 34 | "required": true, 35 | "value": "com" 36 | }, 37 | "SCOUT_MULTIPLIER": { 38 | "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", 39 | "required": true, 40 | "value": "5" 41 | }, 42 | "SCOUT_SLEEP_TIME": { 43 | "description": "Controls how many seconds are waited between each scout", 44 | "required": true, 45 | "value": "1" 46 | }, 47 | "HOURS_TO_KEEP_SCOUTING_HISTORY": { 48 | "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.", 49 | "required": true, 50 | "value": "1" 51 | }, 52 | "STRATEGY": { 53 | "description": "The trading strategy to use. See binance_trade_bot/strategies for more information. Options: default or multiple_coins", 54 | "required": true, 55 | "value": "default" 56 | }, 57 | "BUY_TIMEOUT": { 58 | "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", 59 | "required": true, 60 | "value": "0" 61 | }, 62 | "SELL_TIMEOUT": { 63 | "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", 64 | "required": true, 65 | "value": "0" 66 | }, 67 | "SUPPORTED_COIN_LIST": { 68 | "description": "Supported coin list", 69 | "required": true, 70 | "value": "ADA ATOM BAT BTT DASH DOGE EOS ETC ICX IOTA NEO OMG ONT QTUM TRX VET XLM XMR" 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /backtest.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from binance_trade_bot import backtest 4 | 5 | if __name__ == "__main__": 6 | history = [] 7 | for manager in backtest(datetime(2021, 1, 1), datetime.now()): 8 | btc_value = manager.collate_coins("BTC") 9 | bridge_value = manager.collate_coins(manager.config.BRIDGE.symbol) 10 | history.append((btc_value, bridge_value)) 11 | btc_diff = round((btc_value - history[0][0]) / history[0][0] * 100, 3) 12 | bridge_diff = round((bridge_value - history[0][1]) / history[0][1] * 100, 3) 13 | print("------") 14 | print("TIME:", manager.datetime) 15 | print("BALANCES:", manager.balances) 16 | print("BTC VALUE:", btc_value, f"({btc_diff}%)") 17 | print(f"{manager.config.BRIDGE.symbol} VALUE:", bridge_value, f"({bridge_diff}%)") 18 | print("------") 19 | -------------------------------------------------------------------------------- /binance_trade_bot/__init__.py: -------------------------------------------------------------------------------- 1 | from .backtest import backtest 2 | from .binance_api_manager import BinanceAPIManager 3 | from .crypto_trading import main as run_trader 4 | -------------------------------------------------------------------------------- /binance_trade_bot/__main__.py: -------------------------------------------------------------------------------- 1 | from .crypto_trading import main 2 | 3 | if __name__ == "__main__": 4 | try: 5 | main() 6 | except KeyboardInterrupt: 7 | pass 8 | -------------------------------------------------------------------------------- /binance_trade_bot/api_server.py: -------------------------------------------------------------------------------- 1 | import re 2 | from datetime import datetime, timedelta 3 | from itertools import groupby 4 | from typing import List, Tuple 5 | 6 | from flask import Flask, jsonify, request 7 | from flask_cors import CORS 8 | from flask_socketio import SocketIO, emit 9 | from sqlalchemy import func 10 | from sqlalchemy.orm import Session 11 | 12 | from .config import Config 13 | from .database import Database 14 | from .logger import Logger 15 | from .models import Coin, CoinValue, CurrentCoin, Pair, ScoutHistory, Trade 16 | 17 | app = Flask(__name__) 18 | cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) 19 | 20 | socketio = SocketIO(app, cors_allowed_origins="*") 21 | 22 | 23 | logger = Logger("api_server") 24 | config = Config() 25 | db = Database(logger, config) 26 | 27 | 28 | def filter_period(query, model): # pylint: disable=inconsistent-return-statements 29 | period = request.args.get("period", "all") 30 | 31 | if period == "all": 32 | return query 33 | 34 | num = float(re.search(r"(\d*)[shdwm]", "1d").group(1)) 35 | 36 | if "s" in period: 37 | return query.filter(model.datetime >= datetime.now() - timedelta(seconds=num)) 38 | if "h" in period: 39 | return query.filter(model.datetime >= datetime.now() - timedelta(hours=num)) 40 | if "d" in period: 41 | return query.filter(model.datetime >= datetime.now() - timedelta(days=num)) 42 | if "w" in period: 43 | return query.filter(model.datetime >= datetime.now() - timedelta(weeks=num)) 44 | if "m" in period: 45 | return query.filter(model.datetime >= datetime.now() - timedelta(days=28 * num)) 46 | 47 | 48 | @app.route("/api/value_history/<coin>") 49 | @app.route("/api/value_history") 50 | def value_history(coin: str = None): 51 | session: Session 52 | with db.db_session() as session: 53 | query = session.query(CoinValue).order_by(CoinValue.coin_id.asc(), CoinValue.datetime.asc()) 54 | 55 | query = filter_period(query, CoinValue) 56 | 57 | if coin: 58 | values: List[CoinValue] = query.filter(CoinValue.coin_id == coin).all() 59 | return jsonify([entry.info() for entry in values]) 60 | 61 | coin_values = groupby(query.all(), key=lambda cv: cv.coin) 62 | return jsonify({coin.symbol: [entry.info() for entry in history] for coin, history in coin_values}) 63 | 64 | 65 | @app.route("/api/total_value_history") 66 | def total_value_history(): 67 | session: Session 68 | with db.db_session() as session: 69 | query = session.query( 70 | CoinValue.datetime, 71 | func.sum(CoinValue.btc_value), 72 | func.sum(CoinValue.usd_value), 73 | ).group_by(CoinValue.datetime) 74 | 75 | query = filter_period(query, CoinValue) 76 | 77 | total_values: List[Tuple[datetime, float, float]] = query.all() 78 | return jsonify([{"datetime": tv[0], "btc": tv[1], "usd": tv[2]} for tv in total_values]) 79 | 80 | 81 | @app.route("/api/trade_history") 82 | def trade_history(): 83 | session: Session 84 | with db.db_session() as session: 85 | query = session.query(Trade).order_by(Trade.datetime.asc()) 86 | 87 | query = filter_period(query, Trade) 88 | 89 | trades: List[Trade] = query.all() 90 | return jsonify([trade.info() for trade in trades]) 91 | 92 | 93 | @app.route("/api/scouting_history") 94 | def scouting_history(): 95 | _current_coin = db.get_current_coin() 96 | coin = _current_coin.symbol if _current_coin is not None else None 97 | session: Session 98 | with db.db_session() as session: 99 | query = ( 100 | session.query(ScoutHistory) 101 | .join(ScoutHistory.pair) 102 | .filter(Pair.from_coin_id == coin) 103 | .order_by(ScoutHistory.datetime.asc()) 104 | ) 105 | 106 | query = filter_period(query, ScoutHistory) 107 | 108 | scouts: List[ScoutHistory] = query.all() 109 | return jsonify([scout.info() for scout in scouts]) 110 | 111 | 112 | @app.route("/api/current_coin") 113 | def current_coin(): 114 | coin = db.get_current_coin() 115 | return coin.info() if coin else None 116 | 117 | 118 | @app.route("/api/current_coin_history") 119 | def current_coin_history(): 120 | session: Session 121 | with db.db_session() as session: 122 | query = session.query(CurrentCoin) 123 | 124 | query = filter_period(query, CurrentCoin) 125 | 126 | current_coins: List[CurrentCoin] = query.all() 127 | return jsonify([cc.info() for cc in current_coins]) 128 | 129 | 130 | @app.route("/api/coins") 131 | def coins(): 132 | session: Session 133 | with db.db_session() as session: 134 | _current_coin = session.merge(db.get_current_coin()) 135 | _coins: List[Coin] = session.query(Coin).all() 136 | return jsonify([{**coin.info(), "is_current": coin == _current_coin} for coin in _coins]) 137 | 138 | 139 | @app.route("/api/pairs") 140 | def pairs(): 141 | session: Session 142 | with db.db_session() as session: 143 | all_pairs: List[Pair] = session.query(Pair).all() 144 | return jsonify([pair.info() for pair in all_pairs]) 145 | 146 | 147 | @socketio.on("update", namespace="/backend") 148 | def handle_my_custom_event(json): 149 | emit("update", json, namespace="/frontend", broadcast=True) 150 | 151 | 152 | if __name__ == "__main__": 153 | socketio.run(app, debug=True, port=5123) 154 | -------------------------------------------------------------------------------- /binance_trade_bot/auto_trader.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from typing import Dict, List 3 | 4 | from sqlalchemy.orm import Session 5 | 6 | from .binance_api_manager import BinanceAPIManager 7 | from .config import Config 8 | from .database import Database 9 | from .logger import Logger 10 | from .models import Coin, CoinValue, Pair 11 | 12 | 13 | class AutoTrader: 14 | def __init__( 15 | self, 16 | binance_manager: BinanceAPIManager, 17 | database: Database, 18 | logger: Logger, 19 | config: Config, 20 | ): 21 | self.manager = binance_manager 22 | self.db = database 23 | self.logger = logger 24 | self.config = config 25 | 26 | def initialize(self): 27 | self.initialize_trade_thresholds() 28 | 29 | def transaction_through_bridge(self, pair: Pair): 30 | """ 31 | Jump from the source coin to the destination coin through bridge coin 32 | """ 33 | can_sell = False 34 | balance = self.manager.get_currency_balance(pair.from_coin.symbol) 35 | from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE) 36 | 37 | if balance and balance * from_coin_price > self.manager.get_min_notional( 38 | pair.from_coin.symbol, self.config.BRIDGE.symbol 39 | ): 40 | can_sell = True 41 | else: 42 | self.logger.info("Skipping sell") 43 | 44 | if can_sell and self.manager.sell_alt(pair.from_coin, self.config.BRIDGE) is None: 45 | self.logger.info("Couldn't sell, going back to scouting mode...") 46 | return None 47 | 48 | result = self.manager.buy_alt(pair.to_coin, self.config.BRIDGE) 49 | if result is not None: 50 | self.db.set_current_coin(pair.to_coin) 51 | self.update_trade_threshold(pair.to_coin, result.price) 52 | return result 53 | 54 | self.logger.info("Couldn't buy, going back to scouting mode...") 55 | return None 56 | 57 | def update_trade_threshold(self, coin: Coin, coin_price: float): 58 | """ 59 | Update all the coins with the threshold of buying the current held coin 60 | """ 61 | 62 | if coin_price is None: 63 | self.logger.info(f"Skipping update... current coin {coin + self.config.BRIDGE} not found") 64 | return 65 | 66 | session: Session 67 | with self.db.db_session() as session: 68 | for pair in session.query(Pair).filter(Pair.to_coin == coin): 69 | from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE) 70 | 71 | if from_coin_price is None: 72 | self.logger.info(f"Skipping update for coin {pair.from_coin + self.config.BRIDGE} not found") 73 | continue 74 | 75 | pair.ratio = from_coin_price / coin_price 76 | 77 | def initialize_trade_thresholds(self): 78 | """ 79 | Initialize the buying threshold of all the coins for trading between them 80 | """ 81 | session: Session 82 | with self.db.db_session() as session: 83 | for pair in session.query(Pair).filter(Pair.ratio.is_(None)).all(): 84 | if not pair.from_coin.enabled or not pair.to_coin.enabled: 85 | continue 86 | self.logger.info(f"Initializing {pair.from_coin} vs {pair.to_coin}") 87 | 88 | from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE) 89 | if from_coin_price is None: 90 | self.logger.info(f"Skipping initializing {pair.from_coin + self.config.BRIDGE}, symbol not found") 91 | continue 92 | 93 | to_coin_price = self.manager.get_ticker_price(pair.to_coin + self.config.BRIDGE) 94 | if to_coin_price is None: 95 | self.logger.info(f"Skipping initializing {pair.to_coin + self.config.BRIDGE}, symbol not found") 96 | continue 97 | 98 | pair.ratio = from_coin_price / to_coin_price 99 | 100 | def scout(self): 101 | """ 102 | Scout for potential jumps from the current coin to another coin 103 | """ 104 | raise NotImplementedError() 105 | 106 | def _get_ratios(self, coin: Coin, coin_price): 107 | """ 108 | Given a coin, get the current price ratio for every other enabled coin 109 | """ 110 | ratio_dict: Dict[Pair, float] = {} 111 | 112 | for pair in self.db.get_pairs_from(coin): 113 | optional_coin_price = self.manager.get_ticker_price(pair.to_coin + self.config.BRIDGE) 114 | 115 | if optional_coin_price is None: 116 | self.logger.info(f"Skipping scouting... optional coin {pair.to_coin + self.config.BRIDGE} not found") 117 | continue 118 | 119 | self.db.log_scout(pair, pair.ratio, coin_price, optional_coin_price) 120 | 121 | # Obtain (current coin)/(optional coin) 122 | coin_opt_coin_ratio = coin_price / optional_coin_price 123 | 124 | # Fees 125 | from_fee = self.manager.get_fee(pair.from_coin, self.config.BRIDGE, True) 126 | to_fee = self.manager.get_fee(pair.to_coin, self.config.BRIDGE, False) 127 | transaction_fee = from_fee + to_fee - from_fee * to_fee 128 | 129 | if self.config.USE_MARGIN == "yes": 130 | ratio_dict[pair] = ( 131 | (1 - transaction_fee) * coin_opt_coin_ratio / pair.ratio - 1 - self.config.SCOUT_MARGIN / 100 132 | ) 133 | else: 134 | ratio_dict[pair] = ( 135 | coin_opt_coin_ratio - transaction_fee * self.config.SCOUT_MULTIPLIER * coin_opt_coin_ratio 136 | ) - pair.ratio 137 | return ratio_dict 138 | 139 | def _jump_to_best_coin(self, coin: Coin, coin_price: float): 140 | """ 141 | Given a coin, search for a coin to jump to 142 | """ 143 | ratio_dict = self._get_ratios(coin, coin_price) 144 | 145 | # keep only ratios bigger than zero 146 | ratio_dict = {k: v for k, v in ratio_dict.items() if v > 0} 147 | 148 | # if we have any viable options, pick the one with the biggest ratio 149 | if ratio_dict: 150 | best_pair = max(ratio_dict, key=ratio_dict.get) 151 | self.logger.info(f"Will be jumping from {coin} to {best_pair.to_coin_id}") 152 | self.transaction_through_bridge(best_pair) 153 | 154 | def bridge_scout(self): 155 | """ 156 | If we have any bridge coin leftover, buy a coin with it that we won't immediately trade out of 157 | """ 158 | bridge_balance = self.manager.get_currency_balance(self.config.BRIDGE.symbol) 159 | 160 | for coin in self.db.get_coins(): 161 | current_coin_price = self.manager.get_ticker_price(coin + self.config.BRIDGE) 162 | 163 | if current_coin_price is None: 164 | continue 165 | 166 | ratio_dict = self._get_ratios(coin, current_coin_price) 167 | if not any(v > 0 for v in ratio_dict.values()): 168 | # There will only be one coin where all the ratios are negative. When we find it, buy it if we can 169 | if bridge_balance > self.manager.get_min_notional(coin.symbol, self.config.BRIDGE.symbol): 170 | self.logger.info(f"Will be purchasing {coin} using bridge coin") 171 | self.manager.buy_alt(coin, self.config.BRIDGE) 172 | return coin 173 | return None 174 | 175 | def update_values(self): 176 | """ 177 | Log current value state of all altcoin balances against BTC and USDT in DB. 178 | """ 179 | now = datetime.now() 180 | 181 | session: Session 182 | with self.db.db_session() as session: 183 | coins: List[Coin] = session.query(Coin).all() 184 | for coin in coins: 185 | balance = self.manager.get_currency_balance(coin.symbol) 186 | if balance == 0: 187 | continue 188 | usd_value = self.manager.get_ticker_price(coin + "USDT") 189 | btc_value = self.manager.get_ticker_price(coin + "BTC") 190 | cv = CoinValue(coin, balance, usd_value, btc_value, datetime=now) 191 | session.add(cv) 192 | self.db.send_update(cv) 193 | -------------------------------------------------------------------------------- /binance_trade_bot/backtest.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from datetime import datetime, timedelta 3 | from traceback import format_exc 4 | from typing import Dict 5 | 6 | from sqlitedict import SqliteDict 7 | 8 | from .binance_api_manager import BinanceAPIManager 9 | from .binance_stream_manager import BinanceOrder 10 | from .config import Config 11 | from .database import Database 12 | from .logger import Logger 13 | from .models import Coin, Pair 14 | from .strategies import get_strategy 15 | 16 | cache = SqliteDict("data/backtest_cache.db") 17 | 18 | 19 | class MockBinanceManager(BinanceAPIManager): 20 | def __init__( 21 | self, 22 | config: Config, 23 | db: Database, 24 | logger: Logger, 25 | start_date: datetime = None, 26 | start_balances: Dict[str, float] = None, 27 | ): 28 | super().__init__(config, db, logger) 29 | self.config = config 30 | self.datetime = start_date or datetime(2021, 1, 1) 31 | self.balances = start_balances or {config.BRIDGE.symbol: 100} 32 | 33 | def setup_websockets(self): 34 | pass # No websockets are needed for backtesting 35 | 36 | def increment(self, interval=1): 37 | self.datetime += timedelta(minutes=interval) 38 | 39 | def get_fee(self, origin_coin: Coin, target_coin: Coin, selling: bool): 40 | return 0.00075 41 | 42 | def get_ticker_price(self, ticker_symbol: str): 43 | """ 44 | Get ticker price of a specific coin 45 | """ 46 | target_date = self.datetime.strftime("%d %b %Y %H:%M:%S") 47 | key = f"{ticker_symbol} - {target_date}" 48 | val = cache.get(key, None) 49 | if val is None: 50 | end_date = self.datetime + timedelta(minutes=1000) 51 | if end_date > datetime.now(): 52 | end_date = datetime.now() 53 | end_date = end_date.strftime("%d %b %Y %H:%M:%S") 54 | self.logger.info(f"Fetching prices for {ticker_symbol} between {self.datetime} and {end_date}") 55 | for result in self.binance_client.get_historical_klines( 56 | ticker_symbol, "1m", target_date, end_date, limit=1000 57 | ): 58 | date = datetime.utcfromtimestamp(result[0] / 1000).strftime("%d %b %Y %H:%M:%S") 59 | price = float(result[1]) 60 | cache[f"{ticker_symbol} - {date}"] = price 61 | cache.commit() 62 | val = cache.get(key, None) 63 | return val 64 | 65 | def get_currency_balance(self, currency_symbol: str, force=False): 66 | """ 67 | Get balance of a specific coin 68 | """ 69 | return self.balances.get(currency_symbol, 0) 70 | 71 | def buy_alt(self, origin_coin: Coin, target_coin: Coin): 72 | origin_symbol = origin_coin.symbol 73 | target_symbol = target_coin.symbol 74 | 75 | target_balance = self.get_currency_balance(target_symbol) 76 | from_coin_price = self.get_ticker_price(origin_symbol + target_symbol) 77 | 78 | order_quantity = self._buy_quantity(origin_symbol, target_symbol, target_balance, from_coin_price) 79 | target_quantity = order_quantity * from_coin_price 80 | self.balances[target_symbol] -= target_quantity 81 | self.balances[origin_symbol] = self.balances.get(origin_symbol, 0) + order_quantity * ( 82 | 1 - self.get_fee(origin_coin, target_coin, False) 83 | ) 84 | self.logger.info( 85 | f"Bought {origin_symbol}, balance now: {self.balances[origin_symbol]} - bridge: " 86 | f"{self.balances[target_symbol]}" 87 | ) 88 | 89 | event = defaultdict( 90 | lambda: None, 91 | order_price=from_coin_price, 92 | cumulative_quote_asset_transacted_quantity=0, 93 | ) 94 | 95 | return BinanceOrder(event) 96 | 97 | def sell_alt(self, origin_coin: Coin, target_coin: Coin): 98 | origin_symbol = origin_coin.symbol 99 | target_symbol = target_coin.symbol 100 | 101 | origin_balance = self.get_currency_balance(origin_symbol) 102 | from_coin_price = self.get_ticker_price(origin_symbol + target_symbol) 103 | 104 | order_quantity = self._sell_quantity(origin_symbol, target_symbol, origin_balance) 105 | target_quantity = order_quantity * from_coin_price 106 | self.balances[target_symbol] = self.balances.get(target_symbol, 0) + target_quantity * ( 107 | 1 - self.get_fee(origin_coin, target_coin, True) 108 | ) 109 | self.balances[origin_symbol] -= order_quantity 110 | self.logger.info( 111 | f"Sold {origin_symbol}, balance now: {self.balances[origin_symbol]} - bridge: " 112 | f"{self.balances[target_symbol]}" 113 | ) 114 | return {"price": from_coin_price} 115 | 116 | def collate_coins(self, target_symbol: str): 117 | total = 0 118 | for coin, balance in self.balances.items(): 119 | if coin == target_symbol: 120 | total += balance 121 | continue 122 | if coin == self.config.BRIDGE.symbol: 123 | price = self.get_ticker_price(target_symbol + coin) 124 | if price is None: 125 | continue 126 | total += balance / price 127 | else: 128 | price = self.get_ticker_price(coin + target_symbol) 129 | if price is None: 130 | continue 131 | total += price * balance 132 | return total 133 | 134 | 135 | class MockDatabase(Database): 136 | def __init__(self, logger: Logger, config: Config): 137 | super().__init__(logger, config, "sqlite:///") 138 | 139 | def log_scout( 140 | self, 141 | pair: Pair, 142 | target_ratio: float, 143 | current_coin_price: float, 144 | other_coin_price: float, 145 | ): 146 | pass 147 | 148 | 149 | def backtest( 150 | start_date: datetime = None, 151 | end_date: datetime = None, 152 | interval=1, 153 | yield_interval=100, 154 | start_balances: Dict[str, float] = None, 155 | starting_coin: str = None, 156 | config: Config = None, 157 | ): 158 | """ 159 | 160 | :param config: Configuration object to use 161 | :param start_date: Date to backtest from 162 | :param end_date: Date to backtest up to 163 | :param interval: Number of virtual minutes between each scout 164 | :param yield_interval: After how many intervals should the manager be yielded 165 | :param start_balances: A dictionary of initial coin values. Default: {BRIDGE: 100} 166 | :param starting_coin: The coin to start on. Default: first coin in coin list 167 | 168 | :return: The final coin balances 169 | """ 170 | config = config or Config() 171 | logger = Logger("backtesting", enable_notifications=False) 172 | 173 | end_date = end_date or datetime.today() 174 | 175 | db = MockDatabase(logger, config) 176 | db.create_database() 177 | db.set_coins(config.SUPPORTED_COIN_LIST) 178 | manager = MockBinanceManager(config, db, logger, start_date, start_balances) 179 | 180 | starting_coin = db.get_coin(starting_coin or config.SUPPORTED_COIN_LIST[0]) 181 | if manager.get_currency_balance(starting_coin.symbol) == 0: 182 | manager.buy_alt(starting_coin, config.BRIDGE) 183 | db.set_current_coin(starting_coin) 184 | 185 | strategy = get_strategy(config.STRATEGY) 186 | if strategy is None: 187 | logger.error("Invalid strategy name") 188 | return manager 189 | trader = strategy(manager, db, logger, config) 190 | trader.initialize() 191 | 192 | yield manager 193 | 194 | n = 1 195 | try: 196 | while manager.datetime < end_date: 197 | try: 198 | trader.scout() 199 | except Exception: # pylint: disable=broad-except 200 | logger.warning(format_exc()) 201 | manager.increment(interval) 202 | if n % yield_interval == 0: 203 | yield manager 204 | n += 1 205 | except KeyboardInterrupt: 206 | pass 207 | cache.close() 208 | return manager 209 | -------------------------------------------------------------------------------- /binance_trade_bot/binance_api_manager.py: -------------------------------------------------------------------------------- 1 | import math 2 | import time 3 | import traceback 4 | from typing import Dict, Optional 5 | 6 | from binance.client import Client 7 | from binance.exceptions import BinanceAPIException 8 | from cachetools import TTLCache, cached 9 | 10 | from .binance_stream_manager import BinanceCache, BinanceOrder, BinanceStreamManager, OrderGuard 11 | from .config import Config 12 | from .database import Database 13 | from .logger import Logger 14 | from .models import Coin 15 | 16 | 17 | class BinanceAPIManager: 18 | def __init__(self, config: Config, db: Database, logger: Logger, testnet = False): 19 | # initializing the client class calls `ping` API endpoint, verifying the connection 20 | self.binance_client = Client( 21 | config.BINANCE_API_KEY, 22 | config.BINANCE_API_SECRET_KEY, 23 | tld=config.BINANCE_TLD, 24 | testnet=testnet, 25 | ) 26 | self.db = db 27 | self.logger = logger 28 | self.config = config 29 | self.testnet = testnet 30 | 31 | self.cache = BinanceCache() 32 | self.stream_manager: Optional[BinanceStreamManager] = None 33 | self.setup_websockets() 34 | 35 | def setup_websockets(self): 36 | self.stream_manager = BinanceStreamManager( 37 | self.cache, 38 | self.config, 39 | self.binance_client, 40 | self.logger, 41 | ) 42 | 43 | @cached(cache=TTLCache(maxsize=1, ttl=43200)) 44 | def get_trade_fees(self) -> Dict[str, float]: 45 | if not self.testnet: 46 | return {ticker["symbol"]: float(ticker["takerCommission"]) for ticker in self.binance_client.get_trade_fee()} 47 | 48 | 49 | ## testnet does not provide trade fee API, emulating it 50 | exchange_info = self.binance_client.get_exchange_info() 51 | symbols = exchange_info["symbols"] 52 | return { 53 | symbol["symbol"]: 0.001 54 | for symbol in symbols 55 | } 56 | 57 | 58 | @cached(cache=TTLCache(maxsize=1, ttl=60)) 59 | def get_using_bnb_for_fees(self): 60 | return self.binance_client.get_bnb_burn_spot_margin()["spotBNBBurn"] 61 | 62 | def get_fee(self, origin_coin: Coin, target_coin: Coin, selling: bool): 63 | base_fee = self.get_trade_fees()[origin_coin + target_coin] 64 | if not self.testnet: 65 | if not self.get_using_bnb_for_fees(): 66 | return base_fee 67 | 68 | # The discount is only applied if we have enough BNB to cover the fee 69 | amount_trading = ( 70 | self._sell_quantity(origin_coin.symbol, target_coin.symbol) 71 | if selling 72 | else self._buy_quantity(origin_coin.symbol, target_coin.symbol) 73 | ) 74 | 75 | fee_amount = amount_trading * base_fee * 0.75 76 | if origin_coin.symbol == "BNB": 77 | fee_amount_bnb = fee_amount 78 | else: 79 | origin_price = self.get_ticker_price(origin_coin + Coin("BNB")) 80 | if origin_price is None: 81 | return base_fee 82 | fee_amount_bnb = fee_amount * origin_price 83 | 84 | bnb_balance = self.get_currency_balance("BNB") 85 | 86 | if bnb_balance >= fee_amount_bnb: 87 | return base_fee * 0.75 88 | return base_fee 89 | 90 | def get_account(self): 91 | """ 92 | Get account information 93 | """ 94 | return self.binance_client.get_account() 95 | 96 | def get_ticker_price(self, ticker_symbol: str): 97 | """ 98 | Get ticker price of a specific coin 99 | """ 100 | price = self.cache.ticker_values.get(ticker_symbol, None) 101 | if price is None and ticker_symbol not in self.cache.non_existent_tickers: 102 | self.cache.ticker_values = { 103 | ticker["symbol"]: float(ticker["price"]) for ticker in self.binance_client.get_symbol_ticker() 104 | } 105 | self.logger.debug(f"Fetched all ticker prices: {self.cache.ticker_values}") 106 | price = self.cache.ticker_values.get(ticker_symbol, None) 107 | if price is None: 108 | self.logger.info(f"Ticker does not exist: {ticker_symbol} - will not be fetched from now on") 109 | self.cache.non_existent_tickers.add(ticker_symbol) 110 | 111 | return price 112 | 113 | def get_currency_balance(self, currency_symbol: str, force=False) -> float: 114 | """ 115 | Get balance of a specific coin 116 | """ 117 | with self.cache.open_balances() as cache_balances: 118 | balance = cache_balances.get(currency_symbol, None) 119 | if force or balance is None: 120 | cache_balances.clear() 121 | cache_balances.update( 122 | { 123 | currency_balance["asset"]: float(currency_balance["free"]) 124 | for currency_balance in self.binance_client.get_account()["balances"] 125 | } 126 | ) 127 | self.logger.debug(f"Fetched all balances: {cache_balances}") 128 | if currency_symbol not in cache_balances: 129 | cache_balances[currency_symbol] = 0.0 130 | return 0.0 131 | return cache_balances.get(currency_symbol, 0.0) 132 | 133 | return balance 134 | 135 | def retry(self, func, *args, **kwargs): 136 | for attempt in range(20): 137 | try: 138 | return func(*args, **kwargs) 139 | except Exception: # pylint: disable=broad-except 140 | self.logger.warning(f"Failed to Buy/Sell. Trying Again (attempt {attempt}/20)") 141 | if attempt == 0: 142 | self.logger.warning(traceback.format_exc()) 143 | time.sleep(1) 144 | return None 145 | 146 | def get_symbol_filter(self, origin_symbol: str, target_symbol: str, filter_type: str): 147 | return next( 148 | _filter 149 | for _filter in self.binance_client.get_symbol_info(origin_symbol + target_symbol)["filters"] 150 | if _filter["filterType"] == filter_type 151 | ) 152 | 153 | @cached(cache=TTLCache(maxsize=2000, ttl=43200)) 154 | def get_alt_tick(self, origin_symbol: str, target_symbol: str): 155 | step_size = self.get_symbol_filter(origin_symbol, target_symbol, "LOT_SIZE")["stepSize"] 156 | if step_size.find("1") == 0: 157 | return 1 - step_size.find(".") 158 | return step_size.find("1") - 1 159 | 160 | @cached(cache=TTLCache(maxsize=2000, ttl=43200)) 161 | def get_min_notional(self, origin_symbol: str, target_symbol: str): 162 | return float(self.get_symbol_filter(origin_symbol, target_symbol, "NOTIONAL")["minNotional"]) 163 | 164 | def _wait_for_order( 165 | self, order_id, origin_symbol: str, target_symbol: str 166 | ) -> Optional[BinanceOrder]: # pylint: disable=unsubscriptable-object 167 | while True: 168 | order_status: BinanceOrder = self.cache.orders.get(order_id, None) 169 | if order_status is not None: 170 | break 171 | self.logger.debug(f"Waiting for order {order_id} to be created") 172 | time.sleep(1) 173 | 174 | self.logger.debug(f"Order created: {order_status}") 175 | 176 | while order_status.status != "FILLED": 177 | try: 178 | order_status = self.cache.orders.get(order_id, None) 179 | 180 | self.logger.debug(f"Waiting for order {order_id} to be filled") 181 | 182 | if self._should_cancel_order(order_status): 183 | cancel_order = None 184 | while cancel_order is None: 185 | cancel_order = self.binance_client.cancel_order( 186 | symbol=origin_symbol + target_symbol, orderId=order_id 187 | ) 188 | self.logger.info("Order timeout, canceled...") 189 | 190 | # sell partially 191 | if order_status.status == "PARTIALLY_FILLED" and order_status.side == "BUY": 192 | self.logger.info("Sell partially filled amount") 193 | 194 | order_quantity = self._sell_quantity(origin_symbol, target_symbol) 195 | partially_order = None 196 | while partially_order is None: 197 | partially_order = self.binance_client.order_market_sell( 198 | symbol=origin_symbol + target_symbol, 199 | quantity=order_quantity, 200 | ) 201 | 202 | self.logger.info("Going back to scouting mode...") 203 | return None 204 | 205 | if order_status.status == "CANCELED": 206 | self.logger.info("Order is canceled, going back to scouting mode...") 207 | return None 208 | 209 | time.sleep(1) 210 | except BinanceAPIException as e: 211 | self.logger.info(e) 212 | time.sleep(1) 213 | except Exception as e: # pylint: disable=broad-except 214 | self.logger.info(f"Unexpected Error: {e}") 215 | time.sleep(1) 216 | 217 | self.logger.debug(f"Order filled: {order_status}") 218 | return order_status 219 | 220 | def wait_for_order( 221 | self, order_id, origin_symbol: str, target_symbol: str, order_guard: OrderGuard 222 | ) -> Optional[BinanceOrder]: # pylint: disable=unsubscriptable-object 223 | with order_guard: 224 | return self._wait_for_order(order_id, origin_symbol, target_symbol) 225 | 226 | def _should_cancel_order(self, order_status): 227 | minutes = (time.time() - order_status.time / 1000) / 60 228 | timeout = 0 229 | 230 | if order_status.side == "SELL": 231 | timeout = float(self.config.SELL_TIMEOUT) 232 | else: 233 | timeout = float(self.config.BUY_TIMEOUT) 234 | 235 | if timeout and minutes > timeout and order_status.status == "NEW": 236 | return True 237 | 238 | if timeout and minutes > timeout and order_status.status == "PARTIALLY_FILLED": 239 | if order_status.side == "SELL": 240 | return True 241 | 242 | if order_status.side == "BUY": 243 | current_price = self.get_ticker_price(order_status.symbol) 244 | if float(current_price) * (1 - 0.001) > float(order_status.price): 245 | return True 246 | 247 | return False 248 | 249 | def buy_alt(self, origin_coin: Coin, target_coin: Coin) -> BinanceOrder: 250 | return self.retry(self._buy_alt, origin_coin, target_coin) 251 | 252 | def _buy_quantity( 253 | self, 254 | origin_symbol: str, 255 | target_symbol: str, 256 | target_balance: float = None, 257 | from_coin_price: float = None, 258 | ): 259 | target_balance = target_balance or self.get_currency_balance(target_symbol) 260 | from_coin_price = from_coin_price or self.get_ticker_price(origin_symbol + target_symbol) 261 | 262 | origin_tick = self.get_alt_tick(origin_symbol, target_symbol) 263 | return math.floor(target_balance * 10**origin_tick / from_coin_price) / float(10**origin_tick) 264 | 265 | def _buy_alt(self, origin_coin: Coin, target_coin: Coin): # pylint: disable=too-many-locals 266 | """ 267 | Buy altcoin 268 | """ 269 | trade_log = self.db.start_trade_log(origin_coin, target_coin, False) 270 | origin_symbol = origin_coin.symbol 271 | target_symbol = target_coin.symbol 272 | 273 | with self.cache.open_balances() as balances: 274 | balances.clear() 275 | 276 | origin_balance = self.get_currency_balance(origin_symbol) 277 | target_balance = self.get_currency_balance(target_symbol) 278 | pair_info = self.binance_client.get_symbol_info(origin_symbol + target_symbol) 279 | from_coin_price = self.get_ticker_price(origin_symbol + target_symbol) 280 | from_coin_price_s = "{:0.0{}f}".format(from_coin_price, pair_info["quotePrecision"]) 281 | 282 | order_quantity = self._buy_quantity(origin_symbol, target_symbol, target_balance, from_coin_price) 283 | order_quantity_s = "{:0.0{}f}".format(order_quantity, pair_info["baseAssetPrecision"]) 284 | 285 | self.logger.info(f"BUY QTY {order_quantity}") 286 | 287 | # Try to buy until successful 288 | order = None 289 | order_guard = self.stream_manager.acquire_order_guard() 290 | while order is None: 291 | try: 292 | order = self.binance_client.order_limit_buy( 293 | symbol=origin_symbol + target_symbol, 294 | quantity=order_quantity_s, 295 | price=from_coin_price_s, 296 | ) 297 | self.logger.info(order) 298 | except BinanceAPIException as e: 299 | self.logger.info(e) 300 | time.sleep(1) 301 | except Exception as e: # pylint: disable=broad-except 302 | self.logger.warning(f"Unexpected Error: {e}") 303 | 304 | trade_log.set_ordered(origin_balance, target_balance, order_quantity) 305 | 306 | order_guard.set_order(origin_symbol, target_symbol, int(order["orderId"])) 307 | order = self.wait_for_order(order["orderId"], origin_symbol, target_symbol, order_guard) 308 | 309 | if order is None: 310 | return None 311 | 312 | self.logger.info(f"Bought {origin_symbol}") 313 | 314 | trade_log.set_complete(order.cumulative_quote_qty) 315 | 316 | return order 317 | 318 | def sell_alt(self, origin_coin: Coin, target_coin: Coin) -> BinanceOrder: 319 | return self.retry(self._sell_alt, origin_coin, target_coin) 320 | 321 | def _sell_quantity(self, origin_symbol: str, target_symbol: str, origin_balance: float = None): 322 | origin_balance = origin_balance or self.get_currency_balance(origin_symbol) 323 | 324 | origin_tick = self.get_alt_tick(origin_symbol, target_symbol) 325 | return math.floor(origin_balance * 10**origin_tick) / float(10**origin_tick) 326 | 327 | def _sell_alt(self, origin_coin: Coin, target_coin: Coin): # pylint: disable=too-many-locals 328 | """ 329 | Sell altcoin 330 | """ 331 | trade_log = self.db.start_trade_log(origin_coin, target_coin, True) 332 | origin_symbol = origin_coin.symbol 333 | target_symbol = target_coin.symbol 334 | 335 | with self.cache.open_balances() as balances: 336 | balances.clear() 337 | 338 | origin_balance = self.get_currency_balance(origin_symbol) 339 | target_balance = self.get_currency_balance(target_symbol) 340 | 341 | pair_info = self.binance_client.get_symbol_info(origin_symbol + target_symbol) 342 | from_coin_price = self.get_ticker_price(origin_symbol + target_symbol) 343 | from_coin_price_s = "{:0.0{}f}".format(from_coin_price, pair_info["quotePrecision"]) 344 | 345 | order_quantity = self._sell_quantity(origin_symbol, target_symbol, origin_balance) 346 | order_quantity_s = "{:0.0{}f}".format(order_quantity, pair_info["baseAssetPrecision"]) 347 | self.logger.info(f"Selling {order_quantity} of {origin_symbol}") 348 | 349 | self.logger.info(f"Balance is {origin_balance}") 350 | order = None 351 | order_guard = self.stream_manager.acquire_order_guard() 352 | while order is None: 353 | # Should sell at calculated price to avoid lost coin 354 | order = self.binance_client.order_limit_sell( 355 | symbol=origin_symbol + target_symbol, 356 | quantity=(order_quantity_s), 357 | price=from_coin_price_s, 358 | ) 359 | 360 | self.logger.info("order") 361 | self.logger.info(order) 362 | 363 | trade_log.set_ordered(origin_balance, target_balance, order_quantity) 364 | 365 | order_guard.set_order(origin_symbol, target_symbol, int(order["orderId"])) 366 | order = self.wait_for_order(order["orderId"], origin_symbol, target_symbol, order_guard) 367 | 368 | if order is None: 369 | return None 370 | 371 | new_balance = self.get_currency_balance(origin_symbol) 372 | while new_balance >= origin_balance: 373 | new_balance = self.get_currency_balance(origin_symbol, True) 374 | 375 | self.logger.info(f"Sold {origin_symbol}") 376 | 377 | trade_log.set_complete(order.cumulative_quote_qty) 378 | 379 | return order 380 | -------------------------------------------------------------------------------- /binance_trade_bot/binance_stream_manager.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import threading 3 | import time 4 | from contextlib import contextmanager 5 | from typing import Dict, Set, Tuple 6 | 7 | import binance.client 8 | from binance.exceptions import BinanceAPIException, BinanceRequestException 9 | from unicorn_binance_websocket_api import BinanceWebSocketApiManager 10 | 11 | from .config import Config 12 | from .logger import Logger 13 | 14 | 15 | class BinanceOrder: # pylint: disable=too-few-public-methods 16 | def __init__(self, report): 17 | self.event = report 18 | self.symbol = report["symbol"] 19 | self.side = report["side"] 20 | self.order_type = report["order_type"] 21 | self.id = report["order_id"] 22 | self.cumulative_quote_qty = float(report["cumulative_quote_asset_transacted_quantity"]) 23 | self.status = report["current_order_status"] 24 | self.price = float(report["order_price"]) 25 | self.time = report["transaction_time"] 26 | 27 | def __repr__(self): 28 | return f"<BinanceOrder {self.event}>" 29 | 30 | 31 | class BinanceCache: # pylint: disable=too-few-public-methods 32 | ticker_values: Dict[str, float] = {} 33 | _balances: Dict[str, float] = {} 34 | _balances_mutex: threading.Lock = threading.Lock() 35 | non_existent_tickers: Set[str] = set() 36 | orders: Dict[str, BinanceOrder] = {} 37 | 38 | @contextmanager 39 | def open_balances(self): 40 | with self._balances_mutex: 41 | yield self._balances 42 | 43 | 44 | class OrderGuard: 45 | def __init__(self, pending_orders: Set[Tuple[str, int]], mutex: threading.Lock): 46 | self.pending_orders = pending_orders 47 | self.mutex = mutex 48 | # lock immediately because OrderGuard 49 | # should be entered and put tag that shouldn't be missed 50 | self.mutex.acquire() 51 | self.tag = None 52 | 53 | def set_order(self, origin_symbol: str, target_symbol: str, order_id: int): 54 | self.tag = (origin_symbol + target_symbol, order_id) 55 | 56 | def __enter__(self): 57 | try: 58 | if self.tag is None: 59 | raise Exception("OrderGuard wasn't properly set") 60 | self.pending_orders.add(self.tag) 61 | finally: 62 | self.mutex.release() 63 | 64 | def __exit__(self, exc_type, exc_val, exc_tb): 65 | self.pending_orders.remove(self.tag) 66 | 67 | 68 | class BinanceStreamManager: 69 | def __init__( 70 | self, 71 | cache: BinanceCache, 72 | config: Config, 73 | binance_client: binance.client.Client, 74 | logger: Logger, 75 | ): 76 | self.cache = cache 77 | self.logger = logger 78 | exchange_name = f"binance.{config.BINANCE_TLD}" 79 | if config.TESTNET: 80 | exchange_name += "-testnet" 81 | self.bw_api_manager = BinanceWebSocketApiManager( 82 | output_default="UnicornFy", 83 | enable_stream_signal_buffer=True, 84 | exchange=exchange_name, 85 | ) 86 | self.bw_api_manager.create_stream( 87 | ["arr"], 88 | ["!miniTicker"], 89 | api_key=config.BINANCE_API_KEY, 90 | api_secret=config.BINANCE_API_SECRET_KEY, 91 | ) 92 | self.bw_api_manager.create_stream( 93 | ["arr"], 94 | ["!userData"], 95 | api_key=config.BINANCE_API_KEY, 96 | api_secret=config.BINANCE_API_SECRET_KEY, 97 | ) 98 | self.binance_client = binance_client 99 | self.pending_orders: Set[Tuple[str, int]] = set() 100 | self.pending_orders_mutex: threading.Lock = threading.Lock() 101 | self._processorThread = threading.Thread(target=self._stream_processor) 102 | self._processorThread.start() 103 | 104 | def acquire_order_guard(self): 105 | return OrderGuard(self.pending_orders, self.pending_orders_mutex) 106 | 107 | def _fetch_pending_orders(self): 108 | pending_orders: Set[Tuple[str, int]] 109 | with self.pending_orders_mutex: 110 | pending_orders = self.pending_orders.copy() 111 | for symbol, order_id in pending_orders: 112 | order = None 113 | while True: 114 | try: 115 | order = self.binance_client.get_order(symbol=symbol, orderId=order_id) 116 | except (BinanceRequestException, BinanceAPIException) as e: 117 | self.logger.error(f"Got exception during fetching pending order: {e}") 118 | if order is not None: 119 | break 120 | time.sleep(1) 121 | fake_report = { 122 | "symbol": order["symbol"], 123 | "side": order["side"], 124 | "order_type": order["type"], 125 | "order_id": order["orderId"], 126 | "cumulative_quote_asset_transacted_quantity": float(order["cummulativeQuoteQty"]), 127 | "current_order_status": order["status"], 128 | "order_price": float(order["price"]), 129 | "transaction_time": order["time"], 130 | } 131 | self.logger.info( 132 | f"Pending order {order_id} for symbol {symbol} fetched:\n{fake_report}", 133 | False, 134 | ) 135 | self.cache.orders[fake_report["order_id"]] = BinanceOrder(fake_report) 136 | 137 | def _invalidate_balances(self): 138 | with self.cache.open_balances() as balances: 139 | balances.clear() 140 | 141 | def _stream_processor(self): 142 | while True: 143 | if self.bw_api_manager.is_manager_stopping(): 144 | sys.exit() 145 | 146 | stream_signal = self.bw_api_manager.pop_stream_signal_from_stream_signal_buffer() 147 | stream_data = self.bw_api_manager.pop_stream_data_from_stream_buffer() 148 | 149 | if stream_signal is not False: 150 | signal_type = stream_signal["type"] 151 | stream_id = stream_signal["stream_id"] 152 | if signal_type == "CONNECT": 153 | stream_info = self.bw_api_manager.get_stream_info(stream_id) 154 | if "!userData" in stream_info["markets"]: 155 | self.logger.debug("Connect for userdata arrived", False) 156 | self._fetch_pending_orders() 157 | self._invalidate_balances() 158 | if stream_data is not False: 159 | self._process_stream_data(stream_data) 160 | if stream_data is False and stream_signal is False: 161 | time.sleep(0.01) 162 | 163 | def _process_stream_data(self, stream_data): 164 | event_type = stream_data["event_type"] 165 | if event_type == "executionReport": # !userData 166 | self.logger.debug(f"execution report: {stream_data}") 167 | order = BinanceOrder(stream_data) 168 | self.cache.orders[order.id] = order 169 | elif event_type == "balanceUpdate": # !userData 170 | self.logger.debug(f"Balance update: {stream_data}") 171 | with self.cache.open_balances() as balances: 172 | asset = stream_data["asset"] 173 | if asset in balances: 174 | del balances[stream_data["asset"]] 175 | elif event_type in ( 176 | "outboundAccountPosition", 177 | "outboundAccountInfo", 178 | ): # !userData 179 | self.logger.debug(f"{event_type}: {stream_data}") 180 | with self.cache.open_balances() as balances: 181 | for bal in stream_data["balances"]: 182 | balances[bal["asset"]] = float(bal["free"]) 183 | elif event_type == "24hrMiniTicker": 184 | for event in stream_data["data"]: 185 | self.cache.ticker_values[event["symbol"]] = float(event["close_price"]) 186 | else: 187 | self.logger.error(f"Unknown event type found: {event_type}\n{stream_data}") 188 | 189 | def close(self): 190 | self.bw_api_manager.stop_manager_with_all_streams() 191 | -------------------------------------------------------------------------------- /binance_trade_bot/config.py: -------------------------------------------------------------------------------- 1 | # Config consts 2 | import configparser 3 | import os 4 | 5 | from .models import Coin 6 | 7 | CFG_FL_NAME = "user.cfg" 8 | USER_CFG_SECTION = "binance_user_config" 9 | 10 | 11 | class Config: # pylint: disable=too-few-public-methods,too-many-instance-attributes 12 | def __init__(self): 13 | # Init config 14 | config = configparser.ConfigParser() 15 | config["DEFAULT"] = { 16 | "bridge": "USDT", 17 | "use_margin": "no", 18 | "scout_multiplier": "5", 19 | "scout_margin": "0.8", 20 | "scout_sleep_time": "5", 21 | "hourToKeepScoutHistory": "1", 22 | "tld": "com", 23 | "strategy": "default", 24 | "sell_timeout": "0", 25 | "buy_timeout": "0", 26 | "testnet": False, 27 | } 28 | 29 | if not os.path.exists(CFG_FL_NAME): 30 | print("No configuration file (user.cfg) found! See README. Assuming default config...") 31 | config[USER_CFG_SECTION] = {} 32 | else: 33 | config.read(CFG_FL_NAME) 34 | 35 | self.BRIDGE_SYMBOL = os.environ.get("BRIDGE_SYMBOL") or config.get(USER_CFG_SECTION, "bridge") 36 | self.BRIDGE = Coin(self.BRIDGE_SYMBOL, False) 37 | self.TESTNET = os.environ.get("TESTNET") or config.getboolean(USER_CFG_SECTION, "testnet") 38 | 39 | # Prune settings 40 | self.SCOUT_HISTORY_PRUNE_TIME = float( 41 | os.environ.get("HOURS_TO_KEEP_SCOUTING_HISTORY") or config.get(USER_CFG_SECTION, "hourToKeepScoutHistory") 42 | ) 43 | 44 | # Get config for scout 45 | self.SCOUT_MULTIPLIER = float( 46 | os.environ.get("SCOUT_MULTIPLIER") or config.get(USER_CFG_SECTION, "scout_multiplier") 47 | ) 48 | self.SCOUT_SLEEP_TIME = int( 49 | os.environ.get("SCOUT_SLEEP_TIME") or config.get(USER_CFG_SECTION, "scout_sleep_time") 50 | ) 51 | 52 | # Get config for binance 53 | self.BINANCE_API_KEY = os.environ.get("API_KEY") or config.get(USER_CFG_SECTION, "api_key") 54 | self.BINANCE_API_SECRET_KEY = os.environ.get("API_SECRET_KEY") or config.get(USER_CFG_SECTION, "api_secret_key") 55 | self.BINANCE_TLD = os.environ.get("TLD") or config.get(USER_CFG_SECTION, "tld") 56 | 57 | # Get supported coin list from the environment 58 | supported_coin_list = [ 59 | coin.strip() for coin in os.environ.get("SUPPORTED_COIN_LIST", "").split() if coin.strip() 60 | ] 61 | # Get supported coin list from supported_coin_list file 62 | if not supported_coin_list and os.path.exists("supported_coin_list"): 63 | with open("supported_coin_list") as rfh: 64 | for line in rfh: 65 | line = line.strip() 66 | if not line or line.startswith("#") or line in supported_coin_list: 67 | continue 68 | supported_coin_list.append(line) 69 | self.SUPPORTED_COIN_LIST = supported_coin_list 70 | 71 | self.CURRENT_COIN_SYMBOL = os.environ.get("CURRENT_COIN_SYMBOL") or config.get(USER_CFG_SECTION, "current_coin") 72 | 73 | self.STRATEGY = os.environ.get("STRATEGY") or config.get(USER_CFG_SECTION, "strategy") 74 | 75 | self.SELL_TIMEOUT = os.environ.get("SELL_TIMEOUT") or config.get(USER_CFG_SECTION, "sell_timeout") 76 | self.BUY_TIMEOUT = os.environ.get("BUY_TIMEOUT") or config.get(USER_CFG_SECTION, "buy_timeout") 77 | 78 | self.USE_MARGIN = os.environ.get("USE_MARGIN") or config.get(USER_CFG_SECTION, "use_margin") 79 | self.SCOUT_MARGIN = float(os.environ.get("SCOUT_MARGIN") or config.get(USER_CFG_SECTION, "scout_margin")) 80 | -------------------------------------------------------------------------------- /binance_trade_bot/crypto_trading.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | import time 3 | 4 | from .binance_api_manager import BinanceAPIManager 5 | from .config import Config 6 | from .database import Database 7 | from .logger import Logger 8 | from .scheduler import SafeScheduler 9 | from .strategies import get_strategy 10 | 11 | 12 | def main(): 13 | logger = Logger() 14 | logger.info("Starting") 15 | 16 | config = Config() 17 | db = Database(logger, config) 18 | manager = BinanceAPIManager(config, db, logger, config.TESTNET) 19 | # check if we can access API feature that require valid config 20 | try: 21 | _ = manager.get_account() 22 | except Exception as e: # pylint: disable=broad-except 23 | logger.error("Couldn't access Binance API - API keys may be wrong or lack sufficient permissions") 24 | logger.error(e) 25 | return 26 | strategy = get_strategy(config.STRATEGY) 27 | if strategy is None: 28 | logger.error("Invalid strategy name") 29 | return 30 | trader = strategy(manager, db, logger, config) 31 | logger.info(f"Chosen strategy: {config.STRATEGY}") 32 | 33 | logger.info("Creating database schema if it doesn't already exist") 34 | db.create_database() 35 | 36 | db.set_coins(config.SUPPORTED_COIN_LIST) 37 | db.migrate_old_state() 38 | 39 | trader.initialize() 40 | 41 | schedule = SafeScheduler(logger) 42 | schedule.every(config.SCOUT_SLEEP_TIME).seconds.do(trader.scout).tag("scouting") 43 | schedule.every(1).minutes.do(trader.update_values).tag("updating value history") 44 | schedule.every(1).minutes.do(db.prune_scout_history).tag("pruning scout history") 45 | schedule.every(1).hours.do(db.prune_value_history).tag("pruning value history") 46 | try: 47 | while True: 48 | schedule.run_pending() 49 | time.sleep(1) 50 | finally: 51 | manager.stream_manager.close() -------------------------------------------------------------------------------- /binance_trade_bot/database.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import time 4 | from contextlib import contextmanager 5 | from datetime import datetime, timedelta 6 | from typing import List, Optional, Union 7 | 8 | from socketio import Client 9 | from socketio.exceptions import ConnectionError as SocketIOConnectionError 10 | from sqlalchemy import create_engine, func 11 | from sqlalchemy.orm import Session, scoped_session, sessionmaker 12 | 13 | from .config import Config 14 | from .logger import Logger 15 | from .models import * # pylint: disable=wildcard-import 16 | 17 | 18 | class Database: 19 | def __init__(self, logger: Logger, config: Config, uri="sqlite:///data/crypto_trading.db"): 20 | self.logger = logger 21 | self.config = config 22 | self.engine = create_engine(uri) 23 | self.SessionMaker = sessionmaker(bind=self.engine) 24 | self.socketio_client = Client() 25 | 26 | def socketio_connect(self): 27 | if self.socketio_client.connected and self.socketio_client.namespaces: 28 | return True 29 | try: 30 | if not self.socketio_client.connected: 31 | self.socketio_client.connect("http://api:5123", namespaces=["/backend"]) 32 | while not self.socketio_client.connected or not self.socketio_client.namespaces: 33 | time.sleep(0.1) 34 | return True 35 | except SocketIOConnectionError: 36 | return False 37 | 38 | @contextmanager 39 | def db_session(self): 40 | """ 41 | Creates a context with an open SQLAlchemy session. 42 | """ 43 | session: Session = scoped_session(self.SessionMaker) 44 | yield session 45 | session.commit() 46 | session.close() 47 | 48 | def set_coins(self, symbols: List[str]): 49 | session: Session 50 | 51 | # Add coins to the database and set them as enabled or not 52 | with self.db_session() as session: 53 | # For all the coins in the database, if the symbol no longer appears 54 | # in the config file, set the coin as disabled 55 | coins: List[Coin] = session.query(Coin).all() 56 | for coin in coins: 57 | if coin.symbol not in symbols: 58 | coin.enabled = False 59 | 60 | # For all the symbols in the config file, add them to the database 61 | # if they don't exist 62 | for symbol in symbols: 63 | coin = next((coin for coin in coins if coin.symbol == symbol), None) 64 | if coin is None: 65 | session.add(Coin(symbol)) 66 | else: 67 | coin.enabled = True 68 | 69 | # For all the combinations of coins in the database, add a pair to the database 70 | with self.db_session() as session: 71 | coins: List[Coin] = session.query(Coin).filter(Coin.enabled).all() 72 | for from_coin in coins: 73 | for to_coin in coins: 74 | if from_coin != to_coin: 75 | pair = session.query(Pair).filter(Pair.from_coin == from_coin, Pair.to_coin == to_coin).first() 76 | if pair is None: 77 | session.add(Pair(from_coin, to_coin)) 78 | 79 | def get_coins(self, only_enabled=True) -> List[Coin]: 80 | session: Session 81 | with self.db_session() as session: 82 | if only_enabled: 83 | coins = session.query(Coin).filter(Coin.enabled).all() 84 | else: 85 | coins = session.query(Coin).all() 86 | session.expunge_all() 87 | return coins 88 | 89 | def get_coin(self, coin: Union[Coin, str]) -> Coin: 90 | if isinstance(coin, Coin): 91 | return coin 92 | session: Session 93 | with self.db_session() as session: 94 | coin = session.query(Coin).get(coin) 95 | session.expunge(coin) 96 | return coin 97 | 98 | def set_current_coin(self, coin: Union[Coin, str]): 99 | coin = self.get_coin(coin) 100 | session: Session 101 | with self.db_session() as session: 102 | if isinstance(coin, Coin): 103 | coin = session.merge(coin) 104 | cc = CurrentCoin(coin) 105 | session.add(cc) 106 | self.send_update(cc) 107 | 108 | def get_current_coin(self) -> Optional[Coin]: 109 | session: Session 110 | with self.db_session() as session: 111 | current_coin = session.query(CurrentCoin).order_by(CurrentCoin.datetime.desc()).first() 112 | if current_coin is None: 113 | return None 114 | coin = current_coin.coin 115 | session.expunge(coin) 116 | return coin 117 | 118 | def get_pair(self, from_coin: Union[Coin, str], to_coin: Union[Coin, str]): 119 | from_coin = self.get_coin(from_coin) 120 | to_coin = self.get_coin(to_coin) 121 | session: Session 122 | with self.db_session() as session: 123 | pair: Pair = session.query(Pair).filter(Pair.from_coin == from_coin, Pair.to_coin == to_coin).first() 124 | session.expunge(pair) 125 | return pair 126 | 127 | def get_pairs_from(self, from_coin: Union[Coin, str], only_enabled=True) -> List[Pair]: 128 | from_coin = self.get_coin(from_coin) 129 | session: Session 130 | with self.db_session() as session: 131 | pairs = session.query(Pair).filter(Pair.from_coin == from_coin) 132 | if only_enabled: 133 | pairs = pairs.filter(Pair.enabled.is_(True)) 134 | pairs = pairs.all() 135 | session.expunge_all() 136 | return pairs 137 | 138 | def get_pairs(self, only_enabled=True) -> List[Pair]: 139 | session: Session 140 | with self.db_session() as session: 141 | pairs = session.query(Pair) 142 | if only_enabled: 143 | pairs = pairs.filter(Pair.enabled.is_(True)) 144 | pairs = pairs.all() 145 | session.expunge_all() 146 | return pairs 147 | 148 | def log_scout( 149 | self, 150 | pair: Pair, 151 | target_ratio: float, 152 | current_coin_price: float, 153 | other_coin_price: float, 154 | ): 155 | session: Session 156 | with self.db_session() as session: 157 | pair = session.merge(pair) 158 | sh = ScoutHistory(pair, target_ratio, current_coin_price, other_coin_price) 159 | session.add(sh) 160 | self.send_update(sh) 161 | 162 | def prune_scout_history(self): 163 | time_diff = datetime.now() - timedelta(hours=self.config.SCOUT_HISTORY_PRUNE_TIME) 164 | session: Session 165 | with self.db_session() as session: 166 | session.query(ScoutHistory).filter(ScoutHistory.datetime < time_diff).delete() 167 | 168 | def prune_value_history(self): 169 | session: Session 170 | with self.db_session() as session: 171 | # Sets the first entry for each coin for each hour as 'hourly' 172 | hourly_entries: List[CoinValue] = ( 173 | session.query(CoinValue).group_by(CoinValue.coin_id, func.strftime("%H", CoinValue.datetime)).all() 174 | ) 175 | for entry in hourly_entries: 176 | entry.interval = Interval.HOURLY 177 | 178 | # Sets the first entry for each coin for each day as 'daily' 179 | daily_entries: List[CoinValue] = ( 180 | session.query(CoinValue).group_by(CoinValue.coin_id, func.date(CoinValue.datetime)).all() 181 | ) 182 | for entry in daily_entries: 183 | entry.interval = Interval.DAILY 184 | 185 | # Sets the first entry for each coin for each month as 'weekly' 186 | # (Sunday is the start of the week) 187 | weekly_entries: List[CoinValue] = ( 188 | session.query(CoinValue).group_by(CoinValue.coin_id, func.strftime("%Y-%W", CoinValue.datetime)).all() 189 | ) 190 | for entry in weekly_entries: 191 | entry.interval = Interval.WEEKLY 192 | 193 | # The last 24 hours worth of minutely entries will be kept, so 194 | # count(coins) * 1440 entries 195 | time_diff = datetime.now() - timedelta(hours=24) 196 | session.query(CoinValue).filter( 197 | CoinValue.interval == Interval.MINUTELY, CoinValue.datetime < time_diff 198 | ).delete() 199 | 200 | # The last 28 days worth of hourly entries will be kept, so count(coins) * 672 entries 201 | time_diff = datetime.now() - timedelta(days=28) 202 | session.query(CoinValue).filter( 203 | CoinValue.interval == Interval.HOURLY, CoinValue.datetime < time_diff 204 | ).delete() 205 | 206 | # The last years worth of daily entries will be kept, so count(coins) * 365 entries 207 | time_diff = datetime.now() - timedelta(days=365) 208 | session.query(CoinValue).filter( 209 | CoinValue.interval == Interval.DAILY, CoinValue.datetime < time_diff 210 | ).delete() 211 | 212 | # All weekly entries will be kept forever 213 | 214 | def create_database(self): 215 | Base.metadata.create_all(self.engine) 216 | 217 | def start_trade_log(self, from_coin: Coin, to_coin: Coin, selling: bool): 218 | return TradeLog(self, from_coin, to_coin, selling) 219 | 220 | def send_update(self, model): 221 | if not self.socketio_connect(): 222 | return 223 | 224 | self.socketio_client.emit( 225 | "update", 226 | {"table": model.__tablename__, "data": model.info()}, 227 | namespace="/backend", 228 | ) 229 | 230 | def migrate_old_state(self): 231 | """ 232 | For migrating from old dotfile format to SQL db. This method should be removed in 233 | the future. 234 | """ 235 | if os.path.isfile(".current_coin"): 236 | with open(".current_coin") as f: 237 | coin = f.read().strip() 238 | self.logger.info(f".current_coin file found, loading current coin {coin}") 239 | self.set_current_coin(coin) 240 | os.rename(".current_coin", ".current_coin.old") 241 | self.logger.info(f".current_coin renamed to .current_coin.old - You can now delete this file") 242 | 243 | if os.path.isfile(".current_coin_table"): 244 | with open(".current_coin_table") as f: 245 | self.logger.info(f".current_coin_table file found, loading into database") 246 | table: dict = json.load(f) 247 | session: Session 248 | with self.db_session() as session: 249 | for from_coin, to_coin_dict in table.items(): 250 | for to_coin, ratio in to_coin_dict.items(): 251 | if from_coin == to_coin: 252 | continue 253 | pair = session.merge(self.get_pair(from_coin, to_coin)) 254 | pair.ratio = ratio 255 | session.add(pair) 256 | 257 | os.rename(".current_coin_table", ".current_coin_table.old") 258 | self.logger.info(".current_coin_table renamed to .current_coin_table.old - " "You can now delete this file") 259 | 260 | 261 | class TradeLog: 262 | def __init__(self, db: Database, from_coin: Coin, to_coin: Coin, selling: bool): 263 | self.db = db 264 | session: Session 265 | with self.db.db_session() as session: 266 | from_coin = session.merge(from_coin) 267 | to_coin = session.merge(to_coin) 268 | self.trade = Trade(from_coin, to_coin, selling) 269 | session.add(self.trade) 270 | # Flush so that SQLAlchemy fills in the id column 271 | session.flush() 272 | self.db.send_update(self.trade) 273 | 274 | def set_ordered(self, alt_starting_balance, crypto_starting_balance, alt_trade_amount): 275 | session: Session 276 | with self.db.db_session() as session: 277 | trade: Trade = session.merge(self.trade) 278 | trade.alt_starting_balance = alt_starting_balance 279 | trade.alt_trade_amount = alt_trade_amount 280 | trade.crypto_starting_balance = crypto_starting_balance 281 | trade.state = TradeState.ORDERED 282 | self.db.send_update(trade) 283 | 284 | def set_complete(self, crypto_trade_amount): 285 | session: Session 286 | with self.db.db_session() as session: 287 | trade: Trade = session.merge(self.trade) 288 | trade.crypto_trade_amount = crypto_trade_amount 289 | trade.state = TradeState.COMPLETE 290 | self.db.send_update(trade) 291 | 292 | 293 | if __name__ == "__main__": 294 | database = Database(Logger(), Config()) 295 | database.create_database() 296 | -------------------------------------------------------------------------------- /binance_trade_bot/logger.py: -------------------------------------------------------------------------------- 1 | import logging.handlers 2 | 3 | from .notifications import NotificationHandler 4 | 5 | 6 | class Logger: 7 | Logger = None 8 | NotificationHandler = None 9 | 10 | def __init__(self, logging_service="crypto_trading", enable_notifications=True): 11 | # Logger setup 12 | self.Logger = logging.getLogger(f"{logging_service}_logger") 13 | self.Logger.setLevel(logging.DEBUG) 14 | self.Logger.propagate = False 15 | formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 16 | # default is "logs/crypto_trading.log" 17 | fh = logging.FileHandler(f"logs/{logging_service}.log") 18 | fh.setLevel(logging.DEBUG) 19 | fh.setFormatter(formatter) 20 | self.Logger.addHandler(fh) 21 | 22 | # logging to console 23 | ch = logging.StreamHandler() 24 | ch.setLevel(logging.INFO) 25 | ch.setFormatter(formatter) 26 | self.Logger.addHandler(ch) 27 | 28 | # notification handler 29 | self.NotificationHandler = NotificationHandler(enable_notifications) 30 | 31 | def log(self, message, level="info", notification=True): 32 | if level == "info": 33 | self.Logger.info(message) 34 | elif level == "warning": 35 | self.Logger.warning(message) 36 | elif level == "error": 37 | self.Logger.error(message) 38 | elif level == "debug": 39 | self.Logger.debug(message) 40 | 41 | if notification and self.NotificationHandler.enabled: 42 | self.NotificationHandler.send_notification(str(message)) 43 | 44 | def info(self, message, notification=True): 45 | self.log(message, "info", notification) 46 | 47 | def warning(self, message, notification=True): 48 | self.log(message, "warning", notification) 49 | 50 | def error(self, message, notification=True): 51 | self.log(message, "error", notification) 52 | 53 | def debug(self, message, notification=False): 54 | self.log(message, "debug", notification) 55 | -------------------------------------------------------------------------------- /binance_trade_bot/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .base import Base 2 | from .coin import Coin 3 | from .coin_value import CoinValue, Interval 4 | from .current_coin import CurrentCoin 5 | from .pair import Pair 6 | from .scout_history import ScoutHistory 7 | from .trade import Trade, TradeState 8 | -------------------------------------------------------------------------------- /binance_trade_bot/models/base.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | 3 | Base = declarative_base() 4 | -------------------------------------------------------------------------------- /binance_trade_bot/models/coin.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Boolean, Column, String 2 | 3 | from .base import Base 4 | 5 | 6 | class Coin(Base): 7 | __tablename__ = "coins" 8 | symbol = Column(String, primary_key=True) 9 | enabled = Column(Boolean) 10 | 11 | def __init__(self, symbol, enabled=True): 12 | self.symbol = symbol 13 | self.enabled = enabled 14 | 15 | def __add__(self, other): 16 | if isinstance(other, str): 17 | return self.symbol + other 18 | if isinstance(other, Coin): 19 | return self.symbol + other.symbol 20 | raise TypeError(f"unsupported operand type(s) for +: 'Coin' and '{type(other)}'") 21 | 22 | def __repr__(self): 23 | return f"[{self.symbol}]" 24 | 25 | def info(self): 26 | return {"symbol": self.symbol, "enabled": self.enabled} 27 | -------------------------------------------------------------------------------- /binance_trade_bot/models/coin_value.py: -------------------------------------------------------------------------------- 1 | import enum 2 | from datetime import datetime as _datetime 3 | 4 | from sqlalchemy import Column, DateTime, Enum, Float, ForeignKey, Integer, String 5 | from sqlalchemy.ext.hybrid import hybrid_property 6 | from sqlalchemy.orm import relationship 7 | 8 | from .base import Base 9 | from .coin import Coin 10 | 11 | 12 | class Interval(enum.Enum): 13 | MINUTELY = "MINUTELY" 14 | HOURLY = "HOURLY" 15 | DAILY = "DAILY" 16 | WEEKLY = "WEEKLY" 17 | 18 | 19 | class CoinValue(Base): 20 | __tablename__ = "coin_value" 21 | 22 | id = Column(Integer, primary_key=True) 23 | 24 | coin_id = Column(String, ForeignKey("coins.symbol")) 25 | coin = relationship("Coin") 26 | 27 | balance = Column(Float) 28 | usd_price = Column(Float) 29 | btc_price = Column(Float) 30 | 31 | interval = Column(Enum(Interval)) 32 | 33 | datetime = Column(DateTime) 34 | 35 | def __init__( 36 | self, 37 | coin: Coin, 38 | balance: float, 39 | usd_price: float, 40 | btc_price: float, 41 | interval=Interval.MINUTELY, 42 | datetime: _datetime = None, 43 | ): 44 | self.coin = coin 45 | self.balance = balance 46 | self.usd_price = usd_price 47 | self.btc_price = btc_price 48 | self.interval = interval 49 | self.datetime = datetime or _datetime.now() 50 | 51 | @hybrid_property 52 | def usd_value(self): 53 | if self.usd_price is None: 54 | return None 55 | return self.balance * self.usd_price 56 | 57 | @usd_value.expression 58 | def usd_value(self): 59 | return self.balance * self.usd_price 60 | 61 | @hybrid_property 62 | def btc_value(self): 63 | if self.btc_price is None: 64 | return None 65 | return self.balance * self.btc_price 66 | 67 | @btc_value.expression 68 | def btc_value(self): 69 | return self.balance * self.btc_price 70 | 71 | def info(self): 72 | return { 73 | "balance": self.balance, 74 | "usd_value": self.usd_value, 75 | "btc_value": self.btc_value, 76 | "datetime": self.datetime.isoformat(), 77 | } 78 | -------------------------------------------------------------------------------- /binance_trade_bot/models/current_coin.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from sqlalchemy import Column, DateTime, ForeignKey, Integer, String 4 | from sqlalchemy.orm import relationship 5 | 6 | from .base import Base 7 | from .coin import Coin 8 | 9 | 10 | class CurrentCoin(Base): # pylint: disable=too-few-public-methods 11 | __tablename__ = "current_coin_history" 12 | id = Column(Integer, primary_key=True) 13 | coin_id = Column(String, ForeignKey("coins.symbol")) 14 | coin = relationship("Coin") 15 | datetime = Column(DateTime) 16 | 17 | def __init__(self, coin: Coin): 18 | self.coin = coin 19 | self.datetime = datetime.utcnow() 20 | 21 | def info(self): 22 | return {"datetime": self.datetime.isoformat(), "coin": self.coin.info()} 23 | -------------------------------------------------------------------------------- /binance_trade_bot/models/pair.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column, Float, ForeignKey, Integer, String, func, or_, select 2 | from sqlalchemy.orm import column_property, relationship 3 | 4 | from .base import Base 5 | from .coin import Coin 6 | 7 | 8 | class Pair(Base): 9 | __tablename__ = "pairs" 10 | 11 | id = Column(Integer, primary_key=True) 12 | 13 | from_coin_id = Column(String, ForeignKey("coins.symbol")) 14 | from_coin = relationship("Coin", foreign_keys=[from_coin_id], lazy="joined") 15 | 16 | to_coin_id = Column(String, ForeignKey("coins.symbol")) 17 | to_coin = relationship("Coin", foreign_keys=[to_coin_id], lazy="joined") 18 | 19 | ratio = Column(Float) 20 | 21 | enabled = column_property( 22 | select([func.count(Coin.symbol) == 2]) 23 | .where(or_(Coin.symbol == from_coin_id, Coin.symbol == to_coin_id)) 24 | .where(Coin.enabled.is_(True)) 25 | .scalar_subquery() 26 | ) 27 | 28 | def __init__(self, from_coin: Coin, to_coin: Coin, ratio=None): 29 | self.from_coin = from_coin 30 | self.to_coin = to_coin 31 | self.ratio = ratio 32 | 33 | def __repr__(self): 34 | return f"<{self.from_coin_id}->{self.to_coin_id} :: {self.ratio}>" 35 | 36 | def info(self): 37 | return { 38 | "from_coin": self.from_coin.info(), 39 | "to_coin": self.to_coin.info(), 40 | "ratio": self.ratio, 41 | } 42 | -------------------------------------------------------------------------------- /binance_trade_bot/models/scout_history.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String 4 | from sqlalchemy.ext.hybrid import hybrid_property 5 | from sqlalchemy.orm import relationship 6 | 7 | from .base import Base 8 | from .pair import Pair 9 | 10 | 11 | class ScoutHistory(Base): 12 | __tablename__ = "scout_history" 13 | 14 | id = Column(Integer, primary_key=True) 15 | 16 | pair_id = Column(String, ForeignKey("pairs.id")) 17 | pair = relationship("Pair") 18 | 19 | target_ratio = Column(Float) 20 | current_coin_price = Column(Float) 21 | other_coin_price = Column(Float) 22 | 23 | datetime = Column(DateTime) 24 | 25 | def __init__( 26 | self, 27 | pair: Pair, 28 | target_ratio: float, 29 | current_coin_price: float, 30 | other_coin_price: float, 31 | ): 32 | self.pair = pair 33 | self.target_ratio = target_ratio 34 | self.current_coin_price = current_coin_price 35 | self.other_coin_price = other_coin_price 36 | self.datetime = datetime.utcnow() 37 | 38 | @hybrid_property 39 | def current_ratio(self): 40 | return self.current_coin_price / self.other_coin_price 41 | 42 | def info(self): 43 | return { 44 | "from_coin": self.pair.from_coin.info(), 45 | "to_coin": self.pair.to_coin.info(), 46 | "current_ratio": self.current_ratio, 47 | "target_ratio": self.target_ratio, 48 | "current_coin_price": self.current_coin_price, 49 | "other_coin_price": self.other_coin_price, 50 | "datetime": self.datetime.isoformat(), 51 | } 52 | -------------------------------------------------------------------------------- /binance_trade_bot/models/trade.py: -------------------------------------------------------------------------------- 1 | import enum 2 | from datetime import datetime 3 | 4 | from sqlalchemy import Boolean, Column, DateTime, Enum, Float, ForeignKey, Integer, String 5 | from sqlalchemy.orm import relationship 6 | 7 | from .base import Base 8 | from .coin import Coin 9 | 10 | 11 | class TradeState(enum.Enum): 12 | STARTING = "STARTING" 13 | ORDERED = "ORDERED" 14 | COMPLETE = "COMPLETE" 15 | 16 | 17 | class Trade(Base): # pylint: disable=too-few-public-methods 18 | __tablename__ = "trade_history" 19 | 20 | id = Column(Integer, primary_key=True) 21 | 22 | alt_coin_id = Column(String, ForeignKey("coins.symbol")) 23 | alt_coin = relationship("Coin", foreign_keys=[alt_coin_id], lazy="joined") 24 | 25 | crypto_coin_id = Column(String, ForeignKey("coins.symbol")) 26 | crypto_coin = relationship("Coin", foreign_keys=[crypto_coin_id], lazy="joined") 27 | 28 | selling = Column(Boolean) 29 | 30 | state = Column(Enum(TradeState)) 31 | 32 | alt_starting_balance = Column(Float) 33 | alt_trade_amount = Column(Float) 34 | crypto_starting_balance = Column(Float) 35 | crypto_trade_amount = Column(Float) 36 | 37 | datetime = Column(DateTime) 38 | 39 | def __init__(self, alt_coin: Coin, crypto_coin: Coin, selling: bool): 40 | self.alt_coin = alt_coin 41 | self.crypto_coin = crypto_coin 42 | self.state = TradeState.STARTING 43 | self.selling = selling 44 | self.datetime = datetime.utcnow() 45 | 46 | def info(self): 47 | return { 48 | "id": self.id, 49 | "alt_coin": self.alt_coin.info(), 50 | "crypto_coin": self.crypto_coin.info(), 51 | "selling": self.selling, 52 | "state": self.state.value, 53 | "alt_starting_balance": self.alt_starting_balance, 54 | "alt_trade_amount": self.alt_trade_amount, 55 | "crypto_starting_balance": self.crypto_starting_balance, 56 | "crypto_trade_amount": self.crypto_trade_amount, 57 | "datetime": self.datetime.isoformat(), 58 | } 59 | -------------------------------------------------------------------------------- /binance_trade_bot/notifications.py: -------------------------------------------------------------------------------- 1 | import queue 2 | import threading 3 | from os import path 4 | 5 | import apprise 6 | 7 | APPRISE_CONFIG_PATH = "config/apprise.yml" 8 | 9 | 10 | class NotificationHandler: 11 | def __init__(self, enabled=True): 12 | if enabled and path.exists(APPRISE_CONFIG_PATH): 13 | self.apobj = apprise.Apprise() 14 | config = apprise.AppriseConfig() 15 | config.add(APPRISE_CONFIG_PATH) 16 | self.apobj.add(config) 17 | self.queue = queue.Queue() 18 | self.start_worker() 19 | self.enabled = True 20 | else: 21 | self.enabled = False 22 | 23 | def start_worker(self): 24 | threading.Thread(target=self.process_queue, daemon=True).start() 25 | 26 | def process_queue(self): 27 | while True: 28 | message, attachments = self.queue.get() 29 | 30 | if attachments: 31 | self.apobj.notify(body=message, attach=attachments) 32 | else: 33 | self.apobj.notify(body=message) 34 | self.queue.task_done() 35 | 36 | def send_notification(self, message, attachments=None): 37 | if self.enabled: 38 | self.queue.put((message, attachments or [])) 39 | -------------------------------------------------------------------------------- /binance_trade_bot/scheduler.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import logging 3 | from traceback import format_exc 4 | 5 | from schedule import Job, Scheduler 6 | 7 | 8 | class SafeScheduler(Scheduler): 9 | """ 10 | An implementation of Scheduler that catches jobs that fail, logs their 11 | exception tracebacks as errors, and keeps going. 12 | 13 | Use this to run jobs that may or may not crash without worrying about 14 | whether other jobs will run or if they'll crash the entire script. 15 | """ 16 | 17 | def __init__(self, logger: logging.Logger, rerun_immediately=True): 18 | self.logger = logger 19 | self.rerun_immediately = rerun_immediately 20 | 21 | super().__init__() 22 | 23 | def _run_job(self, job: Job): 24 | try: 25 | super()._run_job(job) 26 | except Exception: # pylint: disable=broad-except 27 | self.logger.error(f"Error while {next(iter(job.tags))}...\n{format_exc()}") 28 | job.last_run = datetime.datetime.now() 29 | if not self.rerun_immediately: 30 | # Reschedule the job for the next time it was meant to run, instead of 31 | # letting it run 32 | # next tick 33 | job._schedule_next_run() # pylint: disable=protected-access 34 | -------------------------------------------------------------------------------- /binance_trade_bot/strategies/README.md: -------------------------------------------------------------------------------- 1 | # Strategies 2 | You can add your own strategy to this folder. The filename must end with `_strategy.py`, 3 | and contain the following: 4 | 5 | ```python 6 | from binance_trade_bot.auto_trader import AutoTrader 7 | 8 | class Strategy(AutoTrader): 9 | 10 | def scout(self): 11 | # Your custom scout method 12 | 13 | ``` 14 | 15 | Then, set your `strategy` configuration to your strategy name. If you named your file 16 | `custom_strategy.py`, you'd need to put `strategy=custom` in your config file. 17 | 18 | You can put your strategy in a subfolder, and the bot will still find it. If you'd like to 19 | share your strategy with others, try using git submodules. 20 | 21 | Some premade strategies are listed below: 22 | ## `default` 23 | 24 | ## `multiple_coins` 25 | The bot is less likely to get stuck 26 | -------------------------------------------------------------------------------- /binance_trade_bot/strategies/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | 4 | 5 | def get_strategy(name): 6 | for dirpath, _, filenames in os.walk(os.path.dirname(__file__)): 7 | filename: str 8 | for filename in filenames: 9 | if filename.endswith("_strategy.py"): 10 | if filename.replace("_strategy.py", "") == name: 11 | spec = importlib.util.spec_from_file_location(name, os.path.join(dirpath, filename)) 12 | module = importlib.util.module_from_spec(spec) 13 | spec.loader.exec_module(module) 14 | return module.Strategy 15 | return None 16 | -------------------------------------------------------------------------------- /binance_trade_bot/strategies/default_strategy.py: -------------------------------------------------------------------------------- 1 | import random 2 | import sys 3 | from datetime import datetime 4 | 5 | from binance_trade_bot.auto_trader import AutoTrader 6 | 7 | 8 | class Strategy(AutoTrader): 9 | def initialize(self): 10 | super().initialize() 11 | self.initialize_current_coin() 12 | 13 | def scout(self): 14 | """ 15 | Scout for potential jumps from the current coin to another coin 16 | """ 17 | current_coin = self.db.get_current_coin() 18 | # Display on the console, the current coin+Bridge, so users can see *some* activity and not think the bot has 19 | # stopped. Not logging though to reduce log size. 20 | print( 21 | f"{datetime.now()} - CONSOLE - INFO - I am scouting the best trades. " 22 | f"Current coin: {current_coin + self.config.BRIDGE} ", 23 | end="\r", 24 | ) 25 | 26 | current_coin_price = self.manager.get_ticker_price(current_coin + self.config.BRIDGE) 27 | 28 | if current_coin_price is None: 29 | self.logger.info(f"Skipping scouting... current coin {current_coin + self.config.BRIDGE} not found") 30 | return 31 | 32 | self._jump_to_best_coin(current_coin, current_coin_price) 33 | 34 | def bridge_scout(self): 35 | current_coin = self.db.get_current_coin() 36 | if self.manager.get_currency_balance(current_coin.symbol) > self.manager.get_min_notional( 37 | current_coin.symbol, self.config.BRIDGE.symbol 38 | ): 39 | # Only scout if we don't have enough of the current coin 40 | return 41 | new_coin = super().bridge_scout() 42 | if new_coin is not None: 43 | self.db.set_current_coin(new_coin) 44 | 45 | def initialize_current_coin(self): 46 | """ 47 | Decide what is the current coin, and set it up in the DB. 48 | """ 49 | if self.db.get_current_coin() is None: 50 | current_coin_symbol = self.config.CURRENT_COIN_SYMBOL 51 | if not current_coin_symbol: 52 | current_coin_symbol = random.choice(self.config.SUPPORTED_COIN_LIST) 53 | 54 | self.logger.info(f"Setting initial coin to {current_coin_symbol}") 55 | 56 | if current_coin_symbol not in self.config.SUPPORTED_COIN_LIST: 57 | sys.exit("***\nERROR!\nSince there is no backup file, a proper coin name must be provided at init\n***") 58 | self.db.set_current_coin(current_coin_symbol) 59 | 60 | # if we don't have a configuration, we selected a coin at random... Buy it so we can start trading. 61 | if self.config.CURRENT_COIN_SYMBOL == "": 62 | current_coin = self.db.get_current_coin() 63 | self.logger.info(f"Purchasing {current_coin} to begin trading") 64 | self.manager.buy_alt(current_coin, self.config.BRIDGE) 65 | self.logger.info("Ready to start trading") 66 | -------------------------------------------------------------------------------- /binance_trade_bot/strategies/multiple_coins_strategy.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from binance_trade_bot.auto_trader import AutoTrader 4 | 5 | 6 | class Strategy(AutoTrader): 7 | def scout(self): 8 | """ 9 | Scout for potential jumps from the current coin to another coin 10 | """ 11 | have_coin = False 12 | 13 | # last coin bought 14 | current_coin = self.db.get_current_coin() 15 | current_coin_symbol = "" 16 | 17 | if current_coin is not None: 18 | current_coin_symbol = current_coin.symbol 19 | 20 | for coin in self.db.get_coins(): 21 | current_coin_balance = self.manager.get_currency_balance(coin.symbol) 22 | coin_price = self.manager.get_ticker_price(coin + self.config.BRIDGE) 23 | 24 | if coin_price is None: 25 | self.logger.info(f"Skipping scouting... current coin {coin + self.config.BRIDGE} not found") 26 | continue 27 | 28 | min_notional = self.manager.get_min_notional(coin.symbol, self.config.BRIDGE.symbol) 29 | 30 | if coin.symbol != current_coin_symbol and coin_price * current_coin_balance < min_notional: 31 | continue 32 | 33 | have_coin = True 34 | 35 | # Display on the console, the current coin+Bridge, so users can see *some* activity and not think the bot 36 | # has stopped. Not logging though to reduce log size. 37 | print( 38 | f"{datetime.now()} - CONSOLE - INFO - I am scouting the best trades. " 39 | f"Current coin: {coin + self.config.BRIDGE} ", 40 | end="\r", 41 | ) 42 | 43 | self._jump_to_best_coin(coin, coin_price) 44 | 45 | if not have_coin: 46 | self.bridge_scout() 47 | -------------------------------------------------------------------------------- /config/apprise_example.yml: -------------------------------------------------------------------------------- 1 | # Define version 2 | version: 1 3 | 4 | # Define your URLs (Mandatory!) 5 | # URLs should start with - (remove the comment symbol #) 6 | # Replace the values with your tokens/ids 7 | # For example a telegram URL would look like: 8 | # - tgram://123456789:AABx8iXjE5C-vG4SDhf6ARgdFgxYxhuHb4A/-606743502 9 | # Rename the file to `apprise.yml` 10 | urls: 11 | # - tgram://TOKEN/CHAT_ID 12 | # - discord://WebhookID/WebhookToken/ 13 | # - slack://tokenA/tokenB/tokenC 14 | # More options here: https://github.com/caronc/apprise 15 | -------------------------------------------------------------------------------- /data/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !/.gitignore 3 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | pylint-sqlalchemy 2 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | crypto-trading: 5 | image: edeng23/binance-trade-bot 6 | container_name: binance_trader 7 | working_dir: /app 8 | volumes: 9 | - ./user.cfg:/app/user.cfg 10 | - ./supported_coin_list:/app/supported_coin_list 11 | - ./data:/app/data 12 | - ./logs:/app/logs 13 | - ./config:/app/config 14 | command: python -m binance_trade_bot 15 | environment: 16 | - PYTHONUNBUFFERED=1 17 | 18 | api: 19 | image: edeng23/binance-trade-bot 20 | container_name: binance_trader_api 21 | working_dir: /app 22 | volumes: 23 | - ./user.cfg:/app/user.cfg 24 | - ./data:/app/data 25 | - ./logs:/app/logs 26 | ports: 27 | - 5123:5123 28 | command: gunicorn binance_trade_bot.api_server:app -k eventlet -w 1 --threads 1 -b 0.0.0.0:5123 29 | depends_on: 30 | - crypto-trading 31 | 32 | sqlitebrowser: 33 | image: ghcr.io/linuxserver/sqlitebrowser 34 | container_name: sqlitebrowser 35 | environment: 36 | - PUID=1000 37 | - PGID=1000 38 | - TZ=Europe/Berlin 39 | volumes: 40 | - ./data/config:/config 41 | - ./data:/data 42 | ports: 43 | - 3000:3000 44 | -------------------------------------------------------------------------------- /logs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/binance-trade-bot/55f8cbbe082bd083a722cba697f708a07f5add16/logs/.gitkeep -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-binance==1.0.27 2 | sqlalchemy==1.4.15 3 | schedule==1.1.0 4 | apprise==0.9.5.1 5 | Flask==2.3.2 6 | gunicorn==20.1.0 7 | flask-cors==3.0.10 8 | flask-socketio==5.0.1 9 | eventlet==0.30.2 10 | python-socketio[client]==5.2.1 11 | cachetools==4.2.2 12 | sqlitedict==1.7.0 13 | unicorn-binance-websocket-api==1.34.2 14 | unicorn-fy==0.11.0 15 | itsdangerous==2.0.1 16 | Werkzeug==2.0.3 -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.11 2 | -------------------------------------------------------------------------------- /supported_coin_list: -------------------------------------------------------------------------------- 1 | ADA 2 | ATOM 3 | BAT 4 | BTTC 5 | DASH 6 | DOGE 7 | EOS 8 | ETC 9 | ICX 10 | IOTA 11 | NEO 12 | OMG 13 | ONT 14 | QTUM 15 | TRX 16 | VET 17 | XLM 18 | XMR 19 | --------------------------------------------------------------------------------