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