# Typescript

### Table of Contents

1. [Base URLs](#base-urls)
2. [Authentication](#authentication)
3. [Core Concepts](#core-concepts)
4. [Account Management](#account-management)
5. [Market Data](#market-data)
6. [Order Management](#order-management)
7. [Position Management](#trade-history)
8. [Trade History](#trade-history)
9. [Utility Endpoints](#utility-endpoints)

### Base URLs

```typescript
const BASE_URLS = {
  TESTNET: "https://perps-tradeapi.kanalabs.io",
  MAINNET: "https://perps-tradeapi.kana.trade"
};
```

### Authentication

All endpoints require an API key passed in the headers:

```typescript
headers: {
  'x-api-key': process.env.API_KEY
}
```

### Core Concepts

#### Profile Address

All on-chain trades are executed using your profile address, not your wallet address. You must fetch your profile address first.

**Endpoint**: `GET /getProfileAddress`

```typescript
async function getProfileAddress(userAddress: string): Promise<string> {
  const response = await axios.get(`${BASE_URL}/getProfileAddress`, {
    params: { userAddress },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

### Account Management

#### Get Wallet Balance

**Endpoint**: `GET /getWalletAccountBalance`

```typescript
async function getWalletBalance(userAddress: string): Promise<number> {
  const response = await axios.get(`${BASE_URL}/getWalletAccountBalance`, {
    params: { userAddress },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get Profile Balance

**Endpoint**: `GET /getProfileBalanceSnapshot`

```typescript
async function getProfileBalance(userAddress: string): Promise<number> {
  const response = await axios.get(`${BASE_URL}/getProfileBalanceSnapshot`, {
    params: { userAddress },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

Get Net Profile Balance

This endpoint returns the net profile balance, which includes both the available balance in trading account and any pending balances from closed positions on all markets.

**Endpoint**: `GET /getNetProfileBalance`

```typescript
async function getNetProfileBalance(userAddress: string): Promise<number> {
  const response = await axios.get(`${BASE_URL}/getNetProfileBalance`, {
    params: { userAddress },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Deposit Funds

**Endpoint**: `GET /deposit`

```typescript
async function depositFunds(userAddress: string, amount: number): Promise<void> {
  const response = await axios.get(`${BASE_URL}/deposit`, {
    params: { userAddress, amount },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Withdraw Funds

**Endpoint**: `GET /withdrawSpecifiMarket`

```typescript
async function withdrawFunds(
  userAddress: string, 
  marketId: number, 
  amount: number
): Promise<void> {
  const response = await axios.get(`${BASE_URL}/withdrawSpecifiMarket`, {
    params: { userAddress, marketId, amount },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  const committedTxn = await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
  await aptos.waitForTransaction({
        transactionHash: committedTxn.hash,
    });
  return committedTxn.hash
}
```

### Market Data

#### Get Market Info

**Endpoint**: `GET /getMarketInfo`

```typescript
async function getMarketInfo(marketId: number): Promise<void> {
  const response = await axios.get(`${BASE_URL}/getMarketInfo`, {
    params: { marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get Market Price

**Endpoint**: `GET /getMarketPrice`

```typescript
async function getMarketPrice(marketId: number): Promise<void> {
  const response = await axios.get(`${BASE_URL}/getMarketPrice`, {
    params: { marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get Last Execution Price

**Endpoint**: `GET /getLastPlacedPrice`

```typescript
async function getLastExecutionPrice(marketId: number): Promise<number> {
  const response = await axios.get(`${BASE_URL}/getLastPlacedPrice`, {
    params: { marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get Perpetual Market Info

Retrieves information about perpetual market, optionally filtered by market ID or base name.

**Endpoint**: `GET /getPerpetualAssetsInfo`

```typescript
async function getAssetInfo(marketId?: number, baseName?: string): Promise<any> {
  const response = await axios.get(`${BASE_URL}/getPerpetualAssetsInfo`, {
    params: { marketId, baseName },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get All Markets

Retrieves information about all available markets.

**Endpoint**: `GET /getPerpetualAssetsInfo/allMarkets`

```python
async function getAllMarkets(): Promise<any[]> {
  const response = await axios.get(`${BASE_URL}/getPerpetualAssetsInfo/allMarkets`, {
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

### Order Management

#### Place Limit Order

Places a limit order on the exchange.

**Endpoint**: `GET /placeLimitOrder`

```typescript
interface PlaceLimitOrderParams {
  marketId: number;
  tradeSide: boolean; // true = long, false = short
  direction: boolean; // false = open, true = close
  size: number;
  price: number;
  leverage: number;
  restriction?: number; // optional
  takeProfit?: number;  // optional
  stopLoss?: number;    // optional
}

async function placeLimitOrder(params: PlaceLimitOrderParams): Promise<void> {
  const response = await axios.get(`${BASE_URL}/placeLimitOrder`, {
    params,
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Place Market Order

**Endpoint**: `GET /placeMarketOrder`

```typescript
interface PlaceMarketOrderParams {
  marketId: number;
  tradeSide: boolean; // true = long, false = short
  direction: boolean; // false = open, true = close
  size: number;
  leverage: number;
  restriction?: number; // optional
  takeProfit?: number;  // optional
  stopLoss?: number;    // optional
}
async function placeMarketOrder(params: PlaceMarketOrderParams): Promise<void> {
  const response = await axios.get(`${BASE_URL}/placeMarketOrder`, {
    params,
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Place Multiple Orders

Places multiple orders in a single transaction.

**Endpoint**: `POST /placeMultipleOrders`

```typescript
interface PlaceMultipleOrdersParams {
    marketId: number;
    orderTypes: boolean[]; // true = limit, false = market
    tradeSides: boolean[]; // true = long, false = short
    directions: boolean[]; // false = open, true = close
    sizes: number[];
    prices: number[];
    leverages: number[];
    restrictions?: any[]; // optional
    takeProfits?: any[]; // optional
    stopLosses?: any[]; // optional
}
async function PlaceMultipleOrders(params: PlaceMarketOrdersParams): Promise<void> {
  const response = await axios.get(`${BASE_URL}/placeMultipleOrders`, {
    params,
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Cancel Orders

**Endpoint**: `POST /cancelMultipleOrders`

```typescript
async function cancelMultipleOrders(
  marketId: number,
  orderIds: string[],
  orderSides: boolean[]
): Promise<void> {
  const response = await axios.post(`${BASE_URL}/cancelMultipleOrders`, {
    marketId,
    cancelOrderIds: orderIds,
    orderSides
  }, {
    headers: { 
      'x-api-key': API_KEY,
      'Content-Type': 'application/json'
    }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Cancel And Place Multiple Orders

**Endpoint**: `POST /cancelAndPlaceMultipleOrders`

```typescript
interface CancelAndPlaceMultipleOrdersParams {
    marketId: number;
    cancelOrderIds: any[];
    orderSides: boolean[]; // true = long, false = short
    orderTypes: boolean[]; // true = limit, false = market
    tradeSides: boolean[]; // true = long, false = short
    directions: boolean[]; // false = open, true = close
    sizes: number[];
    prices: number[];
    leverages: number[];
    restrictions?: any[]; // optional
    takeProfits?: any[]; // optional
    stopLosses?: any[]; // optional
}
async function cancelAndPlaceMultipleOrders(params: CancelAndPlaceMultipleOrdersParams): Promise<void> {
  const response = await axios.get(`${BASE_URL}/cancelAndPlaceMultipleOrders`, {
    params,
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

### Position Management

#### Get Positions

**Endpoint**: `GET /getPositions`

```typescript
interface Position {
  market_id: string;
  leverage: number;
  size: string;
  entry_price: string;
  liq_price: string;
  // ... other fields
}

async function getPositions(userAddress: string, marketId?: number): Promise<Position[]> {
  const response = await axios.get(`${BASE_URL}/getPositions`, {
    params: { userAddress, marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Update Take Profit

**Endpoint**: `GET /updateTakeProfit`

```typescript
async function updateTakeProfit(
  marketId: number,
  tradeSide: boolean,
  newTakeProfitPrice: number
): Promise<void> {
  const response = await axios.get(`${BASE_URL}/updateTakeProfit`, {
    params: { marketId, tradeSide, newTakeProfitPrice },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Update Stop Loss

**Endpoint**: `GET /updateStopLoss`

```typescript
async function updateStopLoss(
  marketId: number,
  tradeSide: boolean,
  newStopLossPrice: number
): Promise<void> {
  const response = await axios.get(`${BASE_URL}/updateStopLoss`, {
    params: { marketId, tradeSide, newStopLossPrice },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

### Trade History

#### Get Open Orders

**Endpoint**: `GET /getOpenOrders`

```typescript
interface OpenOrder {
  market_id: string;
  price: string;
  size: string;
  order_type: number; // see order_type explanation
  // ... other fields
}

async function getOpenOrders(userAddress: string, marketId?: number): Promise<OpenOrder[]> {
  const response = await axios.get(`${BASE_URL}/getOpenOrders`, {
    params: { userAddress, marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

Get All Open Order Ids

**Endpoint**: `GET /getAllOpenOrderIds`

```typescript
async function getAllOpenOrderIds(userAddress: string, marketId: number): Promise<any[]> {
  const response = await axios.get(`${BASE_URL}/getAllOpenOrderIds`, {
    params: { userAddress, marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

Get Order Status By Order Id

**Endpoint**: `GET /getOrderStatusByOrderId`

```typescript
async function getOrderStatusByOrderId(marketId: number, orderId: string): Promise<any[]> {
  const response = await axios.get(`${BASE_URL}/getOrderStatusByOrderId`, {
    params: { marketId, orderId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get Order History

**Endpoint**: `GET /getOrderHistory`

```typescript
async function getOrderHistory(userAddress: string, marketId?: number): Promise<any[]> {
  const response = await axios.get(`${BASE_URL}/getOrderHistory`, {
    params: { userAddress, marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Get All Trades

**Endpoint**: `GET /getAllTrades`

```typescript
async function getAllTrades(marketId: number): Promise<any[]> {
  const response = await axios.get(`${BASE_URL}/getAllTrades`, {
    params: { marketId },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data;
}
```

#### Collapse Position

**Endpoint**: `GET /collapsePosition`

```typescript
async function collapsePosition(
  marketId: number
): Promise<void> {
  const response = await axios.get(`${BASE_URL}/collapsePosition`, {
    params: { marketId },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

#### Add Margin

**Endpoint**: `GET /addMargin`

```typescript
async function addMargin(
  marketId: number,
  tradeSide: boolean,
  amount: number
): Promise<void> {
  const response = await axios.get(`${BASE_URL}/addMargin`, {
    params: { marketId, tradeSide, amount },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

**Settle Pnl**

This API returns a transaction payload used to manually (or automatically, on user interactions) refresh the user's position and settle the Pnl for a specific market, allowing the user to claim any unreleased Pnl.

**Endpoint**: `GET /settlePnl`

```typescript
async function settlePnl(
  marketId: number,
  userAddress: string
): Promise<void> {
  const response = await axios.get(`${BASE_URL}/settlePnl`, {
    params: { marketId, userAddress },
    headers: { 'x-api-key': API_KEY }
  });
  
  const payload = response.data.data;
  const transaction = await aptos.transaction.build.simple({
    sender: userAddress,
    data: payload
  });
  await aptos.transaction.signAndSubmitTransaction({
    transaction,
    signer: account
  });
}
```

### Utility Endpoints

#### Get Account APT Balance

**Endpoint**: `GET /getAccountAptBalance`

```typescript
async function getAptBalance(userAddress: string): Promise<number> {
  const response = await axios.get(`${BASE_URL}/getAccountAptBalance`, {
    params: { userAddress },
    headers: { 'x-api-key': API_KEY }
  });
  return response.data.data;
}
```

### Helper Types

```typescript
// Order type explanations
enum OrderType {
  OPEN_LONG = 1,
  OPEN_SHORT = 2,
  INCREASE_LONG = 3,
  INCREASE_SHORT = 4,
  DECREASE_LONG = 5,
  DECREASE_SHORT = 6,
  CLOSE_LONG = 7,
  CLOSE_SHORT = 8
}

// Restriction types
enum RestrictionType {
  NO_RESTRICTION = 0,
  FILL_OR_ABORT = 1,
  POST_OR_ABORT = 3
}
```
