Binance trading bot python

Build Crypto Bitcoin Trading Bot with Python Binance CCXT — How To Video Tutorials with Code

Building a Crypto Trading Bot with Python on Binance: A series of tutorials, blog posts, videos and discussion around Algo Trading with Cryptocurrency such as Bitcoin and Ethereum

Blockchain Engineer — Crypto Trading Bots

Apr 20, 2018 · 6 min read

Welcome to ‘Building a Crypto Trading Bot in Python’ web-based tutorial series.

This Medium post will serve as a centralized location for the Youtube Tutorials, Github Code, and links to further reading for this project, which has grown quite extensive with a large community, numerous tutorials, and code which is ready to be deployed on your own system in order to begin trading cryptocurrencies algorithmic with a bot.

I suggest that you bookmark this page in order to return to it while learning about crypto trading bots, as there is quite a lot of material available and I will do my best to this post as a centralized location and ‘guide’ to the material.

Thank you for your interest in this project, my intentions are for you to have learned enough for this course to be able to run, design and develop your own crypto trading strategies!

Introduction to Crypto Trading Bots with Python

Hello and welcome to my post discussing “building an automated cryptocurrency trading bot on Binance with Python”. I begun working on this project in April 2018 due to my interest in cryptocurrency trading, and my previous education and skills with python computer programming.

The goals for this project is to create an open-source software which will trade cryptocurrency on an exchange, such as binance, using strategies to maximize profit while reducing risk.

The main motivation for this project is to create an open-source crypto-trading software that anyone can download, edit & customize to implement their own trading strategies.

There exist many crypto trader bots available, but I believe that a solution where the code is open-source and can be customized to each trader’s goals, time horizon & risk profile is desirable.

Many of the available trading bots are proprietary, while others are in languages other than python (Such as Gekko Trading Bot Software). I wanted a python bot so I could run it on my own computer, and keep tight control over the private keys.

To gain a proper understanding of the goals of this project, please watch the introductory video below:

Cryptocurrency Trading: Numerous Opportunities (and Risks)

Problem: Cryptocurrency is a new form of money created around the year 2009 through a white-paper introduced by Satoshi Nakamoto to digitize and store ‘value’ through the internet, known as Bitcoin. Since this time, thousands of other cryptocurrencies have been created enabling a tremendous opportunity for future globally-facilitated transactions.

The current market valuation for all cryptocurrencies is near $400 billion USD at the time of writing, presenting a tremendous opportunity for growth of invested capital as evidenced by the drastic increase in cryptocurrency prices and market caps in 2017.

On the opposite side of this opportunity, the cryptocurrency market contains high volatility and numerous risks.

Much of the current wisdom about cryptocurrency investing is based around ‘buy & hodl’, but an automated solution is desired with the aims of preserving & increasing invested capital with limited trader involvement. Given the tremendous opportunity (and equally large risks involved), a software is desired to aid investment in cryptocurrency by both newbies & experienced cryptocurrency investors.

Design of Cryptocurrency Trading Software

Solution: A software solution is required which can invest funds in cryptocurrency markets (such as Binance) which will buy, sell and hold according to various strategies to increase profit in a way that is easily managed, highly reliable and autonomous.

Читайте также:  Как легально вывести биткоины

Automated Trading Bots are very common on major stock exchanges such as the New York Stock Exchange due to their functionality, speed and pre-defined trading rules.

Crypto Trading Bot Youtube Series

In addition to blog posts and podcasts about this topic, I will create a new video series I will be doing on Youtube titled ‘How To Build an Automated Trading Bot (on Binance with Python)’, which is a technical guide to building a trading bot that will:

  • Purchase and Sell cryptocurrency on the Binance Exchange in a way which maximizes Return on Investment while Reducing Risk.
  • Portfolio Management- Create a daily/weekly/monthly profit & loss statement Tracking Wins & Losses, an ‘index’ of 25 largest Market Cap Coins.
  • Easily customizable while ability to start running as packaged, varying time horizons, risk profile.

I am interested to create an automated algorithmic bot for trading cryptocurrencies due to the advantages of bots and the capabilities provided by software. I documented almost every portion of this journey so that anyone else who would like to modify or replicate the binance trader bot code would be well-informed on many of the design choices I made while building this bot.

Источник

Binance trading bot python

Python bot for trading on the Binance cryptocurrency exchange.

There are two strategies, cross-pair arbitrage and breakout trend trading.

  • mult_arbit.py
  • price_monitor.py
  • run_mult_arbit.py

The point is to turn altcoins into more altcoins. In optimal conditions it can cycle multiple times a minute. It only works in a very specific context:

  • You have to be in a low-fee environment. Any fee above 0.1% kills it, it works on a 0.5% margin trigger over three trades.
  • The altcoin you’re going for has to trade against two base coins that also trade against each other.

So if you’re doing XLM on Binance examples are:

