Coding a DeFi Arbitrage Bot — part 2

Extropy.IO
14 min readNov 10, 2020

In the first part of this series we explained what arbitrage means in the context of decentralized finance and our chosen bot strategy for spotting profitable opportunities between decentralized exchanges.

In this second and final article we will conclude the arbitrage bot tutorial by diving in the code step by step, and illustrating alternative strategies and future improvements that readers could use in order to make the bot production ready, i.e. profitable.

Before we dive in, lets make a clarification about why the bot isn’t profitable as is; the code example is fully working and could be run with no customization, however, arbitrage is a zero-sum game, i.e. there is a finite amount of arbitrage opportunities and a lot of people who are competing to find and execute them first. We will see at the end of this article how to customize the bot with additional arbitrage strategies in order to be more competitive and to find opportunities before others do.

Project Structure

The entire bot is made up of just two core files basically:

  • index.js : a node.js app that continuously fetches crypto prices on exchanges looking for arbitrage opportunities, trying to guaranteee that the trade is possible before even attempting to execute it.
  • TradingBot.sol : a smart contract that gets called by the node app only when a profitable arbitrage is found, it will borrow funds with a flashloan and execute trades on decentralized exchanges.

Basic Setup

Deploy TradingBot.sol

In order to interact with the decentralized exchanges’ smart contracts, users need to deploy a smart contract of their own which handles all of the logic, from flashloans to trading.

We assume that readers are already familiar with deploying a smart contract using the Remix IDE, but we have summed up the steps below:

  • Install Metamask browser extension
  • Create an Ethereum Mainnet account with some ETH for paying gas fees.
  • Don’t use your personal account for this, create a new account for the bot in order to limit accidental losses (more on that later).
  • Go to Remix online IDE
  • Paste the smart contract solidity code
  • Compile the code using compiler version 0.5.17.

--

--

Extropy.IO

Oxford-based blockchain and zero knowledge consultancy and auditing firm