What It Does

This handler runs when a trade position is closed. It allows you to perform actions like logging the final profit/loss, resetting indicators, or saving trade history after a trade is completed.


State and Update Breakdown


Examples

Example 1: Log Final Profit/Loss

/**
    - This defines an asynchronous function that takes two inputs: `state` and `update`.
    - `state` is the memory box for your strategy.
    - `update` contains the latest market data.
**/
async (state = {}, update = {}) => {
  const position = HFS.getPosition(state); // This checks if there’s an open trade position by looking at the state object.
  
  /**
  - This calculates the profit or loss by:
    - Subtracting the entry price (`position.price`) from the closing price (`update.price`).
    - Multiplying the result by the position size (`position.amount`).
  **/
  const profit = (update.price - position.price) * position.amount;
  
  // This logs the final profit or loss to the console.
  console.log(`Position closed. Final Profit/Loss: ${profit}`);
  
  return state; // This returns the updated state object.
}


Example 2: Reset Indicators

/**
    - This defines an asynchronous function that takes two inputs: `state` and `update`.
    - `state` is the memory box for your strategy.
    - `update` contains the latest market data.
**/
async (state = {}, update = {}) => {
	// This logs a message indicating that the position is closed and indicators are being reset.
  console.log("Position closed. Resetting indicators...");
  
  return { ...state, indicators: {} }; // This resets the indicators object to an empty object while keeping the rest of the state intact.
}


Example 3: Save Trade History

/**
    - This defines an asynchronous function that takes two inputs: `state` and `update`.
    - `state` is the memory box for your strategy.
    - `update` contains the latest market data.
**/
async (state = {}, update = {}) => {
  const position = HFS.getPosition(state); // This checks if there’s an open trade position by looking at the state object.
  
  state.tradeHistory = state.tradeHistory || []; // This initializes the tradeHistory array if it doesn’t already exist. If it does exist, it keeps the current array.
  
  // This adds the trade details (type, entry price, exit price, and profit/loss) to the tradeHistory array.
  state.tradeHistory.push({
    type: position.type, // Type of trade (e.g., "long" or "short")
    entryPrice: position.price, // Entry price of the trade
    exitPrice: update.price, // Exit price of the trade
    profit: (update.price - position.price) * position.amount, // Profit/loss of the trade
  });
  
  return state; // This returns the updated state object.
}