Skip to main content

Overview

This guide explains how to execute a portfolio buy transaction that distributes an investment amount across multiple assets in a user’s portfolio. The flow includes fetching automations to determine if monthly investment buttons should be enabled, verifying cash availability, previewing the transaction, and executing based on smart execution preferences.
All investment operations require M2M authentication with a bearer token and the x-user-id header to specify which user’s portfolio to access.

Prerequisites

  • Access to API endpoints
  • M2M bearer token with required scopes
  • x-user-id header (user identifier, MongoDB ObjectId format)
  • Portfolio ID for the user

Portfolio Quick Buy Flow

1

Fetch automations

Before displaying the portfolio buy interface, fetch the user’s automations to determine if the monthly investment button should be enabled.Call GET /automations to retrieve all recurring investment automations for the user.
const BASE = 'https://api.wealthyhood.com';

async function getAutomations({ token, userId }) {
  const res = await fetch(`${BASE}/automations`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'x-user-id': userId,
      'Accept': 'application/json'
    }
  });
  if (!res.ok) throw new Error(`Failed to get automations: ${res.status}`);
  return res.json();
}
Check for active TopUpAutomation entries. If the user has an active monthly automation, you may want to disable or highlight the monthly investment button to avoid duplicate automations.
Successful response returns an array of automations. Filter for category: "TopUpAutomation" and status: "Active" to determine if monthly automation is enabled.
2

Fetch available cash

Retrieve the user’s available cash balance to verify sufficient funds for the investment.Call GET /cash to retrieve the available cash balance across all currencies.
const BASE = 'https://api.wealthyhood.com';

async function getCashBalance({ token, userId }) {
  const res = await fetch(`${BASE}/cash`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'x-user-id': userId,
      'Accept': 'application/json'
    }
  });
  if (!res.ok) throw new Error(`Failed to get cash: ${res.status}`);
  return res.json();
}
Compare the available cash balance in the portfolio’s currency with the intended investment amount. Display a warning if insufficient funds are available.
The portfolio buy endpoint will reject the transaction if insufficient cash is available, but it’s better UX to check and warn the user beforehand.
3

Fetch portfolio buy preview

Get a preview of the portfolio buy transaction to show execution options, fees breakdown, and estimated orders.Call POST /investments/portfolio/preview with the portfolio ID, order amount, and allocation method.
const BASE = 'https://api.wealthyhood.com';

async function getPortfolioPreview({ token, userId, portfolioId, orderAmount, allocationMethod }) {
  const res = await fetch(`${BASE}/investments/portfolio/preview`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'x-user-id': userId,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      portfolioId,
      orderAmount,
      allocationMethod // 'holdings'
    })
  });
  if (!res.ok) throw new Error(`Failed to get preview: ${res.status}`);
  return res.json();
}
Display both express and smart execution options to the user:
  • Express (real-time): Faster execution but may incur additional fees
  • Smart (market hours): Lower fees but executes during market hours
Show the fees breakdown (fees.express vs fees.smart) and execution windows to help users make informed decisions.
The preview response includes:
  • Execution windows for both scenarios
  • Fees breakdown (commission, FX, realtime execution)
  • Estimated quantities per asset
  • Foreign currency rates (if applicable)
4

Execute portfolio buy based on smart execution toggle

Execute the portfolio buy transaction based on the user’s smart execution preference.Call POST /investments/portfolio/orders with the portfolio ID, order amount, allocation method, and execution preference.
const BASE = 'https://api.wealthyhood.com';

async function executePortfolioBuy({ token, userId, portfolioId, orderAmount, allocationMethod, executeEtfOrdersInRealtime }) {
  const res = await fetch(`${BASE}/investments/portfolio/orders`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'x-user-id': userId,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      portfolioId,
      orderAmount,
      allocationMethod,
      executeEtfOrdersInRealtime // true for express, false for smart
    })
  });
  if (!res.ok) throw new Error(`Failed to execute buy: ${res.status}`);
  return res.json();
}
Only users enabled for real-time ETF execution can set executeEtfOrdersInRealtime: true. The API will reject the request if the user is not eligible.
Use the smart execution toggle from your UI to determine the executeEtfOrdersInRealtime value:
  • Toggle OFF → executeEtfOrdersInRealtime: false (smart execution)
  • Toggle ON → executeEtfOrdersInRealtime: true (express execution)
Successful execution returns an AssetTransaction object with:
  • Transaction ID and status
  • Execution window information
  • Array of orders created
  • Fees breakdown
  • Display amounts and quantities
Display a confirmation screen with the execution window and expected completion date.

Error Handling

  • 400 Bad Request: Validation failure or business rule violation (e.g., insufficient cash, invalid allocation method, target allocation not set up)
  • 401/403: Authentication/authorization failures
  • 404 Not Found: Portfolio not found or does not belong to user

See Also