# Integrate ATM

{% hint style="info" %}
The ATM Library is a powerful AI agent for trading. This guide provides a step-by-step process to integrate and utilize the library in your project.
{% endhint %}

**Getting Started**

Installation

To use the ATM library, install it using your preferred package manager:

```bash
npm install atmai
# or
yarn add atmai
```

**Setup**

**API Configuration**

To initialize the library, you need your API key, secret, and API URL. Obtain these from your ATM account.

**1. API Key and Secret:**

• Login to your ATM account.

• Navigate to the API section to generate or retrieve your credentials.

**2. Whitelisted API URL:**

• Use the provided URL for your whitelisted environment.

**Initialization**

Create a new file (e.g., atmConfig.ts) and configure the library:

```typescript
import { ATM } from 'atmai';

// Replace these placeholders with your actual credentials
const API_KEY = '{your-api-key-here}';
const API_SECRET = '{your-api-secret-here}';
const API_URL = 'https://api.atmai.fun';

export const atm = new ATM({
  apiKey: API_KEY,
  apiSecret: API_SECRET,
  apiUrl: API_URL,
});
```

**Usage**

**1. Fetch Portfolio Summary**

Retrieve a portfolio summary for the last 24 hours:

```typescript
import { atm } from './atmConfig';

async function getPortfolioSummary(): Promise<void> {
  try {
    const summary = await atm.getPortfolioSummary({ timeframe: '24h' });
    console.log('24-hour Portfolio Summary:', summary);
  } catch (error) {
    console.error('Error fetching portfolio summary:', error);
  }
}

// Example Usage
getPortfolioSummary();
```

**2. Trend Following Strategy**

Uses AI-assisted trading decisions based:

```typescript
import { atm } from './atmConfig';

// Trend Following Configuration
const config = {
  network: 'Solana', // Blockchain network
  token: '', // Replace with your token of choice
  tradeAmount: 10000, // Amount of tokens to trade per order
  pollingInterval: 5000, // Check price every 50 seconds
  mevProtection: true, // Enable MEV protection
};

// Function to buy tokens with MEV protection
async function buyTokens(token: string, amount: number): Promise<void> {
  try {
    const response = await atm.buy({
      token,
      amount,
      mevProtection: config.mevProtection,
    });
    console.log(`Successfully purchased ${amount} of ${token} with MEV protection:`, response);
  } catch (error) {
    console.error('Error purchasing tokens:', error);
  }
}

// Function to sell tokens with MEV protection
async function sellTokens(token: string, amount: number): Promise<void> {
  try {
    const response = await atm.sell({
      token,
      amount,
      mevProtection: config.mevProtection,
    });
    console.log(`Successfully sold ${amount} of ${token} with MEV protection:`, response);
  } catch (error) {
    console.error('Error selling tokens:', error);
  }
}

// Function to execute trend-following trades
async function trendFollowingStrategy(): Promise<void> {
  try {
    if (lastPrice === 0) {
      // Set initial price
      lastPrice = currentPrice;
      console.log('Initialized last price:', lastPrice);
      return;
    }
    // Prepare prompt for AI agent
    const prompt = {
      network: config.network,
      token: config.token,
      strategy: 'follow_trend_atm_v1.0a',
      tradeAmount: config.tradeAmount,
      mevProtection: config.mevProtection,
    };

    console.log('Sending prompt to AI agent for trend analysis:', prompt);

    // Use AI agent to decide action
    const aiResponse = await atm.executeStrategy(prompt);

    if (aiResponse.action === 'BUY') {
      console.log('ATM identified an upward trend. Buying tokens...');
      await buyTokens(config.token, config.tradeAmount,config.network);
      lastPrice = currentPrice; // Update the last price after buying
    } else if (aiResponse.action === 'SELL') {
      console.log('ATM identified a downward trend. Selling tokens...');
      await sellTokens(config.token, config.tradeAmount,config.network);
      lastPrice = currentPrice; // Update the last price after selling
    } else {
      console.log('ATM recommended holding. No trade executed.');
    }
  } catch (error) {
    console.error('Error in trend-following strategy:', error);
  }
}

// Main function to execute the strategy
async function main(): Promise<void> {
  console.log('Starting Trend Following Strategy on Solana...');
  setInterval(async () => {
    console.log('Executing trend-following strategy...');
    await trendFollowingStrategy();
  }, config.pollingInterval); // Run strategy at regular intervals
}

// Run the script
main().catch((error) => {
  console.error('Error in main function:', error);
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://atm-5.gitbook.io/atmaiagent/features/integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