WARNING: This strategy is super risky. It works best when all three pairs are trading sideways or trending gently. The bot knows nothing about market status other than current price ratios; rapid price swings can easily leave you mid-cycle holding a bag you don’t want. Like this strategy? Check out Rockfish, which implements a similar strategy for the Stellar Decentralized Exchange.

Breakout trend trading:

This strategy looks for X period high/low breakouts and bets with the break direction. It’s inspired by the turtle traders who did commodities in the 1980s (http://www.tradingblox.com/originalturtles/). They were trading on 10-day breakouts, which is far too slow for cryptocurrency exchanges, so the bot is set to X hours, not days. Problem is that according to my testing it barely breaks even (or goes negative) on all breakout ranges I’ve tested.

WARNING: As this strategy currently stands it does not profit. If you want to try it backtest it hard!

Both strategies need these files:

  • api.py
  • data_checks.py
  • excepts.py
  • log.py

(Standard disclaimer saying this isn’t investment advice and bots can lose your money real fast. No warranties, etc. etc.)

Install instructions as requested in an issue:

There is no fancy install; you set up a local Python virtual environment as you would any other, drop the .py files into the directory, revise the parameter sections that refer to certain coins and the rules for them, and run the desired executor file (run_mult_arbit.py or run_turtle.py). You need to create an API key on your Binance account and add the key and secret where indicated near the top of the files as [API key] and [API secret]. The log text files will generate into the directory.

For my developer environment I use PyCharm: https://www.jetbrains.com/pycharm/. There are many other IDEs, or you can do it on the command line as explained at https://packaging.python.org/guides/installing-using-pip-and-virtualenv/.

If you’re new to crypto trading I strongly recommend you acclimate with some manual trading; if you just run the bot without context knowledge you’ll have a bad time.

About

Python bot for trading on the Binance cryptocurrency exchange

Источник

A trading bot in python code for Binance Futures

Is it possible code a python program to trade? Yes, it is.
Is it profitable? Well, it depends.

Today I want to code a python trading bot, that execute all action autonomously.

The strategy

The idea is to check two technical indicators: the weight moving average with period=7 (WMA7) and with period=14 (WMA14).
I suggest you to check the link for a more detailed explanation.

Читайте также:  Коэффициент бета равен 0 доходность

How to Use a Moving Average to Buy Stocks

The moving average (MA) is a simple technical analysis tool that smooths out price data by creating a constantly…

The signals to evaluate are:

  • Sell: if the WMA7 cross up the WMA14.
  • Buy: if the WMA7 cross down the WMA14.

Let’s check an hypothetical case. I consider the BTCUSDT price.

As shown in the figure the strategy in same case works, but NOT always. So now we have to implement in python.

Let’s Code

Register account on Binance

With Binance we can test our strategy in live, using the testnet account.
The only thing that we need is the api key.

Install Libraries

Then we have to install some libraries:

We have to install also a library for the technical indicator, the TA-Lib.
To do that we need to download ta-lib-0.4.0-src.tar.gz, and than we have to execute this command:

Unfortunately the python-binance library doesn’t work completely with a demo account, so we integrate it downloading this file.

The Code

Now we start to code.
First we import the libraries, and set the api key and the secret key.

In order to mange the order and check the signal we define a class.

The get_signal function take the last 40 minutes data from Binance. We are interesting to the close price, because we can calculate the weight moving average. Than with data[‘action’] we know if there is a cross between WMA7 and WMA14.

When WMA7>WMA14 the data[‘action’] is equal to 1 and this is the buy signal.
The opposite when WMA7

In addition to performing the order, there are some variables that track our performance.

Indeed the last function is to plot the performance.

The class Order is defined,and we can call the class in the main.

The dataset indicates the cryptocurrency to trade. The path indicate where to store the performance plot.
The while permits to get the signal every minute and execute the action.

That it’s. now you are able to code a simplistic trading bot. I want to emphasize this bot is only to show how code a python bot and how to connect it with Binance. But probably in a long run it is not a profitable bot.

Источник

Binance trading bot python

Automated cryptocurrency trading bot

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.

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.

Coin A → USDT → Coin B

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.

Coin A → USDT → Coin B

Coin B → USDT → Coin C

Coin C → USDT → Coin A

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.

  • Create a Binance account (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.

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.

Читайте также:  Bitcoin mining bitcoin core

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.
  • 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_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.
  • strategy — The trading strategy to use. See binance_trade_bot/strategies 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.

All of the options provided in user.cfg can also be configured using environment variables.

Paying Fees with BNB

You can use BNB to pay for any fees on the Binance platform, 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.

The official image is available here and will update on every new change.

If you only want to start the SQLite browser

You can test the bot on historic data to see how it performs.

Feel free to modify that file to test and compare different settings and time periods

To make sure your code is properly formatted before making a pull request, remember to install pre-commit:

The scouting algorithm is unlikely to be changed. If you’d like to contribute an alternative method, add a new strategy.

Thanks to a group of talented developers, there is now a Telegram bot for remotely managing this project.

Support the Project

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.

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.

Источник

Оцените статью