Skip to main content

Overview

The trades module (server/trades.ts) provides functions for managing trade data including tags, images, and bulk operations on trades.

Tag Management

addTagToTrade

Add a tag to a specific trade.
server/trades.ts:7
export async function addTagToTrade(
  tradeId: string,
  tag: string
): Promise<Trade>
tradeId
string
required
The ID of the trade to tag
tag
string
required
The tag to add (will be trimmed)
trade
Trade
The updated trade object with the new tag
Example
import { addTagToTrade } from '@/server/trades'

try {
  const trade = await addTagToTrade('trade_123', 'scalping')
  console.log('Tags:', trade.tags) // ['scalping']
} catch (error) {
  console.error('Failed to add tag:', error)
}

removeTagFromTrade

Remove a specific tag from a trade.
server/trades.ts:37
export async function removeTagFromTrade(
  tradeId: string,
  tagToRemove: string
): Promise<Trade>
tradeId
string
required
The ID of the trade
tagToRemove
string
required
The tag to remove
trade
Trade
The updated trade object without the removed tag
Example
import { removeTagFromTrade } from '@/server/trades'

const trade = await removeTagFromTrade('trade_123', 'scalping')
// Tag 'scalping' is now removed from the trade

deleteTagFromAllTrades

Delete a tag from all trades belonging to the authenticated user.
server/trades.ts:67
export async function deleteTagFromAllTrades(
  tag: string
): Promise<{ success: boolean }>
tag
string
required
The tag to delete from all user’s trades
success
boolean
Whether the operation completed successfully
Example
import { deleteTagFromAllTrades } from '@/server/trades'

const result = await deleteTagFromAllTrades('old-strategy')
if (result.success) {
  console.log('Tag removed from all trades')
}

addTagsToTradesForDay

Add multiple tags to all trades on a specific date.
server/trades.ts:138
export async function addTagsToTradesForDay(
  date: string,
  tags: string[]
): Promise<{ success: boolean; tradesUpdated: number }>
date
string
required
Date in ‘YYYY-MM-DD’ format
tags
string[]
required
Array of tags to add
success
boolean
Whether the operation completed successfully
tradesUpdated
number
Number of trades that were updated
Example
import { addTagsToTradesForDay } from '@/server/trades'

const result = await addTagsToTradesForDay(
  '2024-03-15',
  ['high-volatility', 'news-event']
)

console.log(`Updated ${result.tradesUpdated} trades`)
This function finds trades where either the entry date or close date falls on the specified date.

Image Management

updateTradeImage

Update chart images for one or more trades.
server/trades.ts:104
export async function updateTradeImage(
  tradeIds: string[],
  imageData: string | null,
  field: 'imageBase64' | 'imageBase64Second' = 'imageBase64'
): Promise<Trade[]>
tradeIds
string[]
required
Array of trade IDs to update
imageData
string | null
required
Base64 image data or URL (null to remove image)
field
string
default:"imageBase64"
Which image field to update (primary or secondary)
trades
Trade[]
Array of updated trade objects
Example
import { updateTradeImage } from '@/server/trades'

// Add primary chart image to multiple trades
const trades = await updateTradeImage(
  ['trade_123', 'trade_456'],
  'data:image/png;base64,iVBORw0KGg...', // Base64 image
  'imageBase64'
)

// Add secondary chart image
await updateTradeImage(
  ['trade_123'],
  'https://example.com/chart.png', // URL
  'imageBase64Second'
)

// Remove image
await updateTradeImage(['trade_123'], null)
You can update multiple trades at once with the same image, which is useful for grouped trades or multiple positions in the same instrument.

Trade Filtering by Date

When using addTagsToTradesForDay, the function searches for trades in two ways:
  1. Entry Date Match: Trades that were opened on the specified date
  2. Close Date Match: Trades that were closed on the specified date
This ensures that all trades active on a given day are tagged, regardless of when they were opened or closed. Example Use Case
import { addTagsToTradesForDay } from '@/server/trades'

// Tag all trades from a specific trading session
await addTagsToTradesForDay(
  '2024-03-15',
  ['NFP-day', 'high-volatility']
)

// This will tag:
// - Trades opened on March 15
// - Trades closed on March 15
// - Even if some were opened earlier or closed later

Error Handling

All trade functions include error handling and will throw errors that should be caught:
import { addTagToTrade } from '@/server/trades'

try {
  await addTagToTrade('invalid_id', 'test')
} catch (error) {
  if (error.message === 'Trade not found') {
    // Handle missing trade
  } else {
    // Handle other errors
  }
}

Cache Revalidation

All mutation operations automatically revalidate the home page cache:
// After updating trades
revalidatePath('/')
This ensures the UI reflects changes immediately after operations complete.

Database Cleanup

Functions that perform database operations include cleanup in finally blocks:
try {
  // Database operations
} catch (error) {
  console.error('Failed:', error)
  throw error
} finally {
  await prisma.$disconnect()
}

Best Practices

Instead of calling addTagToTrade multiple times, use addTagsToTradesForDay or updateTradeImage with multiple trade IDs for better performance.
// Good: Single call for multiple trades
await updateTradeImage(
  ['trade_1', 'trade_2', 'trade_3'],
  imageData
)

// Avoid: Multiple individual calls
// await updateTradeImage(['trade_1'], imageData)
// await updateTradeImage(['trade_2'], imageData)
// await updateTradeImage(['trade_3'], imageData)
While the functions use authenticated user IDs, always verify trades belong to the user before operations:
const userId = await getUserId()
const trade = await prisma.trade.findFirst({
  where: { id: tradeId, userId }
})

if (!trade) {
  throw new Error('Trade not found or access denied')
}
The addTagsToTradesForDay function automatically handles duplicate tags:
// Creates Set to ensure uniqueness
tags: {
  set: Array.from(new Set([...trade.tags, ...tags]))
}

Account Management

Manage trading accounts and calculate metrics

Authentication

User authentication and session management

Build docs developers (and LLMs) love