**
I’m trying to calculate the MTM (Mark to Market) of a trade entered through Strategy script. The concept is as follows:
Once a position is entered and exited as per Strategy script, entry price and exit price is calculated using
strategy.opentrades.entry_price(strategy.opentrades-1) strategy.closedtrades.exit_price(strategy.closedtrades-1)
MTM = (Exit Price - Entry Price)*Quantity -for a Long Trade
For some reason, the above subtraction is not happening though I’ve checked individually both Entry Price and Exit Price are correctly calculated.
Can anyone please advise, how to resolve this issue.
`Sample code is below **
//@version=5
`strategy("Strategy-check MTM", overlay=true)
//Inputs
Qty = input(defval = 4,title = "Input Quantity")
StopLoss = input(defval = 30,title = "SL Points")
//Long Entry & Exit`
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if longCondition
strategy.entry("Long", strategy.long,Qty)
float EntryPrice = na
detect_entry = (strategy.position_size[1] == 0 and strategy.position_size > 0)
if detect_entry
EntryPrice := strategy.opentrades.entry_price(strategy.opentrades-1)
SL_Level = EntryPrice - StopLoss
longExit = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if longExit
strategy.exit("Long Exit",from_entry = "Long",qty = Qty, stop = SL_Level)
if hour==15 and minute==15
strategy.close_all()
float ExitPrice = 0
float MTM = 0
detect_exit = (strategy.position_size[1] > 0 and strategy.position_size == 0)
if detect_exit
ExitPrice := strategy.closedtrades.exit_price(strategy.closedtrades-1)
MTM := (ExitPrice-EntryPrice)*Qty```
`
The above code correctly calculates Entry and Exit Prices, but I don’t know why it cannot calculate MTM
Shibu Varghese is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.