LogoLogo
  • Introduction
    • 🔴Welcome to IntentX
    • 💢The Omnichain DEX
    • ⚡User Experience Focus
    • 🌐The Meta Front-End
  • On-Chain Derivatives Overview
    • ❓What Problem Does IntentX Solve?
    • 📊Current On-Chain Derivatives Landscape
    • 💡IntentX Solution & Architecture Overview
    • ✅Comparison and Advantages of IntentX
  • IntentX Platform
    • 📈Trading on IntentX
      • 📖Trading Basics
      • 🏫Trading Tutorials
        • 🏫Web3 Wallet
        • 🏫Account Abstracted Wallet
      • 🌡️Liquidations, Margin Management (CVA), and Account Health
      • 📊Instant 1-Click Trading
      • 🛑Take Profit and Stop Loss
      • 💵Collateral & Cross-Margin Accounts
      • 💸Understanding Funding Rates
      • 💰Pricing Data and the Role of Oracles
      • ↕️Unrealized Profit and Loss (uPNL)
      • 📏Open Interest (OI) and Market Activity
      • 🔐Withdrawal Process and Security Measures
      • 📈Advanced Charts by TradingView
    • 🔢Pair List
    • 🌀IntentX Solver Network
      • 🌀Example Solver Order Flow
    • 🫂Referral Program
    • 📱Mobile and Progressive Web App
  • Trading API
    • Introduction
    • Rest API V1
    • Typescript SDK
      • Examples
        • Opening Positions
        • Closing Positions
        • Cancel Positions
        • List Subaccounts
        • List Positions
        • Private Key Authentication
        • Enable Instant Actions
  • Tokenomics
    • 🪙INTX Token and xINTX Staking
    • 🔄Trade & Earn xINTX
    • 📅Token Allocation and Release Schedule
  • Technical Docs (WIP)
    • ⚙️Infrastructure Overview
      • 🔩Technical Docs
      • 🌐Sample Solver Docs
  • Additional Information
    • ❓FAQ
    • 🌐Official Links
    • 📃Terms & Conditions
    • 🔐Security & Audits
    • 🌟Brand & Media Assets
    • 💾Contracts
Powered by GitBook
On this page
  1. Trading API
  2. Typescript SDK
  3. Examples

Opening Positions

import {
  AvailableSolvers,
  calculateAssetQuantityFromCollateral,
  calculatePriceWithSlippage,
  OrderType,
  PositionType,
  SupportedChainId,
} from "@intentx/core";
import { PositionEntityHooks, TradingSDK } from "@intentx/trading-sdk";
import * as dotenv from "dotenv";

dotenv.config();

async function openPositionExample() {
  const tradingSDK = new TradingSDK({
    apiKey: process.env.API_KEY,
    baseUrl: process.env.API_BASE_URL ?? undefined,
  });

  const TARGET_SYMBOL = "XRPUSDT";
  const TARGET_CHAIN_ID = SupportedChainId.BASE;
  const USE_INSTANT_ACTIONS = true;

  const marketTicker = await tradingSDK.marketsManager.getMarketTickerBySymbol(
    TARGET_SYMBOL,
    TARGET_CHAIN_ID
  );

  console.log("marketTicker", marketTicker);

  if (!marketTicker) {
    throw new Error("Market ticker not found");
  }

  const subaccountAddress = "0x52D953159a9a636944C9d96E14CB5DF0948323E9";
  const collateralQuantity = 40; // $40 USD
  const slippage = 0.01; // 1% for market order
  const leverage = 2;
  const direction = PositionType.LONG;

  const marketPrice =
    await tradingSDK.marketsManager.getMarkPriceForSymbol(TARGET_SYMBOL);
  console.log("marketPrice", marketPrice);
  const marketPriceWithSlippage = calculatePriceWithSlippage(
    marketPrice,
    slippage,
    direction,
    "OPEN"
  );

  const assetQuantity = calculateAssetQuantityFromCollateral(
    collateralQuantity,
    leverage,
    marketPriceWithSlippage,
    marketTicker.quantityPrecision,
    marketTicker.pricePrecision
  );

  const position = await tradingSDK.tradeManager.createPosition({
    marketId: marketTicker.id,
    subaccountAddress,
    chainId: TARGET_CHAIN_ID,
    positionType: direction,
    orderType: OrderType.LIMIT,
    limitPrice: 1,
    quantity: assetQuantity,
    slippage: slippage,
    leverage: leverage,
    useInstantActions: USE_INSTANT_ACTIONS,
    solver: AvailableSolvers.PERPS_HUB,
  });

  position.on(PositionEntityHooks.RESERVED, (position, justification) => {
    if (position.orderType === OrderType.LIMIT) {
      console.log("Limit order reserved. Waiting for price execution...");
      process.exit(0);
    }
  });

  position.on(PositionEntityHooks.OPEN_SUCCESS, (position, justification) => {
    console.log("Position opened", position, justification);
  });

  position.on(PositionEntityHooks.OPEN_REJECTED, (position, justification) => {
    console.log("Position failed to open", position, justification);
  });

  position.on(
    PositionEntityHooks.OPEN_PRICE_SETTLED,
    (position, justification) => {
      console.log("Position price settled for", position.id, justification);
      console.log("Average fill quantity", position.openFillQuantity);
      console.log("Average fill price", position.avgOpenFillPrice);
    }
  );

  await position.waitForCompletion();

  // I want to open a market order with ~$40 of collateral
}

openPositionExample()
  .then(() => {
    console.log("Workflow finished");
  })
  .catch((error) => {
    console.error("Error opening position", error);
  });
PreviousExamplesNextClosing Positions

Last updated 1 month ago