Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 93 additions & 79 deletions docs/cow-protocol/tutorials/cow-swap/twap.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,120 +6,134 @@ import Image from '@theme/IdealImage';
import TokenApprovalWarning from '../../../partials/_token_approvals.mdx'

# TWAP orders

Time-Weighted Average Price (TWAP) orders are an advanced feature of CoW Protocol, ideal for executing large trades with minimal price impact by distributing the order over a specified time.

Time-Weighted Average Price (TWAP) orders are an advanced feature of CoW Protocol. Instead of executing a trade all at once, a TWAP splits it into smaller parts and executes them at regular intervals over a time period you choose. TWAP orders work with both **EOA wallets** (like MetaMask or Rabby) and **Safe wallets**.
## Introduction

TWAP orders allow you to split a large trade into smaller parts, executed at regular intervals.
This helps in minimizing market impact and in doing so likely achieves a better average price.


A TWAP order takes one trade and turns it into a series of smaller ones, placed at even intervals. Because each part is only a slice of the total, it has less impact on the market price, and the market gets time to recover between parts. Averaging across several points in time can also smooth out the price you get.

People use TWAPs in a few different ways:

- **Breaking up a trade** to reduce price impact, especially in pools with limited liquidity.
- **Getting an average price over time** instead of committing to a single moment.
- **Scheduling buys or sells at regular intervals**, like a recurring purchase.
### Benefits

- **Reduce price impact on large orders**: For example, buying `$1M` of ETH over 3 hours in 6 parts; the TWAP will place an order of `$166k` every `30min`, significantly reducing the price impact and allowing the market to recover.
- **Average buy price over time**: This strategy reduces the risk of buying at a high price by averaging the prices over a selected period.
- **Ideal for recurring or big trades**: The minimum required order size is `$1k` on Mainnet or `$5` on Gnosis Chain, Arbitrum One and Base.

- **Reduce price impact**: Every trade moves the price a little, and in shallow pools that effect adds up quickly. For example, buying `$1M` of ETH over 3 hours in 6 parts means the TWAP places an order of about `$166k` every `30min`, so the market can recover between parts. The same logic applies at any scale: splitting a `$2k` trade in a thin pool into a few parts can help too.
- **Average price over time**: Spreading a trade across a selected period means your execution isn't tied to a single price point.
- **Set it and (mostly) forget it**: Sign once, and CoW Protocol places each part for you at the interval you chose.
- **Minimum order size**: `$1k` on Mainnet, or `$1` on Gnosis Chain, Arbitrum One and Base.
## Placing a TWAP Order

### Connect your Safe wallet

