I want to write a code that is able to close a long position in differents trades, for example if I by 4 shares at time T I'd like to sell them at time T+n and T+n+1, I wrote the following piece of code but doesn't work:
------------------------------------------------------------------------------
inputs: AvgLen(15), nShares(4), Debug(1);
vars: Avg(0);
Avg = Xaverage(Close, AvgLen);
if (C crosses above Avg) then
Buy("LE") nShares Shares Next Bar at Market;
if (Marketposition = 1) and (Close < Avg) and (CurrentContracts > 0) Then
Sell("LX") (CurrentContracts / 2) Shares Next Bar at Market;
if (Debug > 0) Then
Print(ELDateTime2Str(Date, Time_s), ", MP= ", Marketposition:0, ", NCtr= ", CurrentContracts:0);
------------------------------------------------------------------------------
The problem is that after having sold 2 shares I'm still long of 2 shares, even MC do agree on that (looking to the debug output) but the "sell" code is never executed !
Please find attached a screeshoot of MC
How to close a long position in 2 days ?
Try below.
With or without 'Total' keyword, the result was the same in this case.
Code: Select all
inputs: AvgLen(15), nShares(4), Debug(1);
vars: Avg(0);
Avg = Xaverage(Close, AvgLen);
if (C crosses above Avg) then
Buy("LE") nShares Shares Next Bar at Market;
if (Marketposition = 1) and (Close < Avg) and (CurrentContracts > 0) Then
Sell("LX1") (CurrentContracts * 2 / 4) Shares Total Next Bar at Market;
if (Marketposition = 1) and (Close < Avg) and (CurrentContracts = nShares / 2) Then
Sell("LX2") (CurrentContracts * 3 / 4) Shares Total Next Bar at Market;
if (Marketposition = 1) and (Close < Avg) and (CurrentContracts = nShares / 4) Then
Sell("LX3") (CurrentContracts * 4 / 4) Shares Total Next Bar at Market;
if (Debug > 0) Then
Print(Date, Time_s, ", MP= ", Marketposition:0, ", NCtr= ", CurrentContracts:0);