Hello guys.

In a Pairs Trading strategy, how could I set a percentage Stop Loss limit, for example, totaling the result of the two assets, -5%?

```CODE:if (HasOpenPosition(bars, PositionType.Long))
{
if ((P1.ProfitPctAsOf(idx) + P2.ProfitPctAsOf(idx)) < -nStop)
{
ClosePosition(P1, OrderType.MarketClose, 0);
ClosePosition(P2, OrderType.MarketClose, 0);
}
else if (xFR[idx] >= xBBSma[idx])
{
PlaceTrade(stock2, TransactionType.Cover, OrderType.MarketClose, 0, "Cover" + stock2);
PlaceTrade(stock1, TransactionType.Sell, OrderType.MarketClose, 0, "Sell" + stock1);
}

}
if (HasOpenPosition(bars, PositionType.Short))
{
if ((P1.ProfitPctAsOf(idx) + P2.ProfitPctAsOf(idx)) < -nStop)
{
ClosePosition(P1, OrderType.MarketClose, 0);
ClosePosition(P2, OrderType.MarketClose, 0);
}
else if (xFR[idx] <= xBBSma[idx])
{
PlaceTrade(stock1, TransactionType.Cover, OrderType.MarketClose, 0, "Cover" + stock1);
PlaceTrade(stock2, TransactionType.Sell, OrderType.MarketClose, 0, "Sell" + stock2);
}
}
private Position P1;
private Position P2;
BarHistory stock1, stock2;
private double nStop;```

0
228
Solved
4 Replies

Bookmark

Sort
Let's start here -
1. You're using a Cover / Sell combination in both blocks.
a. In the top block processing PositionType.Long, it [probably] should be Sell/Short
b. In the bottom block processing PositionType.Short, it [probably] should be Cover/Buy

2. You're currently using MarketClose orders. Is this a strategy for Daily bars?

3. When you said "Stop Loss Limit", did you mean to use a Stop-Limit order? If not, what do you mean by "Limit"?
0
Hi Cone, thanks for your time.

1. I posted here only the part of the code that closes the positions, the opening of positions is in a different section.

2. I probably misunderstood the use of MarketClose, I thought it could close the position in the same candle it is called (daily).

3. No, I did not mean Stop Loss Limit. I meant that my loss summing the two positions taken (one long and one short) should be a maximum of 5%.

Sorry for my poor English.
0
Re: MarketClose
All signals execute on the next bar, so a MarketClose would execute at the close on the bar following the current bar index.

There's no way to exit a position in live trading at the close after "seeing" the close. After evaluating the position profit at the close of a daily, the best you can do is to exit at Market (the next day) or try to exit in the after market session with limit orders.

There are more options if you test with intraday data.

Assuming that you've assigned Position objects to P1 and P2 and that neither are null, your calculation of the position profit is correct. But since there is more code required for these null checks, etc. I assume this is where your trouble is.
1