> For the complete documentation index, see [llms.txt](https://docs.nectarliquid.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nectarliquid.com/builders/ai-agents.md).

# AI Agents & Headless Trading

Nectar Liquid is designed natively for headless programmatic execution by autonomous AI agents, automated rebalancers, algorithmic market makers, and quantitative execution bots.

Agents can operate 24/7 on Asset Chain without browser extensions or manual user interactions.

***

### Headless Architecture Overview

```
+-----------------------------------------------------+
|                 Autonomous AI Agent                 |
|  - Private Key (Kept strictly on agent server)      |
|  - Strategy / Decision Engine (LLM or Quant)        |
+-----------------------------------------------------+
              |                             |
     (1) REST API Interactions     (2) On-Chain Execution
              |                             |
              v                             v
    [ Nectar Liquid API ]        [ Asset Chain RPC ]
    - SIWE Authentication        - Query SyntheticsReader
    - Real-Time Market Stats     - Broadcast Order Transactions
    - Attribution & Keys         - Keeper Execution
```

***

### Headless SIWE Authentication Workflow

Autonomous bots authenticate headlessly by executing an automated challenge-response handshake matching the EIP-4361 SIWE standard:

```typescript
import { ethers } from "ethers";
import axios from "axios";

export interface AgentSession {
  token: string;
  walletAddress: string;
}

/**
 * Programmatically authenticates an autonomous agent using its private key.
 */
export async function authenticateAgent(
  privateKey: string,
  builderId?: string
): Promise<AgentSession> {
  const API_URL = "https://api.nectarliquid.com";
  const domain = "app.nectarliquid.com";
  const chainId = 42420; // Asset Chain Mainnet

  // 1. Initialize agent wallet from private key
  const wallet = new ethers.Wallet(privateKey);
  const walletAddress = await wallet.getAddress();

  // 2. Fetch cryptographic challenge nonce
  const nonceResponse = await axios.post(`${API_URL}/auth/nonce`, {
    address: walletAddress,
  });
  const { nonce } = nonceResponse.data;

  // 3. Format standard EIP-4361 SIWE message
  const issuedAt = new Date().toISOString();
  const message = [
    `${domain} wants you to sign in with your Ethereum account:`,
    walletAddress,
    "",
    "Sign in to Nectar Liquid",
    "",
    `URI: https://${domain}`,
    "Version: 1",
    `Chain ID: ${chainId}`,
    `Nonce: ${nonce}`,
    `Issued At: ${issuedAt}`,
  ].join("\n");

  // 4. Sign message headlessly with private key
  const signature = await wallet.signMessage(message);

  // 5. Verify signature and obtain JWT session token
  const verifyResponse = await axios.post(`${API_URL}/auth/verify`, {
    message,
    signature,
    builderId, // Optional builder attribution
  });

  const { token } = verifyResponse.data;

  return {
    token,
    walletAddress,
  };
}
```

***

### Executing Autonomous Trades via SDK

Once authenticated, your agent can query markets and submit orders directly to the blockchain:

```typescript
import { ethers } from "ethers";
import { createIncreaseOrderTxn } from "@nectarliquid/sdk";
import { authenticateAgent } from "./agentAuth";

async function runAutonomousStrategy() {
  const RPC_URL = "https://mainnet-rpc.assetchain.org";
  const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
  const agentWallet = new ethers.Wallet(process.env.AGENT_PRIVATE_KEY!, provider);

  // 1. Authenticate agent session
  const session = await authenticateAgent(
    process.env.AGENT_PRIVATE_KEY!,
    process.env.BUILDER_ID
  );
  console.log(`Agent authenticated as: ${session.walletAddress}`);

  // 2. Configure order parameters
  const MARKET_WETH_PERP = "0x97D83eE4829D0ca1371144cBdCf3EB44c446460D";
  const USDC_COLLATERAL = "0x2B7C1342Cc64add10B2a79C8f9767d2667DE64B2";

  // Position sizing: $2,500 USD notional with $250 USDC margin (10x leverage)
  const sizeDeltaUsd = ethers.utils.parseUnits("2500", 30);
  const collateralAmount = ethers.utils.parseUnits("250", 6);

  // 3. Construct Order Transaction with builder attribution
  const orderTxn = await createIncreaseOrderTxn({
    account: session.walletAddress,
    marketAddress: MARKET_WETH_PERP,
    initialCollateralTokenAddress: USDC_COLLATERAL,
    sizeDeltaUsd,
    initialCollateralDeltaAmount: collateralAmount,
    isLong: true,
    acceptablePrice: ethers.utils.parseUnits("3600", 30), // Oracle protection boundary
    uiFeeReceiver: process.env.BUILDER_FEE_RECEIVER, // Builder fee receiver
  });

  // 4. Broadcast order to Asset Chain
  const tx = await agentWallet.sendTransaction(orderTxn);
  console.log(`Order dispatched by AI agent. Hash: ${tx.hash}`);

  const receipt = await tx.wait();
  console.log(`Order entered OrderVault in block ${receipt.blockNumber}`);
}
```

***

### Best Practices for Autonomous Agents

1. **Private Key Isolation**: Store agent private keys in hardware security modules (HSM), AWS Secrets Manager, or strictly isolated environment variables.
2. **Oracle Slippage Bounds**: Always supply an explicit `acceptablePrice` when creating increase or decrease orders. If market volatility moves oracle prices beyond your acceptable price before keeper execution, the order safely reverts and refunds collateral.
3. **Execution Keeper Buffers**: Ensure your agent maintains a minimal native `RWA` balance to pay initial execution keeper gas fees. Unused keeper gas is refunded automatically to your agent's address upon execution.
4. **Rate Limits & API Keys**: For high-frequency price lookups, use your `nct_live_...` secret API key to benefit from higher rate limit thresholds on protocol endpoints.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.nectarliquid.com/builders/ai-agents.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
