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

# TypeScript Starter Kit

> Place orders via REST API and stream market data via WebSocket. Get your first trade in under 10 minutes, then customize the bot for your strategy.

A streamlined quick-start for the Decibel TypeScript starter kit: set up fast, then customize.

<CardGroup cols={1} className="max-w-3xl mx-auto my-6">
  <Card title="Part 1: Get Your First Trade under 5 min" icon="zap" href="#part-1">
    Follow the exact steps to install, configure, and place your first order.
  </Card>

  <Card title="Part 2: Mental Model & Architecture" icon="brain" href="#part-2">
    Understand Decibel's three-tier account model, execution queue, and funding.
  </Card>

  <Card title="Part 3: Make It Yours" icon="sparkles" href="#part-3">
    Customize markets, order logic, and Trading Accounts for your own strategy.
  </Card>
</CardGroup>

<a id="part-1" />

## Part 1: Get Your First Trade under 5 min

Follow these steps exactly to get your first trade running.

### 1. Prerequisites

* [Node.js](https://nodejs.org/) 18+
* [Petra Wallet](https://petra.app/) browser extension (recommended, optional thanks to Aptos Connect)
* [Git](https://git-scm.com/downloads)
* [Aptos CLI](https://aptos.dev/build/cli#-install-the-aptos-cli) (recommended)

### 2. Get Your Credentials

You need two things: an API Wallet (for signing transactions) and an API Key (for authenticated API requests).

#### Create API Wallet

1. Go to [app.decibel.trade/api](https://app.decibel.trade/api)
2. Connect your Petra Wallet or "Continue with Google"
3. Click **"Create API Wallet"**

<img src="https://mintcdn.com/aptoslabs/Dzk3tLl4GZATvw6n/images/tssk/create-api-wallet.png?fit=max&auto=format&n=Dzk3tLl4GZATvw6n&q=85&s=42ffd13821db1e00570a8e7d0cbde2c5" alt="Create API Wallet Example" width="2746" height="1032" data-path="images/tssk/create-api-wallet.png" />

4. Copy the Private Key immediately (you only see it once)
5. Also save the Wallet Address shown on the same screen

<Warning>
  Store your private key securely! Anyone with this key can access your funds.
</Warning>

#### Create API Key (Bearer Token)

The API Key is used for authenticated requests to the Decibel REST API. You'll get this from Geomi (Aptos Build).

1. Sign up or log in at [geomi.dev](https://geomi.dev)
   * Click "Continue with Google" or enter your email

2. Create or select a project
   * If you're new, you'll see "No resources yet", that's fine!
   * Your project dashboard will show available resources

3. Add an API Key resource

   <img src="https://mintcdn.com/aptoslabs/Dzk3tLl4GZATvw6n/images/tssk/geomi-dashboard.png?fit=max&auto=format&n=Dzk3tLl4GZATvw6n&q=85&s=68de455967bb95b1a2f8492d81798ea7" alt="Geomi Dashboard" width="2374" height="1176" data-path="images/tssk/geomi-dashboard.png" />

   * Click the **"API Key"** card (find it under "Add more resources to your project")

4. Fill out the API Key form:

   <img src="https://mintcdn.com/aptoslabs/Dzk3tLl4GZATvw6n/images/tssk/create-api-key.png?fit=max&auto=format&n=Dzk3tLl4GZATvw6n&q=85&s=1e89cdb7a5b20707bc445fb6a9d49c63" alt="Create API Key Form" width="2392" height="1334" data-path="images/tssk/create-api-key.png" />

   * **API Key Name:** Choose a name (e.g., `decibel` or `my-trading-bot`)
   * **Network:** Select **"Decibel Devnet"** from the dropdown (important!)
   * **Description:** Optional, add a note about what this key is for (150 chars max)
   * **Client usage:** Leave this **OFF** (unless you're building a web/mobile app)
   * Click **"Create New API Key"**

5. Copy your Bearer Token

   <img src="https://mintcdn.com/aptoslabs/Dzk3tLl4GZATvw6n/images/tssk/get-bearer-token.png?fit=max&auto=format&n=Dzk3tLl4GZATvw6n&q=85&s=b2e9ce3111062f215f7655f52db6837f" alt="Get Bearer Token" width="2400" height="1452" data-path="images/tssk/get-bearer-token.png" />

   * After creation, you'll see your API key in the "API Keys" table
   * Find the **"Key secret"** column, this is your Bearer token
   * Click the copy icon next to the masked key (shows as `*****...*****`)

<Info>
  This "Key secret" is your `API_BEARER_TOKEN`. It's the full Bearer token, not just the key name.
</Info>

### 3. Configure the Project

<CodeGroup>
  ```bash Clone and Install theme={null}
  # Clone the repo
  git clone https://github.com/tippi-fifestarr/testetna.git
  cd testetna

  # Install dependencies
  npm install

  # Create env file
  cp .env.example .env
  ```
</CodeGroup>

Open `.env` and paste your credentials:

```bash .env theme={null}
API_WALLET_PRIVATE_KEY=YOUR_COPIED_KEY_HERE
API_WALLET_ADDRESS=0xYOUR_WALLET_ADDRESS_HERE
API_BEARER_TOKEN=YOUR_BEARER_TOKEN_HERE
```

**Quick checklist:**

* `API_WALLET_PRIVATE_KEY`: From Decibel App (Create API Wallet). Both formats are accepted:

  * AIP-80 format: `ed25519-priv-0x...` (as copied from the Decibel app)
  * Hex format: `0x...` (64 hex characters)

  Paste the key exactly as you copied it — do not add or remove the `ed25519-priv-` prefix.
* `API_WALLET_ADDRESS`: From Decibel App (Create API Wallet)
* `API_BEARER_TOKEN`: From Geomi (Create API Key, "Key secret" column)

### 4. Run the "Quick Win"

This script handles everything: funding (via private faucet), account creation, minting USDC, depositing, and placing a trade.

```bash theme={null}
npm run quick-win
```

<Check>
  **If you see "🎉 Order Placement Complete!", congratulations. The code works.**
</Check>

<a id="part-2" />

## Part 2: Mental Model & Architecture 🏗️

Trading on Decibel has specific mechanics that differ from CEXs and many DEXs. Here are 5 key concepts for API traders.

<Tip>
  **Jump to [Part 3](#part-3) if you're ready to start customizing your code.** You can always come back here later.
</Tip>

### 1. The Three-Tier Account Model

Decibel uses a three-tier account structure for programmatic trading:

| Tier                | Description                                                                                                                                                  |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Primary Wallet**  | Your login account. Used to access Decibel App and create API Wallets.                                                                                       |
| **API Wallet**      | A separate wallet for API trading. Holds APT for gas fees and signs all trading transactions. This is your `API_WALLET_ADDRESS`.                             |
| **Trading Account** | Created from your API Wallet. Holds USDC for trading collateral. Address is extracted from transaction events and written to `.env` as `SUBACCOUNT_ADDRESS`. |

**Flow:** Primary Wallet → Create API Wallet → Create Trading Account → Deposit USDC → Trade.

<img src="https://mintcdn.com/aptoslabs/canlJUnLiLpjMoUM/images/tssk/three-account.png?fit=max&auto=format&n=canlJUnLiLpjMoUM&q=85&s=bf69c920ffcf0782cea59f72f9d45dfa" alt="Three-tier account model" width="800" height="533" data-path="images/tssk/three-account.png" />

<Note>
  For API traders, you primarily interact with the API Wallet (not the Primary Wallet). Most users will have a single Trading Account, though you can create multiple for different strategies.
</Note>

### 2. Async Execution (The Queue)

Decibel is an on-chain CLOB (Central Limit Order Book).

| Platform    | Behavior                                                                     |
| ----------- | ---------------------------------------------------------------------------- |
| **CEX**     | `response = placeOrder()` → Returns "Filled"                                 |
| **Decibel** | `response = placeOrder()` → Returns "Transaction Hash" (Ticket to the Queue) |

Execution is asynchronous. The REST response confirms *submission*, not *fill*. Use the [WebSocket stream](/api-reference/websockets/orderupdate) for execution updates.

### 3. "Lazy" Continuous Funding

* **Traditional:** Pay funding every 8 hours
* **Decibel:** Funding ticks every second (continuous accrual)

You only "pay" (settle) funding when you modify or close the position.

<Warning>
  Your `Unrealized PnL` includes accrued funding debt. Watch it closely to avoid liquidation.
</Warning>

### 4. Reduce-Only Logic

Decibel implements strict "Close First" logic.

A Reduce-Only order will never flip your position (e.g., Long 1 → Short 1). It caps execution at your current size, preventing accidental exposure when closing positions aggressively.

See [Place Order](/developer-hub/on-chain/order-management/place-order) for implementation details.

### 5. Bulk Orders (Unique Optimization)

For Market Makers and HFTs:

You can update multiple orders in a single transaction, saving gas and getting atomic updates for spread management.

See [Place Bulk Order](/developer-hub/on-chain/order-management/place-bulk-order) for implementation details.

<a id="part-3" />

## Part 3: Make It Yours

Now that you have a working baseline, here's how to adapt this code for your actual strategy.

### How to Trade a Different Market

Open `src/5-place-order.ts`. Find the "Configuration" section.

**Change this:**

```typescript theme={null}
const marketName = config.MARKET_NAME || 'BTC/USD';
```

**To this:**

```typescript theme={null}
const marketName = 'ETH/USD'; // or SOL/USD, APT/USD, etc.
```

<Note>
  Run `npm run setup` to see a list of all available market names. Market names use the format `SYMBOL/USD` (not `SYMBOL-PERP`).
</Note>

### How to Change Your Order Logic

Open `src/5-place-order.ts`. Find the "Order Parameters" section.

**Change this:**

```typescript theme={null}
const userPrice = 50000;
const userSize = 0.001;
const isBuy = true;
```

**To your own logic:**

```typescript theme={null}
// Example: A simple moving average bot might look like this
const userPrice = calculatedMovingAverage;
const userSize = riskManagementSize;
const isBuy = signal === 'BULLISH';
```

### Focus on Order Management

After running `quick-win`, you have a funded Trading Account ready to use. You can now focus on:

* `src/5-place-order.ts`: Customize your trading strategy
* `src/6-query-order.ts`: Check order status

<Tip>
  You don't need to create a new Trading Account for every trade. Once you have USDC deposited (from `quick-win`), you can run `5-place-order` and `6-query` repeatedly using the same Trading Account.
</Tip>

### How to Use a Different Trading Account

If you want to use a specific Trading Account (e.g., for a different strategy):

1. Create a new one: `npm run create-subaccount`
2. The script automatically updates your `.env` file with the new `SUBACCOUNT_ADDRESS`
3. Run `npm run deposit-usdc` to fund it

**How the Trading Account script works:**

* Calls `create_new_subaccount`, which creates a non-primary Trading Account (random address)
* Extracts the Trading Account address from the `SubaccountCreatedEvent` in the transaction events
* Verifies the address via the API (with up to 5 retries for indexer lag)
* Writes the address to your `.env` file

**To manually select a different Trading Account:**

* After running `create-subaccount`, check the list of Trading Accounts it prints
* Manually edit `.env` and set `SUBACCOUNT_ADDRESS` to the address you want
* Or modify `src/2-create-subaccount.ts` to change the selection logic

## Part 4: What's Next? 🚀

<Steps>
  <Step title="Monitor Risk">
    Build a script to track `Unrealized PnL` + `Accrued Funding` to avoid liquidation.
  </Step>

  <Step title="Market Making">
    Use `src/7-websocket-updates.ts` to listen to the orderbook and place Maker orders.
  </Step>

  <Step title="Explore Order Types">
    Look into `Post-Only` and `Reduce-Only` params in the API docs for advanced control.
  </Step>
</Steps>

### Resources

<CardGroup cols={2}>
  <Card title="Full Documentation" icon="book" href="/quickstart/overview">
    Complete Decibel documentation
  </Card>

  <Card title="Placing Your First Order" icon="shopping-cart" href="/quickstart/placing-your-first-order">
    Alternative guide with Netna and Testnet examples
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.com/invite/decibel">
    Get help from the community
  </Card>

  <Card title="Netna Faucet" icon="faucet" href="https://netna-faucet.decibel.trade">
    Staging network faucet
  </Card>
</CardGroup>

### Network Support

This starter kit is tested and configured for Netna staging network only.

<Info>
  The `getExplorerLink()` function in `utils/client.ts` generates explorer URLs for Netna transactions. For other networks, you need to manually select the network from the explorer dropdown.
</Info>
