How to close a long position in 2 days ?

Questions about MultiCharts and user contributed studies.
User avatar
danilo
Posts: 170
Joined: 02 Jan 2007
Location: Italy
Has thanked: 4 times
Been thanked: 9 times

How to close a long position in 2 days ?

Postby danilo » 20 Sep 2008

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
Attachments
test_DJI.png
(62.36 KiB) Downloaded 373 times

2haerim
Posts: 502
Joined: 01 Sep 2006
Been thanked: 2 times

Postby 2haerim » 20 Sep 2008

Try below.

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);
With or without 'Total' keyword, the result was the same in this case.

User avatar
danilo
Posts: 170
Joined: 02 Jan 2007
Location: Italy
Has thanked: 4 times
Been thanked: 9 times

Postby danilo » 21 Sep 2008

Thanks 2haerim, it does works !


Return to “MultiCharts”