_CoW Swap_ TWAP requires a [Safe](https://safe.global) wallet.

* 🆕 If you don't have one, you can [create a Safe](https://app.safe.global/welcome) wallet
* 🔌 With your Safe wallet, open [CoW Swap (Safe App)](https://app.safe.global/share/safe-app?appUrl=https%3A%2F%2Fswap.cow.fi&chain=eth)

Once CoW Swap is loaded and connected to your Safe you can access TWAP orders via the "TWAP" tab near the center module or the drop-down menu next to the CoW Swap logo.

### Connect your wallet
TWAP orders on _CoW Swap_ work with two kinds of wallet:
* 🦊 **EOA wallets** (MetaMask, Rabby, and friends): connect as usual, no special setup required.
* 🔐 **Safe wallets**: open [CoW Swap (Safe App)](https://app.safe.global/share/safe-app?appUrl=https%3A%2F%2Fswap.cow.fi&chain=eth) from your Safe. Don't have one yet? You can [create a Safe](https://app.safe.global/welcome).
Once CoW Swap is loaded and connected, you can access TWAP orders via the "TWAP" tab near the center module or the drop-down menu next to the CoW Swap logo.
{/* TODO: replace with a screenshot showing the TWAP tab with an EOA wallet connected */}
<Image img={require('/img/cowswap/TWAP_connect.png')} alt="Access TWAP Interface" />

### Select tokens

Choose the token you wish to sell (e.g., `WETH`) and enter the total amount you wish to sell.

<Image img={require('/img/cowswap/TWAP_selectToken.png')} alt="Select Tokens" />


:::note Funds are needed upfront
The full amount you want to sell needs to be in your wallet when you place the order. A TWAP is a single order that executes in parts, so make sure the total is available before you start.
:::

### Specify parameters

This is a _critical_ step where you'll define how your order will be executed over time. Here's how to fine-tune your TWAP order settings:

<Image img={require('/img/cowswap/TWAP_params.png')} alt="Order parameters" style={{ maxWidth: '470px' }} />

1. **Price Protection**: This is a measure to prevent your order from being executed at a price that's too far from the market price when the order was placed. Set the percentage of price protection to define the acceptable price range for your trades. For instance, a 10% price protection means that your order will not execute if the price moves unfavorably by more than 10% from the price at the time the order was made.

2. **Number of Parts**: Decide how many discrete parts you want to divide your order into. This choice will determine the granularity of your TWAP strategy. For example, if you choose to split your order into 2 parts and you are selling a total of 2 WETH, each part will involve selling 1 WETH. The parts have a minimum size of `$5k` on Mainnet or `$5` on Gnosis Chain because each part will need to be executed on-chain, meaning there's a cost associated with each execution.

2. **Number of Parts**: Decide how many discrete parts you want to divide your order into. This choice will determine the granularity of your TWAP strategy. For example, if you choose to split your order into 2 parts and you are selling a total of 2 WETH, each part will involve selling 1 WETH. {/* TODO: confirm per-part minimums with the technical team. Current docs say $5k on Mainnet / $5 on Gnosis Chain, which doesn't line up with the $1k / $1 order minimums above. */}Each part is executed on-chain, meaning there's a cost associated with each execution, so very small parts may not be worthwhile.
3. **Total Duration**: Choose the total time frame over which your order should be executed. The TWAP strategy will distribute your trades evenly across this duration. Select from predefined durations like 1 hour, or set a custom duration based on your trading strategy.

4. **Part Duration** _(read-only)_: View the duration of each individual part of your order. It is calculated automatically as the total duration divided by the number of parts. For instance, if your total duration is 1 hour and you have 2 parts, each part will have a duration of 30 minutes.

5. **Sell per Part** _(read-only)_: After setting the number of parts and the total duration, the interface will display the sell amount for each part. Ensure this aligns with your trade expectations.

6. **Buy per Part** _(read-only)_: Similarly, for a buy TWAP order, this will indicate how much of the token you are looking to purchase in each part of the order.

Carefully review and adjust your order parameters to align with market conditions, anticipated movements, and your trading objectives, as they are crucial in dictating the execution and efficacy of your TWAP strategy. Once you have tailored these details to your satisfaction, you can move on to the next step to finalize and place your order.

### Unsupported wallet? Upgrade Safe Fallback Handler

If your wallet is _unsupported_, upgrade to a Safe with the special fallback handler required for TWAP orders. [Learn all about the new Safe fallback handler](https://blog.cow.fi/all-you-need-to-know-about-cow-swaps-new-safe-fallback-handler-8ef0439925d1) and its relevance to Safe in this [overview](https://help.safe.global/en/articles/40838-what-is-a-fallback-handler-and-how-does-it-relate-to-safe). Naturally, the upgrade process has undergone [extensive auditing](https://github.com/cowprotocol/composable-cow/tree/ab3addad9bc05acdbf5fb040eb5c336209b58e31/audits) for increased peace of mind.


### Safe wallet only: upgrade the Safe Fallback Handler

_This step only applies to Safe wallets. If you're using an EOA wallet, skip ahead to "Review and confirm"._

If your Safe is _unsupported_, upgrade it to a Safe with the special fallback handler required for TWAP orders. [Learn all about the new Safe fallback handler](https://blog.cow.fi/all-you-need-to-know-about-cow-swaps-new-safe-fallback-handler-8ef0439925d1) and its relevance to Safe in this [overview](https://help.safe.global/en/articles/40838-what-is-a-fallback-handler-and-how-does-it-relate-to-safe). Naturally, the upgrade process has undergone [extensive auditing](https://github.com/cowprotocol/composable-cow/tree/ab3addad9bc05acdbf5fb040eb5c336209b58e31/audits) for increased peace of mind.

<Image img={require('/img/cowswap/TWAP_unsupported.png')} alt="Unsupported wallet" style={{ maxWidth: '440px' }} />

### Review and confirm

Check all the details of your order, including price protection and limit price. Once you have reviewed the details, sign the transaction in your Safe interface.


Check all the details of your order, including price protection and limit price. Once you're happy, confirm in your wallet.

**With an EOA wallet**, you sign a single transaction to create the TWAP order. Depending on the token and your existing allowances, you may also need one of the following before that:

* a **permit signature** (for tokens that support permits), or
* an **on-chain approval transaction** (for tokens that don't, or where your current allowance isn't enough).
Your wallet will prompt you for whichever applies, so there's nothing to configure.

**With a Safe wallet**, sign the transaction in your Safe interface.

{/* TODO: add an EOA review/confirm screenshot */}
<TokenApprovalWarning spender="TWAPContract" />

Be careful when signing an order. All of the associated parameters are final and cannot be changed once the order is signed and submitted to the API. If you make a mistake, you will need to cancel the order and create a new one. You can do this in the orders overview.

Be careful when signing an order. All of the associated parameters are final and cannot be changed once the order is signed and submitted. If you make a mistake, you will need to cancel the order and create a new one. You can do this in the orders overview.
<Image img={require('/img/cowswap/TWAP_review.png')} alt="Review order" style={{ maxWidth: '470px' }} />

### Finalization and monitoring

Once you've signed the order, the process of finalizing and monitoring your TWAP order begins. This is a multi-step process that ensures your order is securely processed and activated.

Once you've signed the order, the process of finalizing and monitoring your TWAP order begins.
<Image img={require('/img/cowswap/TWAP_orderSubmitted.png')} alt="Order submitted successfully" style={{ maxWidth: '470px' }} />

The "Order submitted successfully" screen indicates that your order has been initially accepted.
<br />


**Safe wallets only:** if your Safe has multiple owners, you'll see an "Order in signing state" screen while the remaining signatures are collected. Ensure all necessary parties sign to proceed.

<Image img={require('/img/cowswap/TWAP_orderSigning.png')} alt="Order in signing state" />

The "Order in signing state" screen shows that your order may require additional signatures from your Safe. Ensure all necessary parties sign to proceed.
Once the transaction is confirmed on-chain (for a Safe, after all signatures are collected), your order becomes 'active'. The "Orders overview" allows you to monitor its current status and see the full list of active orders.
<br />

After all signatures are collected and the transaction is submitted on-chain, your order becomes 'active'. The "Orders overview" allows you to monitor its current status and see the full list of active orders.
<br />


<Image img={require('/img/cowswap/TWAP_ordersOverview.png')} alt="Orders overview" />
Each TWAP can be expanded to show the individual parts.

<Image img={require('/img/cowswap/TWAP_orderMenu.png')} alt="Order menu" />
The three-dot menu for the parent TWAP shows the actions available that affects all parts of a TWAP.

<Image img={require('/img/cowswap/TWAP_partMenu.png')} alt="Order part menu" style={{ maxWidth: '470px' }} />
Each individual TWAP part also have a three-dot menu with actions pertaining to that individual order.

<Image img={require('/img/cowswap/TWAP_orderReceipt.png')} alt="Order receipt" style={{ maxWidth: '470px' }}/>
Finally, the "Order receipt" provides a detailed confirmation of your active TWAP order, complete with execution details and transaction details.

## Cancelling a TWAP order

Canceling a TWAP order involves a few simple steps. Begin by locating your active TWAP order in the "Your Orders" section to manage it.

Cancelling a TWAP order takes a few simple steps. Begin by locating your active TWAP order in the "Your Orders" section.
<Image img={require('/img/cowswap/TWAP_orderMenu.png')} alt="Order menu" />

Here in the order overview, find the order you intend to cancel. Click the three-dot menu icon at the end of the order's row to open up additional actions. Select "Cancel order" from the dropdown menu to initiate the cancellation process.

Find the order you intend to cancel and click the three-dot menu icon at the end of the order's row. Select "Cancel order" from the dropdown menu to start the cancellation process.
<Image img={require('/img/cowswap/TWAP_cancelOrder.png')} alt="Cancel order" style={{ maxWidth: '470px' }} />

A confirmation window will appear, summarizing the order you are about to cancel, including the swap details and the transaction type. This is your opportunity to review and ensure that you are canceling the correct order.

When you confirm the cancellation by clicking "Request cancellation," a new transaction will be created in your Safe. This transaction is not final until all required parties (Safe owners) provide their signature.

Once all signatures are collected, the transaction to cancel the order will be executed. It's vital to coordinate with all signers to complete this promptly, especially if the order needs to be canceled quickly due to changing market conditions or other strategic considerations. After the cancellation transaction is fully signed and submitted, the order will be removed from your active orders list and considered canceled.


A confirmation window will appear, summarizing the order you are about to cancel, including the swap details and the transaction type. This is your chance to double-check that you're cancelling the right order.

When you confirm by clicking "Request cancellation", a cancellation transaction is created.

* **EOA wallets**: confirm the transaction in your wallet. Cancellation happens on-chain, so it costs gas.
* **Safe wallets**: the transaction appears in your Safe and isn't final until all required owners have signed. Cancellation is also on-chain and costs gas. It's worth coordinating with your co-signers promptly, especially if you need to cancel quickly because market conditions have changed.
Once the cancellation transaction is confirmed, the order is removed from your active orders list and considered cancelled.

## Conclusion

TWAP orders are a strategic approach for large trades, reducing price impact and securing better average prices. Try it out and let us know your experience at [info@cow.fi](mailto:info@cow.fi)!
TWAP orders spread a trade across time, which can reduce price impact and give you a smoother average price, whatever wallet you use. Try it out and let us know your experience at [info@cow.fi](mailto:info@cow.fi)!
Loading