How to code this stop loss?

 
I need to code a function that close a long position when is reached a particular value of the cross, that of the most recent swing low; the situation is mirrored for short trades, where the expert should find the most recent swing high.

See these pictures for a more clear vision:





----

I'm going to use a function like this to close my orders:

if(OrderType()==OP_BUY)
  {
   if((Bid<StopLoss)
     { 
      OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);
     }
  }



My problem is to calculate the "StopLoss" value as said before. Can you help me?


 
Here is one way:

For long position

int lookBack = 50; // how far to look back for a low

double stoploss = Low[ Lowest(NULL, 0, MODE_LOW, lookBack, 0)];