# Run DCA bot

<figure><img src="https://1420663172-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fb0DdMLXZFpK1vsL3ZKiG%2Fuploads%2FVJi8TEvWmot5DXoANwAn%2FScreen%20Shot%202022-10-12%20at%2017.02.47.png?alt=media&#x26;token=265e7aee-b776-422b-9b36-876885a520be" alt=""><figcaption></figcaption></figure>

This is a sample Pine Script and a corresponding alert message to run a DCA(Dollar-Cost Averaging) bot with the following conditions as an example.

* Execute BTC-USD Long order daily with 200 USD when close price < 20,000 until total position size is less than 1 BTC
* Execute close(short) order when daily close price > 24,000

All of the above values are parameterized and you can customize them.&#x20;

<figure><img src="https://1420663172-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fb0DdMLXZFpK1vsL3ZKiG%2Fuploads%2Fp29WEvN5SovdYNR1LSGO%2FScreen%20Shot%202022-10-12%20at%2017.41.51.png?alt=media&#x26;token=656e1ca2-d97a-42b1-8daf-056db04cc67b" alt=""><figcaption></figcaption></figure>

### Setup

1. Select market you want to run DCA bot and set arbitrary time-interval(the above example is 1D)

&#x20; 2\.  Open "Pine Editor" tab and paste the following script after deleting shown original script. Then click "Add to chart"

{% code title="Pine Script" overflow="wrap" lineNumbers="true" %}

```
//@version=5
strategy("DCA bot", pyramiding = 999, default_qty_type=strategy.percent_of_equity, default_qty_value=1)

// Execute long order when close price is under this price
thresholdPrice = input(20000, "Entry Threshold Price")
ExitPrice = input(24000, "Exit Price")
orderSize = input(200, "Order Amount in USD")
maxPosition = input.float(1.00, "Max Position Size", 0.01, 100.00, 0.01)
startDate = timestamp(2022, 01, 01, 0, 0)

if startDate <= time
    if close < thresholdPrice and strategy.position_size < maxPosition
        strategy.entry("Long", strategy.long, (orderSize / close))

    else if close > ExitPrice and strategy.position_size > 0
        strategy.close_all("Close Position")
```

{% endcode %}

In the above script, We assume

* No remaining positions/orders in the target market running this bot.
* Enough amount of collateral is already in place to avoid liquidation.

3\. Click Alert button and paste the following code into message field.

{% code title="Alert message body" %}

```json
{
	"exchange": "perpetual", // or replace with "dydx"
	"strategy":"DCABot",
	"market":"BTC_USD",
	"size":"{{strategy.order.contracts}}",
	"reverse":false,
	"order":"{{strategy.order.action}}",
	"position":"{{strategy.market_position}}",
	"price":"{{strategy.order.price}}"
}
```

{% endcode %}
