If I’m in a trade and price moves favourably, I am trying to close half the position and set a stop so that the trade can’t lose. I’ve written this simple code to help me debug it. It does’t seem to work on my spread betting platform. Could someone please tell me whether it should be possible and I’ve done something wrong in the code, or if there’s another way to do it? If it’s not possible on a spread betting platform, is it possible with CFDs?
My screenshot shows that the code runs; Stopmoved = 1 and Soldhalf = 1, but there is no indication that the buy is executed and COUNTOFSHARES never changes to 1.
Code to close half a position
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
IFNOTONMARKETANDclose<close[1]THEN// conditions to enter a short trade
SELLSHORT2perpointatmarket
ENDIF
IFSHORTONMARKETANDclose<tradeprice-10THEN// if the price moves 10pts in my favour...
breakevenLevel=tradeprice-5//...calculate the level for a stop 5pts below the trade open price...
SELLATbreakevenLevelSTOP//...and place a new stop order on market at breakevenLevel, ie 5pts below the trade open price
Partial closure is possible in backtesting even if IG don’t allow it in live trading but also your code at line 10 is
1
buy1PERPOINTatmarket//close half of the trade
If you want to partially close a short position then you must use EXITSHORT and not BUY. BUY will reverse the position and all short positions will be closed as it is not possible to be long and short at the same time in a ProOrder strategy.