New Trading API

Created at 22 Nov 2013, 12:59
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!
Spotware's avatar

Spotware

Joined 23.09.2013

New Trading API
22 Nov 2013, 12:59


In the new version of cAlgo we added a new trading API. The main advantage of this new trading API is the ability to choose between Synchronous and Asynchronous trade methods. The previous API allowed asynchronous methods only and although it is rather flexible, it is difficult to deal with on occasion, because one needs to implement more methods in order to handle some situations.

 

Example: Market Order

For example, if we want to execute a market order and print the newly created positions entry price or error message if execution failed, to the log, the code looked like this in the old API:

 

protected override void OnStart()
{
    var request = new MarketOrderRequest(TradeType.Buy, 10000) 
    {
        Label = "My Label"
    };
    Trade.Send(request);
}

protected override void OnPositionOpened(Position openedPosition)
{
    Print("Position created entry price: {0}", openedPosition.EntryPrice);
}

protected override void OnError(Error error)
{
    Print("Failed to create position :(");
}

Now, we can use the synchronous method, which means that our program will not continue execution until the operation is completed. So, everything is implemented in a single method:

 

protected override void OnStart()
{
    var result = ExecuteMarketOrder(TradeType.Buy, Symbol, 10000, "My Label");
    
    if (result.IsSuccessful)
    {
        Print("Position created entry price: {0}", result.Position.EntryPrice);
    }
    else
    {
        Print("Failed to create position :(");
    }
}

Alternatively one can choose asynchronous methods that require us to implement several methods and in general the program becomes more complex. But sometimes it can be useful, for example if we want to execute several commands in parallel:

 

protected override void OnStart()
{
    ExecuteMarketOrderAsync(TradeType.Buy, Symbol, 10000, "My Label", OnExecuted);
}

private void OnExecuted(TradeResult result)
{
    if (result.IsSuccessful)
    {
        Print("Position created entry price: {0}", result.Position.EntryPrice);
    }
    else
    {
        Print("Failed to create position :(");
    }
}

You can also notice that the code using new methods is shorter than the code using old requests.

 

Supported Methods

Right now cAlgo supports the following methods (as well as their Async analogues):

  • ExecutemarketOrder
  • PlaceLimitOrder
  • PlaceStopOrder
  • ModifyPosition
  • ModifyPendingOrder
  • ClosePosition
  • CancelPendingOrder

 

Partial Close

Note that ClosePosition supports partial close now. Volume to close must be specified in a second parameter:

 

ClosePosition(position, 50000);

 

Positions and PendingOrders collections

Another change that was made in this version, is the replacement of Account.Positions and Account.PendingOrders collections with Positions and PendingOrders properties of a Robot. We have changed an iteration behavior of those collections so that they become compatible with the new API. For example, you can use code such as the following, to close all positions:

 

foreach (var position in Positions)
{
    ClosePosition(position);
}

If we used Account.Position in the code snippet above, it wouldn't work since the synchronous method ClosePosition closes a position and removes it from the collection. The new collections allow to continue iteration in this case.

We've also added new events to Positions collection: Opened and Closed

 

protected override void OnStart()
{
    Positions.Opened += OnPositionsOpened;
}

private void OnPositionsOpened(PositionOpenedEventArgs args)
{
    Print("Position #{0} is opened", args.Position.Id);
}

In contrast to the overridden OnPositionOpened(position) method, this is called for any position of an account, not only for positions opened by the current robot instance. If you need to handle the same robots positions opening only, you can use the position's label. The Positions.Closed event works in the same way.

 

Old API support

The old API will be supported for an infinitely long time, so you don't need to rewrite your existing robots, although we recommend the use of the new API because of it's simplicity. The new features will be added in the new API only.

 

 

 

 


@Spotware
Replies

jeex
22 Nov 2013, 13:23

Great job!

Great Job. Congrats.


@jeex

hichem
25 Nov 2013, 11:28

Is the new API available on all Brokers?

 

I have noticed that on the LqdMarkets cAlgo, the new API is not yet updated
 


@hichem

Spotware
25 Nov 2013, 14:18

RE:

hichem said:

Is the new API available on all Brokers?

 

I have noticed that on the LqdMarkets cAlgo, the new API is not yet updated
 

Not yet. It will be available on the next update.


@Spotware

Hyperloop
29 Nov 2013, 08:25

Hi,

Are there currently future plans to release additional events for both the Positions AND PendingOrders?

Ex) PendingOrders.Placed, PendingOrders.Cancelled, Positions.Modified, PendingOrders.Modified

Being able to detect global changes like these would be very helpful especially for who run multiple robots simultaneously.

PS. So far the new API is great; love it!


@Hyperloop

Spotware
29 Nov 2013, 11:31

RE:

Hyperloop said:

Hi,

Are there currently future plans to release additional events for both the Positions AND PendingOrders?

Ex) PendingOrders.Placed, PendingOrders.Cancelled, Positions.Modified, PendingOrders.Modified

Being able to detect global changes like these would be very helpful especially for who run multiple robots simultaneously.

PS. So far the new API is great; love it!

Thank you for your kind words. Yes, there are plans for additional events such as you have described.


@Spotware

Hyperloop
29 Nov 2013, 20:42

Great, I look forward to future updates.


@Hyperloop

lec0456
13 Dec 2013, 03:56

isn't the code in the example wrong? It reads:

