Money management risk

Hi Everyone;

I don´t know if it is possible to code this. It is the way I trade with success and I want to test it.

I risk 500 eur per trade. From my open position to my stop I find out how many shares do I have to invest to have a 500 eur risk.
Lets say my Initial equity is 50.000 eur and I want to risk maximum 5.000 eur anytime. Then, I can start with 10 open positions. (10x500)

But as I have a trailing stop, when some stocks have it stop point above the entryprice, I have the possibility to invest in a new stock because there is risk available. Therefore if that happens I will have more stocks risking the same quantity.

What I have codified is this:

SetOption("initialequity",50000); 
SetOption("maxopenpositions",10);

RoundLotSize = 1;
loss= 500;
distance = C-WMA(C,22);
risk = distance/C;
shares=floor(loss/ValueWhen(distancia !=0,distancia));
SetPositionSize(Ref(acciones,-1),spsShares);

type or paste code here

As you can see I have a fixed number of "maxOpenPositions" and should be variable depending on the risk used up to 5.000 eur.

thank you