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.
export async function addTagToTrade (
tradeId : string ,
tag : string
) : Promise < Trade >
The ID of the trade to tag
The tag to add (will be trimmed)
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.
export async function removeTagFromTrade (
tradeId : string ,
tagToRemove : string
) : Promise < 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.
export async function deleteTagFromAllTrades (
tag : string
) : Promise <{ success : boolean }>
The tag to delete from all user’s trades
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' )
}
Add multiple tags to all trades on a specific date.
export async function addTagsToTradesForDay (
date : string ,
tags : string []
) : Promise <{ success : boolean ; tradesUpdated : number }>
Date in ‘YYYY-MM-DD’ format
Whether the operation completed successfully
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.
export async function updateTradeImage (
tradeIds : string [],
imageData : string | null ,
field : 'imageBase64' | 'imageBase64Second' = 'imageBase64'
) : Promise < Trade []>
Array of trade IDs to update
Base64 image data or URL (null to remove image)
field
string
default: "imageBase64"
Which image field to update (primary or secondary)
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:
Entry Date Match : Trades that were opened on the specified date
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
Use bulk operations when possible
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