# TWAP

TWAP, or time-weighted average price, is a way to achieve dollar cost averaging (DCA) to enter or exit a position. It is a more complicated algo but Dexible makes it simple to configure through the sdk algo factory. Let's start with an example:

{% tabs %}
{% tab title="JavaScript" %}
```javascript
let algo = sdk.algo.create({
   type: sdk.algo.types.TWAP,
   timeWindow: {
      hours: 24
   },
   gasPolicy: {
        type: sdk.gasPolicyTypes.RELATIVE,
        deviation: 0
   },
   slippagePercent: .5
});
```
{% endtab %}

{% tab title="Python" %}
```python
algo = sdk.algo.create(
   type=sdk.algo.types.TWAP,
   ## You can also use datetime.timedelta as time_window
   time_window={"hours": 24},
   gas_policy={
        "type": sdk.GasPolicyTypes.RELATIVE,
        "deviation": 0
   },
   slippage_percent=.5)
```
{% endtab %}
{% endtabs %}

Note the use of "timeWindow". This tells Dexible execute the order across a 24-hour time period. Dexible will compute the optimum number of rounds based on current market conditions and insert an evaluation delay based on timeWindow/numberOfRounds.&#x20;

The timeWindow is used to determine how often to evaluate the market for execution of each round. A 24-hour time period, with say 5 rounds, means it will look at the market every 4.8 hours and attempt to execute. There is another flag you can add to the order: randomizeDelay: true. If the randomizeDelay parameter is true,  Dexible will randomize the delay between evaluations but will execute the full order within the time window.&#x20;

After the time window is up, regardless of how much of the TWAP order has been executed, it will cancel the order due to expiration.

### maxRounds Warning

In the StopLoss example earlier, maxRounds was used to tell Dexible to force the execution in a single round, regardless of consequences. In that use case, it might make sense to ignore market impact. maxRounds can also be used in TWAP algos; however, you will want to be careful with how you use it because it may expose your order to excessive market impact. For example, if you were trading 100 ETH and forced it to limit each round to 10 ETH (i.e. maxRounds = 10), 10 ETH may be a significant amount to trade in a single round depending on the token you're buying. It could result in higher losses compared to Dexible's recommended number of rounds. Our optimized recommendation will always choose the maximum net output after reducing costs.

### Price Range

TWAP can also have a bounded price range. This limits market impact exposure as it executes within the time window. The range takes a "base" price and then an upper and lower bound percentage. Here is an example TWAP with a price range:

{% tabs %}
{% tab title="JavaScript" %}
```javascript
let algo = sdk.algo.create({
   type: sdk.algo.types.TWAP,
   timeWindow: {
      hours: 24
   },
    priceRange: {
        basePrice: Price.unitsToPrice({
            inToken: tokenIn,
            outToken: tokenOut,
            inUnits: 1, //1 WETH
            outUnits: 2056 //for this amount of MATIC
        }),
        lowerBoundPercent: 2,
        upperBoundPercent: 2
    },
    gasPolicy: {
        type: sdk.gasPolicyTypes.RELATIVE,
        deviation: 0
    },
    slippagePercent: .5
});
```
{% endtab %}

{% tab title="Python" %}
```python
from datetime import timedelta
algo = sdk.algo.create(
    type="TWAP",
    time_window=timedelta(hours=24),
    price_range={
        "base_price": dexible.Price.units_to_price(
            in_token=token_in,
            out_token=token_out,
            in_units=1,  # 1 WETH
            out_units=2056),  # for this amount of MATIC
        "lower_bound_percent": 2,
        "upper_bound_percent": 2},
    gas_policy={
        "type": sdk.GasPolicyTypes.RELATIVE,
        "deviation": 0
    },
    slippage_percent=.5)
print(algo)
# <Algo TWAP policies: 
#  [<Policy GasCost gas_type: relative, amount: None, deviation 0>,
#   <Policy Slippage amount: 0.5>, 
#   <Policy BoundedDelay time_window_seconds: 86400, randomize_delay: False>,
#   <Policy PriceBounds upper_bound_percent: 2, lower_bound_percent: 2>]>

```
{% endtab %}
{% endtabs %}

This is similar to a normal TWAP except we've added a price range. This tells Dexible to execute across 24 hours and only execute a round if the price is within +/- 2% of the base price. Regardless of how many rounds are executed in 24 hours, the order will expire.
