Access Real-Time Metal Prices with Cognitive Actions

25 Apr 2025
Access Real-Time Metal Prices with Cognitive Actions

In the fast-paced world of finance, having access to real-time data is crucial for making informed decisions. The "Live Metal Prices" service provides developers with powerful Cognitive Actions that allow for the retrieval of current prices for precious metals such as Gold, Silver, Palladium, and Platinum in over 160 currencies, including USD, GBP, and EUR. By integrating these actions into your applications, you can enhance user experience, streamline financial transactions, and provide timely information to clients and stakeholders.

Common use cases for these actions include financial applications that require up-to-date market data, trading platforms that need to display real-time prices for metals, and investment analysis tools that support decision-making based on current market conditions. With these Cognitive Actions, developers can simplify the process of fetching and displaying metal prices, ultimately saving time and resources.

Prerequisites

To get started with Live Metal Prices, you will need a Cognitive Actions API key and a basic understanding of how to make API calls.

Fetch Live Metal and Currency Rates

This action allows you to retrieve real-time prices for Gold, Silver, Palladium, and Platinum based on a selected currency. It is particularly useful for applications where users need to see the current market value of these metals in a specific currency.

Input Requirements:

  • requestedSymbols: A comma-separated string of requested symbols (e.g., "XAU,XAG,PA,PL").
  • requestedCurrency: The currency in which the result should be denominated (e.g., "EUR").

Expected Output:

  • Returns the current prices for the requested metals in the specified currency.
  • Includes success status and any validation messages if the input is not supported.

Use Cases for this action:

  • Financial dashboards that display live updates of metal prices.
  • E-commerce platforms that sell precious metals and need to show current prices.
  • Investment tools that require the latest market data for analysis.

```python
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "64cb0d85-b002-43ff-91e6-7e8d15a307b8" # Action ID for: Fetch Live Metal and Currency Rates

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "requestedSymbols": "XAU,XAG,PA,PL,GBP,EUR",
  "requestedCurrency": "EUR"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Fetch Metal and Currency Rates
This action extends the functionality to allow users to retrieve real-time prices for metals based on a specific unit of weight. This is essential for applications dealing with transactions or calculations that require precise measurements.

**Input Requirements:**
- `requestedSymbols`: A comma-separated string of symbols (e.g., "XAU,XAG,PA,PL").
- `requestedCurrency`: The currency code for the requested conversion (e.g., "EUR").
- `requestedUnitOfWeight`: The unit of weight for measurement (e.g., "gram").

**Expected Output:**
- Provides current prices based on the specified unit of weight, along with a success status and validation messages when necessary.

**Use Cases for this action:**
- Jewelry businesses that need to calculate prices based on weight.
- Financial applications that necessitate precise pricing for transactions involving metals.
- Trading platforms that require weight-specific pricing for user transactions.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "d405465c-0bec-438e-9d34-23d69bb5de97" # Action ID for: Fetch Metal and Currency Rates

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "requestedSymbols": "XAU,XAG,PA,PL,GBP,EUR",
  "requestedCurrency": "EUR",
  "requestedUnitOfWeight": "gram"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Fetch Live Metal Prices
This action simplifies the retrieval process by allowing developers to get real-time prices for metals with smaller payloads. It is useful for applications that need to minimize data transfer while still providing essential market information.

**Input Requirements:**
- `requestedSymbolsList`: A comma-separated list of requested symbols (e.g., "XAU,XAG,PA,PL").

**Expected Output:**
- Returns the latest prices for the requested metals, along with a success status and the base currency.

**Use Cases for this action:**
- Lightweight applications that need quick access to metal prices without the overhead of additional data.
- Financial apps aimed at providing users with a quick glance at market values.
- Integration into widgets or tools that display current prices without requiring extensive data.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "e9b32df9-3c4f-45e6-bf1f-899fce5df471" # Action ID for: Fetch Live Metal Prices

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "requestedSymbolsList": "XAU,XAG,PA,PL,GBP,EUR"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Conclusion
The Live Metal Prices Cognitive Actions provide developers with the tools needed to access and display real-time metal prices efficiently. By integrating these actions, you can enhance financial applications, improve user engagement, and provide timely data that is crucial for decision-making. As the demand for real-time financial information continues to grow, leveraging these Cognitive Actions will place your applications at the forefront of the industry. 

Explore how you can implement these actions today to deliver real-time insights to your users!