> ## Documentation Index
> Fetch the complete documentation index at: https://docs.glider.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# Portfolio Automation

> A guide to automated portfolio rebalancing

This guide explains how to set up, manage, and customize automated portfolio rebalancing with the Glider API.

## Overview

Glider's portfolio automation enables your portfolio to maintain its target allocations through automatic rebalancing. This keeps your portfolio aligned with your investment strategy without requiring manual intervention.

The automation lifecycle includes:

1. Starting automation
2. Monitoring rebalance status
3. Pausing/resuming as needed
4. Triggering manual rebalances
5. Customizing rebalance schedules

## Setting Up Automation

### 1. Start Portfolio Automation

To start automation for a portfolio:

```javascript theme={null}
const startResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/start`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-KEY': 'your_api_key_here',
  },
  body: JSON.stringify({
    runRebalanceImmediately: true, // Run a rebalance right away
    interval: {
      every: 86400000, // 24 hours in milliseconds
    }
  }),
});

const startData = await startResponse.json();
```

The `interval` parameter specifies how often the portfolio should be checked for rebalancing:

* `every`: Time between checks in milliseconds
* `offset`: Optional offset in milliseconds from the start time

Common intervals:

* Daily: 86400000 ms
* Weekly: 604800000 ms
* Hourly: 3600000 ms

### 2. Check Automation Status

To check if automation is active and retrieve its current status:

```javascript theme={null}
const statusResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/automation/status`, {
  method: 'GET',
  headers: {
    'X-API-KEY': 'your_api_key_here',
  },
});

const statusData = await statusResponse.json();
console.log("Automation status:", statusData.data.status);
```

The response includes details about:

* Current status (active, paused, etc.)
* Next scheduled rebalance time
* Last rebalance result
* Schedule configuration

## Managing Automation

### Pausing Automation

To temporarily pause automation:

```javascript theme={null}
const pauseResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/pause`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-KEY': 'your_api_key_here',
  },
  body: JSON.stringify({
    reason: "User requested pause" // Optional reason
  }),
});

const pauseData = await pauseResponse.json();
```

### Resuming Automation

To resume previously paused automation:

```javascript theme={null}
const resumeResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/resume`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-KEY': 'your_api_key_here',
  },
  body: JSON.stringify({
    reason: "User requested resume" // Optional reason
  }),
});

const resumeData = await resumeResponse.json();
```

### Triggering Manual Rebalance

For v2 B2B integrations, trigger a one-off rebalance for a portfolio your API key has access to:

```javascript theme={null}
const triggerResponse = await fetch(`https://api.glider.fi/v2/portfolios/${portfolioId}/rebalance`, {
  method: 'POST',
  headers: {
    'x-api-key': 'your_api_key_here',
  },
});

const triggerData = await triggerResponse.json();
const operationId = triggerData.data.operationId;
```

The response is accepted asynchronously. Poll `GET /v2/portfolios/{portfolioId}/operations/{operationId}` until the operation completes (`state`: `completed`, `failed`, or `cancelled`).

For legacy v1 integrations, the equivalent endpoint is:

```javascript theme={null}
const triggerResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/trigger`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-KEY': 'your_api_key_here',
  },
  body: JSON.stringify({
    skipScheduleValidation: true // Allow triggering even if no schedule exists
  }),
});

const triggerData = await triggerResponse.json();
```

### Updating Schedule Interval

To change how frequently the portfolio is rebalanced:

```javascript theme={null}
const updateIntervalResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/update-schedule-interval`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-KEY': 'your_api_key_here',
  },
  body: JSON.stringify({
    interval: {
      every: 43200000, // 12 hours in milliseconds
      offset: 0, // Optional: Offset from the start time in milliseconds
    },
  }),
});

const updateIntervalResult = await updateIntervalResponse.json();
```

## Monitoring Rebalance Activity

### Getting Rebalance Status

To check the status of all rebalance activities:

```javascript theme={null}
const rebalanceStatusResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/rebalance/status?limit=10`, {
  method: 'GET',
  headers: {
    'X-API-KEY': 'your_api_key_here',
  },
});

const rebalanceStatus = await rebalanceStatusResponse.json();
```

### Getting Specific Workflow Status

To get detailed information about a specific rebalance workflow:

```javascript theme={null}
const workflowStatusResponse = await fetch(`https://api.glider.fi/v1/portfolio/${portfolioId}/rebalance/status/${workflowId}`, {
  method: 'GET',
  headers: {
    'X-API-KEY': 'your_api_key_here',
  },
});

const workflowStatus = await workflowStatusResponse.json();
```

## Customizing Rebalance Behavior

The rebalancing behavior is determined by the `tradingSettings` in your portfolio template:

### Threshold-Based Rebalancing

Rebalances when asset allocations drift beyond a specified percentage:

```javascript theme={null}
templateData: {
  // ... other template data
  tradingSettings: {
    type: "threshold",
    triggerPercentage: 5 // Rebalance when assets drift 5% from target
  }
}
```

### Calendar-Based Rebalancing

Rebalances on a fixed schedule regardless of drift:

```javascript theme={null}
templateData: {
  // ... other template data
  tradingSettings: {
    type: "calendar",
    frequency: "weekly" // Options: daily, weekly, biweekly, monthly
  }
}
```

## Best Practices

1. **Start with sufficient funds**: Ensure the portfolio has enough assets to cover gas fees for rebalancing
2. **Select appropriate intervals**: Choose rebalancing frequency based on your portfolio's volatility and size
3. **Monitor gas usage**: Be aware that frequent rebalancing can lead to higher gas costs
4. **Set realistic thresholds**: Too small a threshold may cause excessive rebalancing, while too large may defeat the purpose
5. **Use manual triggers sparingly**: Reserve manual rebalancing for significant market events or portfolio changes

## Next Steps

After setting up automation, consider:

1. [Monitoring portfolio performance](/api-reference/endpoints/portfolio-performance) to track how automated rebalancing affects returns
2. [Updating the portfolio template](/guides/portfolio-updating) to fine-tune your allocation strategy
3. [Depositing additional assets](/guides/portfolio-deposits) to grow your portfolio
