This handler runs when an open position is updated, such as when the price changes. It allows you to monitor and manage your open trades in real-time, like tracking profit, updating stop-loss levels, or checking how long the position has been open.
/**
- 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 by:
- Subtracting the entry price (`position.price`) from the current price (`update.price`).
- Multiplying the result by the position size (`position.amount`).
**/
const profit = (update.price - position.price) * position.amount;
// This logs the current profit to the console.
console.log(`Current profit: ${profit}`);
return state; // This returns the updated state object.
}
position.price
) from the current price (update.price
).position.amount
)./**
- 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.
const { price } = update; // This extracts the price from the update object.
// This checks if the price has moved above the current trailing stop level.
if (price > state.trailingStop) {
// This updates the trailing stop to 5% below the new price.
state.trailingStop = price * 0.95;
}
return state; // This returns the updated state object.
}
update
object./**
- 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.
const currentTime = Date.now(); // This gets the current time in milliseconds.
const entryTime = position.entryTime; // This gets the time the position was opened.
// This checks if 1 hour (3600000 milliseconds) has passed since the position was opened.
if (currentTime - entryTime > 3600000) {
// This logs a message to the console if the position has been open for over 1 hour.
console.log("Position has been open for over 1 hour.");
}
return state; // This returns the updated state object.
}