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

# Portfolio Quick Buy Flow

> End-to-end steps to execute a quick portfolio buy transaction

## 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.

<Info>
  All investment operations require M2M authentication with a bearer token and the `x-user-id` header to specify
  which user's portfolio to access.
</Info>

### 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

<Steps>
  <Step title="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.

    <CodeGroup>
      ```javascript Node.js theme={null}
      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();
      }

      ```

      ```bash cURL theme={null}
      curl -X GET 'https://api.wealthyhood.com/automations' \
        -H 'Accept: application/json' \
        -H 'Authorization: Bearer YOUR_M2M_TOKEN' \
        -H 'x-user-id: 64f0c51e7fb3fc001234abcd'
      ```
    </CodeGroup>

    <Tip>
      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.
    </Tip>

    <Check>
      Successful response returns an array of automations. Filter for `category: "TopUpAutomation"` and `status: "Active"` to determine if monthly automation is enabled.
    </Check>
  </Step>

  <Step title="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.

    <CodeGroup>
      ```javascript Node.js theme={null}
      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();
      }

      ```

      ```bash cURL theme={null}
      curl -X GET 'https://api.wealthyhood.com/cash' \
        -H 'Accept: application/json' \
        -H 'Authorization: Bearer YOUR_M2M_TOKEN' \
        -H 'x-user-id: 64f0c51e7fb3fc001234abcd'
      ```
    </CodeGroup>

    <Tip>
      Compare the available cash balance in the portfolio's currency with the intended investment amount. Display a
      warning if insufficient funds are available.
    </Tip>

    <Warning>
      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.
    </Warning>
  </Step>

  <Step title="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.

    <CodeGroup>
      ```javascript Node.js theme={null}
      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();
      }

      ```

      ```bash cURL theme={null}
      curl -X POST 'https://api.wealthyhood.com/investments/portfolio/preview' \
        -H 'Accept: application/json' \
        -H 'Content-Type: application/json' \
        -H 'Authorization: Bearer YOUR_M2M_TOKEN' \
        -H 'x-user-id: 64f0c51e7fb3fc001234abcd' \
        -d '{
          "portfolioId": "64f0c51e7fb3fc001234abcd",
          "orderAmount": 100.0,
          "allocationMethod": "holdings"
        }'
      ```
    </CodeGroup>

    <Tip>
      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.
    </Tip>

    <Info>
      The preview response includes:

      * Execution windows for both scenarios
      * Fees breakdown (commission and FX)
      * Estimated quantities per asset
      * Foreign currency rates (if applicable)
    </Info>
  </Step>

  <Step title="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.

    <CodeGroup>
      ```javascript Node.js theme={null}
      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();
      }

      ```

      ```bash cURL theme={null}
      # Smart execution (market hours)
      curl -X POST 'https://api.wealthyhood.com/investments/portfolio/orders' \
        -H 'Accept: application/json' \
        -H 'Content-Type: application/json' \
        -H 'Authorization: Bearer YOUR_M2M_TOKEN' \
        -H 'x-user-id: 64f0c51e7fb3fc001234abcd' \
        -d '{
          "portfolioId": "64f0c51e7fb3fc001234abcd",
          "orderAmount": 100.0,
          "allocationMethod": "holdings",
          "executeEtfOrdersInRealtime": false
        }'

      # Express execution (real-time)
      curl -X POST 'https://api.wealthyhood.com/investments/portfolio/orders' \
        -H 'Accept: application/json' \
        -H 'Content-Type: application/json' \
        -H 'Authorization: Bearer YOUR_M2M_TOKEN' \
        -H 'x-user-id: 64f0c51e7fb3fc001234abcd' \
        -d '{
          "portfolioId": "64f0c51e7fb3fc001234abcd",
          "orderAmount": 100.0,
          "allocationMethod": "holdings",
          "executeEtfOrdersInRealtime": true
        }'
      ```
    </CodeGroup>

    <Warning>
      Only users enabled for real-time ETF execution can set `executeEtfOrdersInRealtime: true`. The API will reject
      the request if the user is not eligible.
    </Warning>

    <Tip>
      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)
    </Tip>

    <Check>
      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.
    </Check>
  </Step>
</Steps>

***

## 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

* API Reference → [Preview Portfolio Buy](/api-reference/investments/portfolio-preview)
* API Reference → [Execute Portfolio Buy Order](/api-reference/investments/portfolio-order)
* API Reference → [Get Automations](/api-reference/automations/get-automations)
* API Reference → [Get Cash](/api-reference/cash/get-cash)
