Binance - Receive Email when a Trade is Filled

Binance - Receive Email when a Trade is Filled

By ᛈレΛᚱIᛏᛉ | revtoki | 16 Sep 2020


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:

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.

api_created.jpg

src: https://algotrading101.com/learn/binance-python-api-guide/ 

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

For Linux/Mac:

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 python3, then:

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:

36ecf08f7d7e7fc79d2f9d6b2a56774d3c21bd81f730287e2e7283ded16e0e20.png

 

There you should see something like this:

6b59433b1f897bea20541f92366a01d279dd13b72d0e4f092544d2dbc08369b3.png

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:

set gmail_passwd=your_mail_passwd
export gmail_passwd="your_mail_passwd"

Step 5: The code

Open your favorite editor and paste the code below (make sure you modify self.gmail_usr = "your_email@foo.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 = "your_email@foo.org"
		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' .

Follow-Up:

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.



revtoki
revtoki

Engineering blog

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.