Build a crypto back running trading bot. Back running is the strategy of having a transaction next in line right after a transaction that would benefit you. An example of back running is a liquidation transaction immediately following an oracle price update. Back running is the process of having a transaction included in the same block right after the target transaction.
How does a crypto back running trading bot work
- Oracles, rebase tokens, large institutions, Defi applications, etc. submit different types of transactions to the blockchain
- A program monitors the blockchain’s transaction pool
- The program reviews all transactions in the pool for opportunities to back run
- Program identifies an opportunity. Transactions in the pool will trigger a future event (liquidation, arbitrage opportunity, etc.).
- The program submits a transaction in an attempt to be right after the target transaction in the same block
Examples of crypto back running
Transactions in the pool create opportunities that didn’t exist before they were mined. A few examples of back running target transactions are:
- An Oracle price transaction will cause an account to be liquidated in the next block. In this case you would want your back running transaction to be include right after the oracle price change transaction in the same block.
- A large trade will cause an arbitrage opportunity on Uniswap in the next block. You want your trade to be right after the large trade and in the same block but before your competition.
- Rebase tokens (example AMPL) create opportunities when rebasing occurs. After the rebase transaction you submit a trade to the Uniswap pool that is out of balance.
- There are many other opportunities that exist in the defi ecosystem.
The goal of crypto back running is to have your transaction included in the same block as the target transaction. This results in arbitrage opportunities not existing for your competition.
In the example below you can see the Compound Oracle transaction (circled in green) and 0x7b2ef transactions before and after it in an attempt to be the next transactions in line. In the example below back running bots need to send more then one transaction to increase the odds to be next inline after the Compound Oracle transaction.
Ultimately miners decide how to sort transactions to include in the next block. Transaction in the same block for the same gas price are ordered by (FIFO) first in first out. So some back running bots will submit multiple transactions from different accounts. This might result in a higher probability of one of their transactions processing right after the target transaction. Unfortunately this adds spam transactions to the network.
Build a crypto back running trading bot
Your bot needs to be smart and fast to be successful. It takes time to build a bot that is sophisticated enough to win trades. To help you get started below are items to consider.
Back running bot hardware
The bot and blockchain node need to run on the same machine. The bot needs to inspect the transaction pool and blockchain many times per second. In a world of speed it is imperative that the bot and node run on the same machine.
If you build your own machine consider the following hardware specifications or better:
- AMD Ryzen 5 3600 6-Core 12-Thread cpu
- Sabrent 1TB Rocket NVMe 4.0 Gen4 PCIe M.2 Internal SSD.
- ASUS Prime B550M-A motherboard
Back running bot software
The bot software consists of an Operating System, blockchain node software and bot software in Python.
Save yourself the hassle and setup a Linux ubuntu server.
Running a blockchain node
You can run your liquidation bot on any machine that is operating an Ethereum node and available 24 hours a day 7 days a week. A few options are as follows:
- Operate a Geth Node and your choice of hardware
- Quick Node and your choice of hardware
- Infra and your choice of hardware
- Alchemy Super node and your choice of hardware
Building a crypto back running trading bot in Python
When building a back running trading bot organize your code and plan for enhancements. Below are some simple ideas on how to structure your project.
Create a configuration component that contains the following information:
- Node connection information to the test environment and the main net environment. IPC is the fastest way to obtain data from the node
- Addresses, abi and fee information for each decentralized exchange or Defi protocol
- All token assets that I wanted to monitor and their configuration
######## Production Environment ######## #connection information node_url = 'urltonode' web3 = Web3(Web3.IPCProvider(node_url)) #AMM exchanges uniswap_network_address = 'address' uniswap_network_abi = json.loads(xxxxx) #lending compound_network_address = 'address' compound_network_abi = json.loads(xxxxx) #tokens USDC_address = 'address' WETH_address = 'address' etc.
Create a market data component to capture pricing information from different sources.
- Functions to get a pricing information for a particular token on Uniswap, Pancake Swap, etc.
- Function to get supply and lending rates
def stream_pancake_prices(): def stream_uniswap_prices():
Create a component that contains utility functions that your application might need.
- Functions to get gas information
- Functions to obtain pair information
def get_eth_station_gas_price(): def get_max_gas_price(): def AMM_get_pair_address():
Create a generic trading component that allows you to submit different types to trades to the network.
- Function to submit an individual trade directly to each of the on chain decentralized exchanges
- Function to submit trades to your smart contract to perform a token swap or flash loan arbitrage
def submit_single_trade(): def submit_swap(): def submit_flashloan():
Back running functions
This is the brains of the program and will take the most time to write. The program needs to take all the transaction in the pool and run them through multiple function. Consider making these processes multi threaded for speed and performance.
- Determine a back running strategy
- Make sure you research different strategies as some contracts have safe guards in place
- Monitor the tx_pool and inspect transactions
- Run them through your strategy
- If an opportunity exists submit one or multiple trades (multiple trades require using different accounts)
- Check on the trade you submitted and make adjustments to it if necessary or if competition exists
import threading #An Oracle price transaction causes an account to be liquidated in the next block. #Uniswap receives a large trade that causes an arbitrage opportunity in the next block. #After the rebase transaction you submit a trade to the Uniswap pool that is out of balance.
- Consider main.py to be multi process
if __name__ == '__main__': processes =  for _ in range(2): x_backrunningfunction_process = multiprocessing.Process(target=backrunningfunctions) x_backrunningfunction_process.start() processes.append(x_backrunningfunction_process) y_backrunningfunction_process = multiprocessing.Process(target=backrunningfunctions) y_backrunningfunction_process.start() processes.append(x_backrunningfunction_process) for process in processes: process.join()
These are the basics to help you start building a crypto back running trading bot.
This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.
Blockchains to build and test on
- Click here for information about how to use the Ethereum test network and how to obtain test ETH.
- For information about how to use the Binance Smart Chain and how to obtain test BNB
- Click here for information about how to use the Polygon test network and how to obtain test ETH.