Building With Definitive
This guide walks you through building an application that serves many users using Definitive's Organization API. Whether you're creating an app, Telegram bot, trading terminal or something else, this guide provides the step-by-step process for integrating Definitive's execution infrastructure.
Who is this For?
Overview
You'll leverage Definitive's Organization API to provide your users with professional-grade trading execution. This architecture allows you to:
- Manage multiple user portfolios from a single organization
- Provide institutional-quality execution for users
- Abstract away the complexity of advanced trading and execution
- Maintain self-custody for end users
Step-by-Step Integration
1. Create an Organization
Start by signing up for Definitive to create your organization. This will serve as the parent entity for all your user portfolios.
Visit the Definitive platform and create an account. Once you're logged in, navigate to your organization page:
:::info Organization ID You can find your organization ID on the organization page. You'll need this ID for all API calls using the Organization API. :::
2. Generate Organization API Key
Generate an organization-level API key that will be used for all API calls on behalf of your users.
Navigate to your organization settings page and generate a new API key and secret:
Store these credentials securely in your application.
:::warning Security Never expose your API key and secret in client-side code. Always make API calls from your backend. :::
3. Integrate Organization Endpoints
Use your organization API key to make calls to the /organization
endpoints. These endpoints allow you to manage multiple portfolios and execute trades on behalf of your users.
import { AuthHelpers } from "./auth-helpers";
// Initialize with your organization credentials
const organizationId = "your-organization-id";
const apiKey = process.env.DEFINITIVE_API_KEY;
const apiSecret = process.env.DEFINITIVE_API_SECRET;
// Example: Get organization details and portfolios
const organizationData = await AuthHelpers.signAndSend({
path: "/v2/organization",
method: "GET",
organizationId,
apiKey,
apiSecret,
});
For detailed authentication setup, see the Organization API Getting Started guide.
4. Create User Portfolios
For each user who signs up for your application:
4.1 Create a Portfolio
// Create a new portfolio for the user
const portfolio = await AuthHelpers.signAndSend({
path: "/v2/organization/create-portfolio",
method: "POST",
body: {
portfolioName: `${userId}`,
},
organizationId,
apiKey,
apiSecret,
});
const portfolioId = portfolio.portfolioId;
:::info Portfolio Name While you are free to name each users portfolio anything you'd like we suggest that you use something which easily identifies the user in your system - eg. a user's id. :::
:::info Portfolio ID After creating a portfolio you will be given an ID which will be used for other actions like trading. We suggest that you store this in your database at time of portfolio creation. :::
5. Handle User Deposits (Vaults Created Automatically)
When users are ready to start trading, they need to deposit funds into their Definitive vault. Vaults are now created automatically during the deposit process - no separate vault creation step is needed.
The deposit endpoint returns call data that users can execute to transfer funds, and will automatically create the vault if it doesn't exist.
// Get deposit transaction for user (vault created automatically if needed)
const depositTx = await AuthHelpers.signAndSend({
path: `/v2/organization/portfolios/${portfolioId}/deposit`,
method: "POST",
body: {
chain: "solana", // Currently only Solana supported
asset: "So11111111111111111111111111111111111111112", // Wrapped SOL
amount: "1000000000", // 1 SOL in lamports
walletAddress: userSolanaAddress,
signer: userSolanaAddress, // User's wallet address (vault signer)
},
organizationId,
apiKey,
apiSecret,
});
// Return transaction to user for signing and submission
// The user executes this transaction to deposit funds
:::info Automatic Vault Creation
Vaults are now created automatically during the deposit process. Simply provide the user's wallet address as the signer
parameter, and the vault will be created if it doesn't already exist.
:::
:::info EOA Signers The signer on these vaults should be the user's EOA whether you're using:
- Privy: Use the user's embedded wallet address
- Turnkey: Use the user's managed wallet address
- Self-custody: Use the user's imported wallet address :::
Reference: Deposit
6. Facilitate Trading
Once users have deposited funds, you can facilitate trading using the quote and order endpoints.
6.1 Get Trading Quote
// Get a quote for the user's trade
const quote = await AuthHelpers.signAndSend({
path: `/v2/organization/portfolios/${portfolioId}/trade/quote`,
method: "POST",
body: {
type: "market",
chain: "ethereum",
targetAsset: "0xA0b86a33E6411F8D7B0681b1a0eb82B1F0d55d7a", // Example token
contraAsset: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // WETH
qty: "1000",
orderSide: "buy",
slippageTolerance: "0.01", // 1%
maxPriceImpact: "0.01", // 1%
},
organizationId,
apiKey,
apiSecret,
});
6.2 Submit Order
// Submit the order using the quote
const { quote: quoteDetails, ...externalOrderRequest } = quote;
const order = await AuthHelpers.signAndSend({
path: `/v2/organization/portfolios/${portfolioId}/trade`,
method: "POST",
body: {
externalOrderRequest,
quoteId: quoteDetails.id,
},
organizationId,
apiKey,
apiSecret,
});
console.log(`Order submitted: ${order.orderId}`);
Reference: Get Quote | Submit Order
Additional Features
Portfolio Management
Monitor and manage user portfolios:
- Get Portfolio Details - View portfolio and vault information
- List Positions - Check user balances and positions
- List Transfers - View deposit/withdrawal history
- Refresh Balance - Force balance updates
- Get Portfolio Fees - Gets fees for a portfolio
Order Management
Track and manage trading activity:
- List Orders - View order history across portfolios
- Get Order Details - Get detailed order information
- Cancel Order - Cancel pending orders
Advanced Trading
Support sophisticated trading strategies:
- Limit Orders: Set specific price targets
- TWAP Orders: Time-weighted average price execution
- Stop Orders: Conditional order execution
- Stop-Loss Orders: Risk management automation
- Take Profit Orders: Automatic profit-taking when price targets are reached
Best Practices
Security
- Store API credentials securely (environment variables, secrets management)
- Never expose API keys in client-side code
- Implement proper error handling and retry logic
- Validate all user inputs before API calls
User Experience
- Provide real-time order status updates
- Show clear deposit instructions and transaction status
- Implement proper loading states during API calls
- Handle network errors gracefully
Portfolio Management
- Regularly refresh balances for accurate position data
- Implement proper pagination for large datasets
- Cache frequently accessed data to reduce API calls
- Monitor order status and notify users of important updates
Getting Help
- Documentation: Comprehensive API reference in this documentation
- Discord: Join our Discord community for support
- Twitter: Follow @definitivefi for updates