To stay ahead in the cryptocurrency markets, traders are increasingly relying on sophisticated algorithmic trading strategies to enter and exit their positions. One popular automated trading strategy is the Time-Weighted Average Price (TWAP) algorithm.
This article provides a comprehensive guide on setting up a bot for automated TWAP execution on Perp, enabling traders to minimize the market impact of large orders and attain better entry prices.
As an algorithmic trading strategy that aims to achieve an average execution price of an asset over a specified period, TWAP execution allows traders to submit larger orders without significantly affecting the market price. This is achieved by breaking a large order into smaller chunks and executing them at regular time intervals.
The TWAP bot outlined in this article can be used by traders to achieve better execution prices. The benefits of automated TWAP execution are explained in more detail in the following section.
The advantages to using a TWAP bot for executing trades on Perp are:
Reducing slippage: The TWAP execution bot minimizes slippage, reducing the difference between the expected execution price of a trade and the actual execution price.
Minimizing market impact: By distributing large orders over time, the TWAP bot reduces the likelihood of causing sudden price movements that could be detrimental to the trader's position. TWAP execution is especially useful for markets where liquidity is thinner.
Automating trade execution: Traders can automate their trading strategy to scale in, and scale out, of positions without manual intervention.
Optimizing execution prices: TWAP orders allow traders to get the best possible price for their order. If there’s elevated price volatility and the market is near an important support level, using TWAP execution to go long will evenly distribute the buy orders over time. In turns, this helps the trader get a better average entry price as compared to opening a position manually through the UI.
Suitable for various market conditions: The TWAP algorithm can be used in both trending and range-bound markets, making it a versatile trading strategy.
A bot that automates TWAP execution can be used by traders to split orders into smaller ones over a specified period. By following the 5 steps below, traders can programmatically scale in and out of positions over time on Perp.
Clone the GitHub Repository
Download Yarn
Edit the Config.json
File
Create the .env
File
Run the TWAP Execution Bot
The first step is to go to the bot’s GitHub repository:
Find the green “Code” button and then click on “Download ZIP”.
Unzip the folder. The contents of the folder are shown in the screenshot below:
Alternatively, you can use the following command in your Terminal application:
git clone https://github.com/grantweii/perp-algo-executor.git
Open the Terminal application and enter the following commands:
cd perp-algo-executor
Yarn install
The third step is to edit the config.json
file, which can be found by going to perp-funding-arbitrageur > src > config.json. The file can be opened and edited using a text editor.
The screenshot below displays what you’ll see once opening the config.json
file with Visual Studio Code:
You’ll notice that from the screenshot above that two strategies are supported:
spread: a simple arbitrage between a hedge exchange and Perp.
twap: splits an order into multiple child orders and executes them at an interval, thereby achieving an average price over a specified period.
The first 14 lines of code displayed in the file above specifies a spread strategy that runs funding rate arbitrage between Binance and Perp for the AAVE market. While lines 16-33 specifies a TWAP execution strategy to open a long position for the ETH market on Perp.
Spread
For the spread strategy, let’s assume the funding rate is high for SOL. If a trader enters a $100,000 hedged SOL position to capture the funding payments but only wants to enter when the prices are in their favor, they can run the spread strategy.
To do so, the optional hedge parameter must be enabled, which will automatically hedge your position. The code snippet below shows what the config file should look like if you want to run the spread strategy for SOL.
EXECUTION.MIN_SPREAD is the strategy specific parameter for spread. In other words, the minimum difference in basis points required for the execution condition to pass.
A MIN_SPREAD of 5 means the effective short price must be at least 5 basis points greater than the long price in order to pass (favorable arb).
Alternatively, MIN_SPREAD of -5 means the short price must be at most 5 basis points lower than the long price in order to pass (possibly unfavorable arb).
The spread is calculated as follows:
EXECUTION.ORDER_NOTIONAL refers to the size of each child order and SLIPPAGE refers to the maximum slippage tolerance, measured in basis points.
TWAP
Focusing in on the TWAP execution strategy, the EXECUTION.PARTS field shows that the total position will be split into two $100 buy orders. EXECUTION.PERIOD shows the expected time to scale to the TOTAL_NOTIONAL (total notional position) of $200.
Given that 5-minutes are specified for the execution period and there's two child orders, the $200 ETH position will be opened using two orders across 2.5-minute intervals.
The description of the other fields are shown below:
POLL_INTERVAL: the time between iterations (in milliseconds).
HIDE_SIZE: if the field is set to true, the TWAP execution will execute a random size between 0.9 to 1.1 times the child order size.
CLOSE_ONLY: must be specified if closing a position. Effectively, it acts like a reduce only. Set to false when opening a position, or true for closing a position.
Let’s look at another example, assuming a trader wants to enter a $100,000 long position in the DOGE market. The price impact of this is close to 1% if executed with a single order. So a trader is better off slicing the order into multiple parts and TWAP in over time.
If a trader wants to split this $100,000 position into 20 child orders over a 4-hour time period, then they can edit the config file and enter the code below:
After the TWAP order has been fulfilled, a trader can also scale out of their position by doing the following:
Updating the CLOSE_ONLY parameter to ‘true’ in the config.json
file,
Inverting the PERP_DIRECTION parameter (in this example, changing it from long to short),
Running the bot again (see step 5).
Now that the strategy has been specified, the next step is to edit the .env.example
file and create a .env
file in the root directory.
Here’s what the .env.example
file looks like before entering the required information:
To run the TWAP strategy, enter the private key of the wallet you want to use for execution. Once you’ve entered your private key, save the file and rename it as ‘.env’.
The API key and secret for your Binance account are required for running the spread strategy. You can also specify the RPC you want to use. It is recommended to use your own Optimism RPC as the public RPC is rate limited and you may get banned for excessive use.
To provide another example of how the automated TWAP execution works, you can use the code displayed below to long ETH and open a total notional position of $2000, which is split into 20 child orders over a 15-minute period.
Once the config.json
file has been edited, click on ‘File’ then ‘Save’ in Visual Studio Code.
Now we’re all set to start running the automated TWAP execution strategy to scale in or out of positions on Perp, or run a funding rate arbitrage strategy between Binance and Perp.
Go back to the Terminal window, input the following command and press enter:
npm start
The TWAP strategy that was specified in the config.json
file will be automatically executed over time for the wallet associated with the private key entered in the .env
file.
If the bot encounters any errors, you may have input the wrong parameters. Just follow the error message and update your parameters. You may also encounter an error if the root administrator is not enabled. Root administrator can be enabled by entering su [adminUsername]
in Terminal.
The bot outlined above is the first iteration for building a TWAP-based execution strategy, but there are some factors to consider while executing this strategy:
Funding rate The position will earn/pay the funding rate while the order is being executed. The historical funding rate can be queried from The Graph’s API here.
Gas
Maintain enough gas in the wallet to execute the transaction. The tool does not monitor gas in the wallet or support the maximum gas setting.
Margin ratio
Perp allows up to 10x leverage for traders. If your position is using leverage, have a plan in place to manage risk and ensure you have enough margin ratio to avoid liquidation during the TWAP execution. More details about position liquidation can be found here.
Execution not guaranteed
The order might not get executed fully if the slippage tolerance, gas balance or minimum spread parameters are set too low.
Monitor liquidity while executing funding rate arbitrage
For large positions, it might be difficult to exit the position quickly if liquidity is thin or price volatility is too high.
And that’s the end of our tutorial on automating TWAP execution on Perp! If you have any feedback or questions, come and chat to us via the dedicated thread in the #general channel for this tool on Discord. If you want to enhance the TWAP bot, you can fork it or submit a pull request to the GitHub repository.