Arbitraging Between DEXes and CEXes for Fun & Profit

Perp-curie-arbitrageur is an open-sourced template that automatically executes your arbitrage strategy between Perpetual Protocol v2 “Curie” and FTX.

In this blog post, we’ll cover what Perpetual Protocol v2 is, the risks and rewards of running this bot, how you can run it on your computer and on AWS, and further modification suggestions.

Perpetual Protocol 101

Perpetual Protocol, or Perp v2 “Curie” specifically, is a decentralized derivative exchange (DEX) on Optimism where traders can use USDC (a USD-backed stablecoin) to speculate on cryptocurrency’s price movement with up to 10x leverage. You can open a long position if you believe one asset’s price will go up or open short positions if you expect it will go down. At the time of writing, the DEX supports 17around 20 markets, including BTC, ETH, ATOM, BNB, and more!

You can learn how it works in detail by watching this 10-minute video or reading this article.

Risks and Rewards of Running Perp-curie-arbitrageur

The way perp-curie-arbitrageur works is that, whenever there is a price difference between Perp v2 (a derivative DEX) and FTX (a CEX), the bot will buy on the cheaper side and sell on the more expensive side. Out of the box, this template allows you to set the desired price difference for the bot to take action. Additionally, you can specify the markets for the bot to run the arbitrage strategy.

Of course, we can’t just look at the rewards. How about the risks associated with running this bot?

The main risk is liquidation, which can happen when you use too much leverage to trade on either Perp v2 or FTX. Luckily, the bot lets you set the margin ratio you’re comfortable with, which is the reciprocal of leverage, and it will start to reduce the position sizes whenever the margin ratio is reached.

Setting the Stage

If you consider yourself an experienced programmer, you should have no problem setting up the bot by the readme in the perp-curie-arbitrageur repo.

In the previous sections, we learned what Perp v2 is and the risks and rewards of running an arbitraging bot on the platform. This section will go through the steps to set up a bot on your computer. You can join our Discord server where we have a #coding-chat channel for questions you encounter when building on top of Perp v2.

First, you need to download and install Node.JS on your computer, which comes along with the Node Package Manager (npm) that we need.

Once installed, you can type the following commands in your terminal (Terminal for macOS or Command Prompt for Windows) to check both software versions on your computer.

node -v

npm -v

You should see similar responses on your screen, like the screenshot below. There might be some differences between your version and mine, but you’ll be fine if the npm version is at least seven and Node.js is at least 16.

For Windows users, if you see an error message of “‘node is not recognized as an internal or external command,” you need to modify your Environment Variables. You can search “Environment Variables” on your PC and add the location where you installed Node.js in the PATH. My installed location is at “C:\Program Files\nodejs\”.

Then you need to install Git on your computer. You can visit this site to see the install guide for each OS. For those who want to learn more about Git, you can watch this 100 second video to know more about it. Once installed, type the following command in your terminal to verify it’s working:

git --version

Again, for Windows users, if you run into an error that starts with “git is not recognized as an internal or external command…”, you need to edit your Environment Variables as we previously did for Node.js.

Now, we will clone the perp-curie-arbitrageur repo and build it locally. You can do so with the following commands in your terminal:

git clone https://github.com/perpetual-protocol/perp-curie-arbitrageur.git

cd perp-curie-arbitrageur

npm install

npm run build

If everything goes well, you should be able to see responses like the ones below:

The last thing in this section is that you need to download a cryptocurrency wallet. We recommend MetaMask as it’s the world’s most popular browser wallet. During onboarding, you’ll be asked to save 12 recovery phrases. You should never share these with anyone under any circumstances, especially those who claim to be part of a customer service team.

Get the Tokens you Need

