Close trade after x seconds

Created at 19 Sep 2014, 07:53
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
RV

RV13

Joined 29.08.2014

Close trade after x seconds
19 Sep 2014, 07:53


In cAlgo, how can I code the following: "close trade xyz after x seconds"?
 


@RV13
Replies

adheer
19 Sep 2014, 09:15

Here is the code.

It goes through all open positions, and calculates the elapsed time (in seconds) since the position was opened. If the elapsed time is greater than X (seconds), it closes the position.

DateTime currTime = Time;	// The current time.
int posCount = Positions.Count; // Total positions.

for( int i = posCount - 1; i >= 0; i-- )
{
	// Total seconds elapsed for a trade.
	int elapsedSeconds = (int) (currTime.Subtract(Positions[i].EntryTime).TotalSeconds);
	if ( elapsedSeconds > X )
		ClosePosition(Positions[i]);	// Close the trade.
}


Note : I use for loop to iterate (from upper bound to 0) instead of using the foreach iterator. This is because we (may) close the position during the iteration.


@adheer

adheer
19 Sep 2014, 09:19

RE:

adheer said:

Here is the code.

It goes through all open positions, and calculates the elapsed time (in seconds) since the position was opened. If the elapsed time is greater than X (seconds), it closes the position.

DateTime currTime = Time;	// The current time.
int posCount = Positions.Count; // Total positions.

for( int i = posCount - 1; i >= 0; i-- )
{
	// Total seconds elapsed for a trade.
	int elapsedSeconds = (int) (currTime.Subtract(Positions[i].EntryTime).TotalSeconds);
	if ( elapsedSeconds > X )
		ClosePosition(Positions[i]);	// Close the trade.
}


Note : I use for loop to iterate (from upper bound to 0) instead of using the foreach iterator. This is because we (may) close the position during the iteration.

Line number 8 in the above code 

if ( elapsedSeconds > X )

should be read as 

if ( elapsedSeconds > X )

The <strong>X</strong> is due to the HTML formatting.


@adheer