Build a crypto back running trading bot

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

  1. Oracles, rebase tokens, large institutions, Defi applications, etc. submit different types of transactions to the blockchain
  2. A program monitors the blockchain’s transaction pool
  3. The program reviews all transactions in the pool for opportunities to back run
  4. Program identifies an opportunity. Transactions in the pool will trigger a future event (liquidation, arbitrage opportunity, etc.).
  5. The program submits a transaction in an attempt to be right after the target transaction in the same block

How does a crypto back running trading bot work

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.

crypto back running bot example in etherscan

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.

For hardware you can use a local pc, Digital Ocean, Amazon Web Services, etc. If you plan to build a local server to run consider one of the following options:

If you build your own machine consider the following hardware specifications or better:

Back running bot software

The bot software consists of an Operating System, blockchain node software and bot software in Python.

Operating System

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:

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.

Configuration

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.

Market Data

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():

Utilities

Create a component that contains utility functions that your application might need.

  • Functions to get gas information
  • Functions to obtain pair information
  • etc.
def get_eth_station_gas_price():

def get_max_gas_price():

def AMM_get_pair_address():

Trading functions

Create a generic trading component that allows you to submit different types to trades to the network.

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.

  1. Determine a back running strategy
  2. Make sure you research different strategies as some contracts have safe guards in place
  3. Monitor the tx_pool and inspect transactions
  4. Run them through your strategy
  5. If an opportunity exists submit one or multiple trades (multiple trades require using different accounts)
  6. 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.

Main

  • 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

Next – Deploy a smart contract to the Fantom Network

1 thought on “Build a crypto back running trading bot

Leave a Reply