There are two tokens we need in order to run perp-curie-arbitrageur. They are ETH and USDC. Please be aware that, since there is no test account on FTX, we’ll be using real ETH and USDC in the following. It’s better to start with a small amount to get comfortable with it and then increase from there.

  • For ETH:

    If you only use CEXes like Binance or FTX, you can use LayerSwap to transfer some of your ETH to Optimism. If you have ETH on chains like Ethereum or BNB Chain, you can use TransferTo.xyz to bridge your ETH to Optimism. ETH is used to pay the gas fees for your transactions and each transaction on Perp v2 costs around 0.001 ETH, so even 0.1 ETH can be used for a long time.

  • For USDC:

    Similar to ETH, you can use either LayerSwap or TransferTo depending on how much you want to transfer and from where. And as mentioned above, USDC is used as the collateral for your positions.

Also, because by default, MetaMask doesn’t include Optimism in the network list, you need to go to Chainlist to add Optimism to your MetaMask to see your ETH and USDC balance in your wallet.

Configure the Bot: Local Variables and Strategy

At this point, we’re just a few adjustments away from running the bot locally.

Rename the .env.example file to .env and modify it

You need to rename the .env.example file in the root folder of perp-curie-arbitrageur to .env and add a web3 endpoint, your wallet’s private key, and everything related to FTX to it. Here is what your .env file looks like once it’s done:

For a web3 endpoint for Optimism, you can obtain it by creating a free account on Infura or Alchemy. If you wonder what a web3 endpoint is, it’s where this bot submits your transaction. The endpoint provider, e.g. Infura, will broadcast your transaction to blockchain miners/validators upon reception, who will later validate your transaction and add it to the blockchain's latest block.

As for the private key, you can export it from your MetaMask by clicking the more button (besides your wallet address), clicking “Account details,” then “Export Private Key.”  Similar to recovery phrases, you should never share your private key. It’s recommended that you use a new MetaMask account rather than the one that you’ve been using for trades.

As for FTX’s API key and secret, you can generate them by going to the API page of your subaccount and clicking "Create API Key”. The permission should be “Trading” only.

Modify config.json file

Next up, we need to modify the parameters in the config.json file, which sits in the configs subfolder of the src folder, to create our strategy.

Here are the parameters that you need to determine and the respective description in the config file:

  • PRICE_CHECK_INTERVAL_SEC: The frequency to check the price in seconds.

  • BALANCE_CHECK_INTERVAL_SEC: The frequency to check your balance on FTX and your address.

  • ARBITRAGE_MAX_GAS_FEE_ETH:

  • BALANCE_MAX_GAS_FEE_ETH: The maximum amount of gas fees in ETH that you’re willing to pay to do arbitrage. One thing worth pointing out is that , Optimism uses the first-comes, first-served approach to process transactions, meaning that increasing the ARBITRAGE_MAX_GAS_FEE_ETH will not confirm any faster.

  • PERP_MIN_MARGIN_RATIO:

  • FTX_MIN_MARGIN_RATIO: As we mentioned above, the margin ratio is the metric to show how many leverages you use. The lower this metric, the easier for your position to get liquidated.  If you set them as 0.2, then the max leverage is 5x. Recommended to start from 1 to be safe.

  • PERP_EMERGENCY_MARGIN_RATIO:

  • FTX_EMERGENCY_MARGIN_RATIO: The margin ratio threshold when the positions on both platforms will start to be reduced. For instance, if you set them as 0.1 here, that means your positions will begin to be closed when your leverage reaches 10x. Recommended to begin with a number that is closer to 1 to start with.

  • EMERGENCY_REDUCE_AMOUNT: 9000,
    The USD value of the position that the bot should start to close when the emergency margin ratio is reached.

  • EMERGENCY_REDUCE_SLEEP_SEC: The interval between each emergency reduction should be.

  • EMERGENCY_REDUCE_CHECK_INTERVAL_SEC: The frequency that emergency checks should be conducted.

  • IS_ENABLED: Set to true to enable this market.

  • FTX_MARKET_NAME: The name of the market on FTX. Usually, if it’s a perpetual market, then it’ll follow a naming convention of ticker-perp. For instance, BTC’s perpetual market is known as BTC-PERP on FTX.

  • ORDER_AMOUNT: Order amount in USDC for each trade. Remember to top up your account before running the bot.

  • SHORT_TRIGGER_SPREAD:

  • LONG_TRIGGER_SPREAD: The price difference threshold between both platforms at which the bot should start executing your strategy.

  • IS_EMERGENCY_REDUCE_MODE_ENABLED:
    Whether (or not) the bot should reduce positions when the leverage is too high.

