Help with coding tigh trailing stop loss

Hi, I am trying to complete the code for a tight trailing stop for my EA. The Trailing Stop I currently have is such as that only when the trade is much closer to the TP, is when the actual SL is moved up, but I want to make a trailing stop that stays exactly the same distance from the current price, as the price level moves closer to the TP, any advice would be helpful.

Here is the code:

```void OnTick()
{

for(int i = PositionsTotal()-1; i >= 0; i--){

ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket)){

double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
double posOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double posSl = PositionGetDouble(POSITION_SL);
double posTp = PositionGetDouble(POSITION_TP);

int posType = PositionGetInteger(POSITION_TYPE);

// if(ask - posSl > )
double possibleWin = posTp - bid;
double newSl = bid - possibleWin;
newSl = NormalizeDouble(newSl,_Digits);

if(newSl > posSl){
Print("Position #", ticket, " was modified by tsl...");
}
}
}else if(posType == POSITION_TYPE_SELL){
// if(ask - posSl > )
double possibleWin = ask - posTp;
double newSl = ask + possibleWin;
newSl = NormalizeDouble(newSl,_Digits);

if(newSl < posSl  ||  posSl == 0){
Print("Position #", ticket, " was modified by tsl...");
}
}
}
}
}```

A solution for a long position could be as follows:

```double max_quote = (max_quote < current_quote) ? current_quote : max_quote;
double percentage = ((position_TP - max_quote) / (position_TP - open_price));
double stop_out = max_quote - (max_profit * perccentage);

if(stop_out > current_quote)
{ ClosePosition(); }

```

untested pseudocode but it should give an idea on how it could be approached.

EDIT:

you will need to take measures to track each single positions values according to their parameters. Especially you need to store the value max_quote for each position, or recalculate it every time based on opening time and quote.

Reason: