This is a tutorial providing a minimal python program for a Binance email notifier. The example is with trade event notifications (i.e. when buys and sells happen etc.) but can be modified to suit your needs. It does not require extensive programming knowledge, as the code is provided and the instructions are step-by-step. Before reading make sure you have python3 installed (you can quickly get it from here). If there's any trouble along the way, please leave a comment and I'll try my best to get back.
Step 1: Installing python-binance library:
The python-binance library can be easily installed. Open a command prompt or bash and enter:
pip install python-binance
Step 2: Generating an API Key
The second step is setting up your Binance credentials so that you can interact with their API (In case you don't have a Binance account, consider making one with the following referral link: https://www.binance.com/en/register?ref=XSS4Y56N to receive a 10% discount off your trading fees). The official guide for setting your API keys can be found here, but I'll leave the steps below:
After logging into the Binance account, click API Management in the user center drop-down box. After entering the API management page, set an API key, and click Create. Security Tip: Before creating the API, you need to bind the secondary authentication.
- Click Get code, enter “Phone verification code”, “E-mail verification code” and “Google verification code”, then click Submit to create an API.
Remember to store your Secret Key somewhere safe. It will not be shown again. Due to security reasons, please do not share this key with anyone. (If you forget the Secret Key, you will need to delete the API then re-create a new one.)
Before moving forward, there are a few settings here that we need to take a look at. The Read Only option is selected by default, and you likely won’t be able to uncheck it.
This permits the API to read your account details and is enabled by default. Perhaps it is a bit misleading since it includes the term Only, but you can still perform other operations with this option checked. If you’re still testing out the API, it might be a good idea to leave these unchecked. If you’re ready to start trading, then check off the Enable Trading box and the Enable Future box if you plan to trade futures.
Step 3: Storing the API Key
You can store your API keys as environment variables. This minimizes the risk of revealing your credentials when sharing the code. This can be done via the command prompt. Here are the cmd commands for Windows users:
set binance_api=your_api_key_here set binance_secret=your_api_secret_here
export binance_api="your_api_key_here" export binance_secret="your_api_secret_here"
Add the above lines in your
.bashrc so you won't have to do this every time you open a shell. For Windows you will have to check if the commands above permanently store the information or not.
You can then later retrieve the key and secret through a python command line interface (CLI). Open a command prompt and run
import os os.environ.get('binance_api') os.environ.get('binance_secret')
Step 4: Setting up a Gmail SMTP password
This is a similar process to obtaining and storing the API key. In case you are using a different email provider, you will have to check how to setup python smtp with them. Access https://myaccount.google.com/ and go to Security on the left sidebar. Under Signing in to Google, go to App passwords:
There you should see something like this:
Select Mail for app and for device you can select anything. Once generated, you can then copy and store your password in the same way:
Step 5: The code
Open your favorite editor and paste the code below (make sure you modify
self.gmail_usr = "firstname.lastname@example.org" with your actual email).
import os import smtplib from binance.client import Client from binance.websockets import BinanceSocketManager from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart class BinanceConnection: def __init__(self): self.api_key = os.environ.get('binance_api') self.api_secret = os.environ.get('binance_secret') self.client = Client(self.api_key, self.api_secret) self.bsm = BinanceSocketManager(self.client) class MailSender: def __init__(self): self.gmail_usr = "email@example.com" self.gmail_passwd = os.environ.get('gmail_passwd') self.sent_from = self.gmail_usr self.to = self.gmail_usr def send_email_notification(self, _subject, _body): msg = MIMEMultipart('alternative') msg['Subject'] = _subject msg['From'] = self.sent_from msg['To'] = self.to msg.attach(MIMEText(_body,'plain')) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(self.gmail_usr, self.gmail_passwd) server.sendmail(self.sent_from, self.to, msg.as_string()) server.quit() print('Email sent!') except: print('Something went wrong with setting up gmail smtp..') # called by socket manager in case there's an account update def status_update(msg): if msg['e'] == 'executionReport' and not msg['X'] == 'PARTIALLY_FILLED': ms = MailSender() _subject = '[Python-API] Order ' + msg['X'] + ' [' + msg['s'] + ', ' + msg['S'] + ']' _body = 'OrdPrice: ' + msg['p'] + '\nOrigQty: ' + msg['q'] + '\nType: ' + msg['o'] if msg['o'] == 'STOP_LOSS_LIMIT': _body = _body + '\nStop price: ' + msg['P'] ms.send_email_notification(_subject, _body) bc = BinanceConnection() user_conn = bc.bsm.start_user_socket(status_update) bc.bsm.start() print("User socket active.")
To test it out you can open a command prompt and type
python3 'programName.py'. You should see the 'User socket active' message. Then you can open or cancel an order on Binance to see if you get an email. If all goes well you have an email notifier working on your PC. To not receive emails for every created or cancelled order you can add
and not msg['X'] == 'NEW' or
and not msg['X'] == 'CANCELED' after
if msg['e'] == 'executionReport' .
Keep in mind this is only an example. You can adapt the functionality with whatever you prefer. You can use a socket that gives live price of a trade pair or make non-socket API calls. There are many options, all of which you can see in the API documentation.
This can also be run on your phone, which can be an advantage as your phone is usually on all the time and can listen constantly for account trade changes. If this post gets enough interest, I will post a follow-up on how to run it on the phone. I use termux for that, which gives you linux like CLI on your phone.