We use vBTC (BTC market) and vPERP (PERP market) as the target markets in the config file by default. However, the bot can support up to 5 markets simultaneously. You can check the list of markets on Perp v2 from the UI or this JSON file.

Run Locally

There is one extra step for Windows users - you need to add additional two lines below above the initLog() in the index.ts file otherwise it can’t read the parameters in your .env file.

import dotenv from "dotenv";

dotenv.config();

If there is any error saying dotenv isn’t installed, you can run the command below in your terminal to install dotenv.

npm install dotenv --save

Now, we’re all set! For macOS users, type the command below to run the bot locally:

env $(cat .env | grep -v '#' | xargs) npm run start

For Windows users, type the command below in your terminal:

npm start

If it runs successfully on your machine, you should be able to see similar responses on your terminal:

Run on AWS Lambda

If you’re not familiar with AWS Lambda, you can watch this video to learn more about it (or serverless in general) in 100 seconds. But in general, the main selling point of AWS’ Lambda is that, instead of renting a dedicated server on AWS to run your program 24/7. You only pay the times when your application runs on a shared server, which is more suitable for our use case as the bot only runs from time to time based on your settings.

As a starter for this section, you need to register an account on AWS and install AWS CLI on your machine. Check the installation instructions for each OS here.

Once AWS CLI is installed, you need to configure your AWS profile by running the following command in your Terminal (macOS) or Command Prompt (Windows):

aws configure

Then you need to type your access key and secret. You can create them from the Identity and Access Management page.

Depending on your settings, sometimes you need to create a new user on AWS to generate a key. To do so, you need to click Users on the Identity and Access Management page and then create a new user with permission to manage Lambda.

Following this, you need to type the AWS region you use in the .env file in your perp-curie-arbitrageur folder. For instance, add AWS_REGION=ap-southest-1 to the file if you choose a server located in Singapore.

Also, for Windows users who have run the bot locally in the previous sections, you need to remove the two lines that you added in the index.ts file.

import dotenv from "dotenv";

dotenv.config();

By now we’re all set! Enter the following commands in your terminal to deploy the bot to AWS:

npm run build

npm run sls:deploy

You should be able to see the following responses if everything goes well:

Once your bot is running, you can see the real-time logs by going to the perp-arbitrageur-production-main Lambda function on AWS and clicking the “View logs in CloudWatch” under the Monitor tab. You should be able to see similar logs when running the bot on your computer.

Congratulations! Your bot is now automatically arbitraging the price difference between Perp v2 and FTX!

Further Modification Suggestions

As mentioned at the beginning of this article, this bot is just a template for arbitraging between Perp v2 and FTX. Given the nature of an open-sourced software, anyone can add functionalities to this bot. Below are some directions that you can explore:

  • Support more DEXes and CEXes

    You can modify the bot to support for CEXes like Binance or Huobi to discover more arbitraging opportunities. It also applies to derivative DEXs as there are numerous of them on the market.

  • Better position wind down process

    Currently, the bot will close positions from both exchanges when the margin ratio reaches the limit you set. A better approach to wind down positions should be closing both sides when the prices on both exchanges are the same and do it gradually to reduce price impact aka slippage per trade.

  • Error or success report

    Right now the bot only does its job quietly and you can only check CloudWatch to know its status. One way to improve this is to add a script to send out a Telegram or Discord message when certain criteria are met. For instance, you can write a script to send out Telegram messages when a trade is successful.

That’s the end of our tutorial on how to run perp-curie-arbitrageur!

Besides this tutorial, recently we also have released tutorials on how to run perp-maker! Feel free to check them out.

One last thing - we have a #coding-chat channel on our Discord for questions you encounter when building on top of Perp v2. Feel free to join and say hi.

Helpful Resources

Translations of this article are available in Hindi (हिंदी), Mandarin (普通话) and Swahili, thanks to the help of our Perpvangelists!

Subscribe to Perpetual Protocol 🥨
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.