foreach (var position in Positions)
{
    ClosePosition(positions);
}

There is o variable positions, right? shouldn't it be:

foreach (var position in Positions)
{
    ClosePosition(position);
}

???


@lec0456

Spotware
13 Dec 2013, 09:25

RE:

lec0456 said:

isn't the code in the example wrong? It reads:

foreach (var position in Positions)
{
    ClosePosition(positions);
}

There is o variable positions, right? shouldn't it be:

foreach (var position in Positions)
{
    ClosePosition(position);
}

???

Yes, thank you for pointing that out. 


@Spotware

hermoso
31 Dec 2013, 04:53

RE:

lec0456 said:

isn't the code in the example wrong? It reads:

foreach (var position in Positions)
{
    ClosePosition(positions);
}

There is o variable positions, right? shouldn't it be:

foreach (var position in Positions)
{
    ClosePosition(position);
}

???

isn't the thing you wrote wrong? It reads:

There is o variable positions, right? shouldn't it be:

There is no variable positions, right?


@hermoso

lec0456
31 Dec 2013, 08:33

that is correct,  meant to say that there is NO variable named "positions"  and that that the function ClosePosition should use the variable "position"

 

it was just a type-o, I wanted clarified


@lec0456

AlexanderRC
05 Nov 2014, 00:40

Should not OnError() virtual method be marked as [Obsolete]?

As it is not possible to deduce which API call caused the error?


@AlexanderRC

Spotware
05 Nov 2014, 14:09

RE:

AlexanderRC said:

Should not OnError() virtual method be marked as [Obsolete]?

OnError is not obsolete, it handles errors from both API approaches.

As it is not possible to deduce which API call caused the error?

No, it is not possible. We plan to add TradeOperation to TradeResult in the future.


@Spotware

lec0456
05 Mar 2015, 04:34

When I use Trade.Executing it gives a warning that this is obsolete.

 

What is the new way to get this functionality


@lec0456

Spotware
05 Mar 2015, 11:28

RE:

lec0456 said:

When I use Trade.Executing it gives a warning that this is obsolete.

 

What is the new way to get this functionality

If you use synchronous methods like ExecuteMarketOrder, ClosePosition, etc., there is no need to check the executing property. If you use asynchronous methods like ExecuteMarketOrderAsync, ClosePositionAsync, etc., you can check IsExecuting property of TradeOperation object:

            var operation = ExecuteMarketOrderAsync(...);
            ...
            RefreshData();
            if (operation.IsExecuting)
              ...

 


@Spotware

RhettG
03 Jul 2015, 13:56

Hi

So:

OnPositionClosed - Only handles positions opened by this instance of this bot

OnPositionsClosed - Handles any and all positions on your account

Correct?

What if I stop the bot and start it again later with trades opened by the previous version still in the system?

What about stop and limit orders placed by this instance of this bot? It seems to me they aren't included in OnPositionClosed when they close and I have to manipulate the comment and label fields to keep my bot running on only its own trades. 

Is there any thought to including positions opened by stop and limit orders in the OnPositionOpened and OnPositionClosed methods?

I often want to use the comment and labels for other things and I can't edit those while a trade is open so its tricky (I seem to have lots of code manipulating, concatenating and splitting strings so I can see exactly what my bots are doing. One day when I am an expert coder I'll have more confidence.)

Thanks for a great product. Keep up the excellent work.


@RhettG

Spotware
07 Jul 2015, 12:07

Dear Trader,

OnPositionClosed is obsolete therefore we do not recommend it. The old API is also obsolete and we do not recommend the use of it.

We recommend you to subscribe a method to the Positions.Closed event which is called each time a position closes. You can filter the positions closed based on some label filter.


@Spotware

psossa.mobile
29 Apr 2016, 01:20

RE: RE:

This post was removed by moderator.


greybox
08 May 2016, 12:01

When will Partial Closure work in Backtest??


@greybox

greybox
11 May 2016, 04:34

@Spotware kindly comment on when partial closure will be available in Backtest, very important feature for me. 


@greybox

Spotware
11 May 2016, 12:14

Dear Trader,

It's in our plans to provide users with the ability to partially close a position in Backtesting in the future. However, we cannot provide you with an ETA. Stay tuned.

Additionally, you can post your ideas/suggestions to http://vote.spotware.com/


@Spotware

greybox
14 May 2016, 02:31

Please, it's such an important feature for me. Kindly include it in the next version.
Partial closure already works in Live, so should be easy for you to enable it for Backtest.


@greybox

greybox
26 May 2016, 05:37

RE:

Spotware please provide an update to this matter.

greybox said:

Please, it's such an important feature for me. Kindly include it in the next version.
Partial closure already works in Live, so should be easy for you to enable it for Backtest.

 


@greybox

robartrioson
17 Aug 2016, 03:22

New Trading API vs forex signals

Foreign exchange signal suppliers often cost for their service, typically as a lot as $one hundred a month. For this the subscriber will get 1-5 alerts a day, sent by way of e-mail, text message or instant messenger. The dealer is below no obligation to do something with the knowledge, of course. They are advisory in nature, and the dealer is free to ignore them fully if he wants to. But most traders usually go along with the recommendation that involves them by forex signals. They wouldn’t pay for the service if they didn’t find the advice useful. To know more forex signals


@robartrioson

... Deleted by UFO ...

... Deleted by UFO ...