Skip to content

cBot Code Samples

This page provides several code snippets that you can use when developing your own cBots. Note that none of the cBots listed below guarantee any financial returns. Make sure to backtest and customise your cBots before deploying any instances on your live account(s).

Samples Repository

More code samples are always available in the git@github.com:spotware/ctrader-automate-samples.git repository. To access it, click here.

Synchronous Operations

All cBots in this section execute their operations synchronously.

Executing Market Orders

  • A simple cBot performing successful operations

The following cBot creates a market order upon startup and saves the result in the result variable.

If order execution is successful, the entry price is printed in the log.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, 10000);

            if (result.IsSuccessful)
            {
                var position = result.Position;
                Print("Position entry price is {0}", position.EntryPrice);
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD
  • Executing Market Order to Buy 10000 EURUSD SUCCEEDED, Position PID14576001
  • Position entry price is 1.19067
  • A simple cBot with customisable parameters

When declaring various cBot properties, you can turn them into customisable parameters using the [Parameter()] declaration. When a new instance of your cBot is launched, you (or other users) will be able to assign custom values to these parameters. To learn more about parameters, click here.

Consider the following example.

1
2
    [Parameter("SMA Period", DefaultValue = 14)]
    public int SmaPeriod { get; set; }

In it, we define the following characteristics.

  • The name of the parameter. It will, subsequently, appear in the cTrader UI ("SMA Period").
  • The default value of the parameter that will apply to all new instances unless it is changed by users (DefaultValue = 14).

In the below code, we show how the SmaPeriod property can be used in an actual cBot.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class SamplecBotReferenceSMA : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("SMA Period", DefaultValue = 14)]
        public int SmaPeriod { get; set; }

        private SampleSMA sma;

        protected override void OnStart()
        {
            sma = Indicators.GetIndicator<SampleSMA>(Source, SmaPeriod);
        }

        protected override void OnTick()
        {
            Print("{0}", sma.Result.LastValue);
        }
    }

Our bot takes the customisable SmaPeriod property and, on start, passes its value to the Indicators.GetIndicator<SampleSMA>() method. This method returns a simple moving average value for the specified period.

When creating a cBot instance, all adjustable parameters can be set up in the 'Add Instance' window.

When launched, the bot informs us of what the last simple moving average value was on every tick.

Log Output

  • CBot instance [Sample cBot Reference SMA, EURUSD, h1] started.
  • 0.975685714285714
  • 0.975681428571429
  • 0.97568
  • CBot instance [Sample cBot Reference SMA, EURUSD, h1] stopped by user.
  • Executing a market order with more arguments

In the previous example, we passed the minimum possible number of arguments to the ExecuteMarketOrder() method. They were the trade type (TradeType.Buy), the symbol (Symbol) and volume (-1).

The ExecuteMarketOrder() method can be called with additional arguments such as Label, StopLoss, TakeProfit, and Comment. The example below specifies the label ("order 1"), the stop loss protection mechanism (10), and the take profit level (10).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    [Robot(TimeZone = TimeZones.UTC)]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, 10000, "order 1", 10, 10);

            if (result.IsSuccessful)
            {
                var position = result.Position;
                Print("Position entry price is {0}", position.EntryPrice);
                Print("Position SL price is {0}", position.StopLoss);
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10) SUCCEEDED, Position PID14576098
  • Position entry price is 1.1896
  • Position SL price is 1.1886

Modifying a Position

In the below example, we only add a take profit value (10) when an order is executed. Afterward, we modify the position to add a stop loss.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
    [Robot()]
    public class SamplecBbot : Robot
    {
        protected override void OnStart()
        {
            var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, 10000,
                                    "order 1", null, 10);
            if (result.IsSuccessful)
            {
                var position = result.Position;
                Print("Position SL price is {0}", position.StopLoss);

                var stopLoss = position.EntryPrice - 10*Symbol.PipSize;
                ModifyPosition(position, stopLoss, position.TakeProfit);

                Print("New Position SL price is {0}", position.StopLoss);

            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (TP: 10) SUCCEEDED, Position PID14576161
  • Position SL price is null
  • Modifying position PID14576161 (SL: 1.18744, TP: 1.18944)
  • Modifying position PID14576161 (SL: 1.18744, TP: 1.18944) SUCCEEDED, Position PID14576161
  • New Position SL price is 1.18744

Closing a Position

  • Performing a full close

The code sample below places a market order. If the gross profit of the resulting position exceeds a certain value (null && position.GrossProfit > 10), it is closed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            ExecuteMarketOrder(TradeType.Buy, SymbolName, 10000, "myLabel");
        }

        protected override void OnTick()
        {
            var position = Positions.Find("myLabel");
            if (position != null && position.GrossProfit > 10)
            {
                ClosePosition(position);
                Stop();
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD
  • Executing Market Order to Buy 10000 EURUSD SUCCEEDED, Position PID14576180
  • Performing a partial close

We will modify the previous example to create two market orders with the same labels ("myLabel"). On each new bar, our cBot will close exactly one-half of one of these orders but only if its volume is equal to or greater than 20,000.

We also use the Positions.FindAll() method. It returns a list of positions that we can iterate through.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            ExecuteMarketOrder(TradeType.Buy, SymbolName, 20000, "myLabel");
            ExecuteMarketOrder(TradeType.Buy, SymbolName, 30000, "myLabel");
        }

        protected override void OnBar()
        {
            var positions = Positions.FindAll("myLabel", SymbolName, TradeType.Buy);

            foreach (var position in positions)
            {
                if (position.VolumeInUnits >= 20000)
                {
                    ClosePosition(position, 15000);
                }
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 20000 EURUSD
  • Executing Market Order to Buy 20000 EURUSD SUCCEEDED, Position PID14579299
  • Executing Market Order to Buy 30000 EURUSD
  • Executing Market Order to Buy 30000 EURUSD SUCCEEDED, Position PID14579300

Creating Pending Orders

  • Creating limit and stop orders

Limit and stop orders are pending orders; despite this, they are created similarly to market orders. However, when creating limit and stop orders, you also have to specify their target price and there is no market range.

This cBot creates two limit orders and a stop order. It then iterates through the orders and prints their labels and IDs to the log.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            PlaceLimitOrder(TradeType.Buy, SymbolName, 10000, Symbol.Bid, "myLimitOrder");
            PlaceLimitOrder(TradeType.Buy, SymbolName, 20000, Symbol.Bid-2*Symbol.PipSize,
                    "myLimitOrder");
            PlaceStopOrder(TradeType.Buy, SymbolName, 10000, Symbol.Ask, "myStopOrder");

            foreach (var pendingOrder in PendingOrders)
            {
                 Print("Order placed with label {0}, id {1}",
                                              pendingOrder.Label, pendingOrder.Id);
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19036)
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19036) SUCCEEDED, PendingOrder OID25220794
  • Placing Limit Order to Buy 20000 EURUSD (Price: 1.19017)
  • Placing Limit Order to Buy 20000 EURUSD (Price: 1.19017) SUCCEEDED, PendingOrder OID25220795
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19040)
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19040) SUCCEEDED, PendingOrder OID25220796
  • Order placed with label myLimitOrder, id 25220794
  • Order placed with label myLimitOrder, id 25220795
  • Order placed with label myStopOrder, id 25220796
  • Creating pending orders with more parameters

As is the case with market orders, you can also specify the order label, various protection mechanisms, the order expiry date, and provide a comment.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            DateTime midnight = Server.Time.AddDays(1).Date;

            PlaceLimitOrder(TradeType.Buy, SymbolName, 10000, Symbol.Bid, "mySample_cBot", 10, null, midnight, "First");

            PlaceStopOrder(TradeType.Buy, SymbolName, 10000, Symbol.Ask, "mySample_cBot", 10, 10, null, "Second");

            foreach (var order in PendingOrders)
            {
                var sl = order.StopLoss == null ? "" : "SL: " + order.StopLoss;
                var tp = order.TakeProfit == null ? "" : " TP: " + order.TakeProfit;

                var text = string.Format("{0} {1}", sl, tp);

                if (order.OrderType == PendingOrderType.Limit)
                    Print(order.Comment + " Limit Order " + text);
                else
                    Print(order.Comment + " Stop Order " + text);
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19049, SL: 10, ExpireTime: 12/05/2018 00:00:00)
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19049, SL: 10, ExpireTime: 12/05/2018 00:00:00) SUCCEEDED, PendingOrder OID25220807
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19053, SL: 10, TP: 10)
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19053, SL: 10, TP: 10) SUCCEEDED, PendingOrder OID25220808
  • Limit Order
  • First Limit Order SL: 1.18949
  • Second Stop Order SL: 1.18953 TP: 1.19153

Modifying Pending Orders

It is possible to modify several characteristics of pending orders.

The example below showcases how to modify the target price, the protection levels, or the expiration date and time of a pending order.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            var price = Symbol.Ask + 10 * Symbol.PipSize;
            DateTime? expiry = Server.Time.AddHours(12);
            PlaceStopOrder(TradeType.Buy, SymbolName, 10000, price, "myLabel", 10, 10, expiry);
        }

        protected override void OnBar()
        {
            foreach (var order in PendingOrders)
            {
                if (order.Label == "myLabel")
                {
                    double newPrice = Symbol.Ask + 5 * Symbol.PipSize;
                    ModifyPendingOrder(order, newPrice, order.StopLossPips,
                                                                order.TakeProfitPips, order.ExpirationTime);
                }
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19254, SL: 10, TP: 10, ExpireTime: 11/05/2018 20:07:25)
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19254, SL: 10, TP: 10, ExpireTime: 11/05/2018 20:07:25) SUCCEEDED, PendingOrder OID25220877

Canceling Pending Order

The syntax for canceling an order is CancelPendingOrder(order), where order is of type PendingOrder.

The below example shows canceling all orders with the label "myLabel".

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnTick()
        {
            foreach (var order in PendingOrders)
            {
                if (order.Label == "myLabel")
                {
                    CancelPendingOrder(order);
                }
            }
        }
    }

Position Events

It is possible to subscribe to events related to various trading operations. For example, to test whether a position is opened, we subscribe to an event that is raised for all Position objects on open.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            Positions.Opened += PositionsOnOpened;
            ExecuteMarketOrder(TradeType.Buy, Symbol, 10000, "myLabel", 10, 10);
        }

        private void PositionsOnOpened(PositionOpenedEventArgs args)
        {
            var pos = args.Position;
            Print("Position opened at {0}", pos.EntryPrice);
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10) SUCCEEDED, Position PID14579468
  • Position opened at 1.19224

Similarly, it is possible to subscribe to events that are raised every time a position is closed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            Positions.Closed += PositionsOnClosed;
            ExecuteMarketOrder(TradeType.Buy, Symbol, 10000, "myLabel", 10, 10);
        }

        protected override void OnBar()
        {
            var position = Positions.Find("myLabel");
            if (position != null)
                ClosePosition(position);
        }

        private void PositionsOnClosed(PositionClosedEventArgs args)
        {
            var pos = args.Position;
            Print("Position closed with {0} profit", pos.GrossProfit);
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10) SUCCEEDED, Position PID14579479
  • Closing position PID14579299
  • Closing position PID14579299 SUCCEEDED, Position PID14579299
  • Position closed with 20.64 profit

Coordinates Conversion

The below cBot allows users to place limit orders in a suitable direction simply by right-clicking on a chart. It achieves this by converting mouse Y-coordinates to chart Y-coordinates (which, for symbols, correspond to symbol prices).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class CoordinatesConverter : Robot
    {
        protected override void OnStart()
        {
            Chart.MouseUp += Chart_MouseUp;
        }

        private void Chart_MouseUp(ChartMouseEventArgs obj)
        {
            var desiredPrice = Chart.YToYValue(obj.MouseY);
            var desiredTradeType = desiredPrice > Symbol.Bid ? TradeType.Sell : TradeType.Buy;
            PlaceLimitOrder(desiredTradeType, SymbolName, 10000, desiredPrice);
        }
    }
}

Asynchronous Execution

The code samples above are designed to implement cBots using synchronous execution. As we have stated previously, C# also supports asynchronous operations. Apart from multi-threading, asynchronous execution is the only way to make your cBot perform several actions within the same timeframe.

Executing Market Orders Asynchronously

The syntax of the asynchronous methods is similar to that of the synchronous ones. While they accept the same types of arguments, their return type is TradeOperation instead of TradeResult.

  • Basic asynchronous operations

The following cBot demonstrates how asynchronous operations work. A market order is created; in the next conditional, the bot checks if the operation is executing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            TradeOperation operation = ExecuteMarketOrderAsync(TradeType.Buy, SymbolName, 10000);

            if (operation.IsExecuting)
            {
                Print("Operation Is Executing");
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD
  • Operation Is Executing
  • Executing Market Order to Buy 10000 EURUSD SUCCEEDED, Position PID14579532
  • Executing an order

The next example highlights the difference between synchronous and asynchronous methods.

The cBot checks if an operation is executing right after calling an asynchronous method. It does it again after calling a synchronous method. The log output for these two actions is different.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            TradeOperation operation = ExecuteMarketOrderAsync(TradeType.Buy, SymbolName, 10000);
            Print(operation.IsExecuting ? "Operation Is Executing" : "Operation executed");
            ExecuteMarketOrder(TradeType.Buy, SymbolName, 20000);
            Print(operation.IsExecuting ? "Operation Is Executing" : "Operation executed");

        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD
  • Operation Is Executing
  • Executing Market Order to Buy 20000 EURUSD
  • Executing Market Order to Buy 10000 EURUSD SUCCEEDED, Position PID14579541
  • Executing Market Order to Buy 20000 EURUSD SUCCEEDED, Position PID14579542
  • Operation executed
  • Executing an order with more parameters

The following cBot places an order specifying its label ("myLabel"), protection levels (10, 10), symbol (SymbolName), and volume (10000).

The example also contains the Positions collection and the FindAll() method. Find() and FindAll() can be used to find positions with the same label, symbol, and trade type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            ExecuteMarketOrderAsync(TradeType.Buy, SymbolName, 10000, "myLabel", 10, 10);
        }
        protected override void OnTick()
        {
            Position[] positions = Positions.FindAll("myLabel", SymbolName, TradeType.Buy);
            if (positions.Length == 0)
                return;

            foreach (var position in positions)
                Print("Buy at {0} SL {1}", position.EntryPrice, position.StopLoss);

            Stop();
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (SL: 10, TP: 10) SUCCEEDED, Position PID14579719
  • Buy at 1.19087 SL null
  • Buy at 1.19357 SL 1.19257
  • cBot "New cBot" was stopped for EURUSD, h1.

Modifying Position Asynchronously

The cBot below places a market order and then modifies the newly opened position.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            ExecuteMarketOrderAsync(TradeType.Buy, SymbolName, 10000, "myLabel", null, 10);
        }

        protected override void OnTick()
        {
            Position myPosition = Positions.Find("myLabel");
            if (myPosition != null && myPosition.StopLoss == null)
            {
                double stopLoss = Symbol.Bid - 10 * Symbol.PipSize;
                ModifyPositionAsync(myPosition, stopLoss, myPosition.TakeProfit);
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (TP: 10) SUCCEEDED, Position PID14579736
  • Modifying position PID14579300 (SL: 1.19213, TP: null)
  • Modifying position PID14579300 (SL: 1.19213, TP: null) SUCCEEDED, Position PID14579300

Closing a Position Asynchronously

The next example demonstrates closing a position asynchronously if it exists.

The Find() method is used to search the Positions collection for the position with a specific label.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            ExecuteMarketOrderAsync(TradeType.Buy, Symbol, 10000, "myLabel", null, 10);
        }

        protected override void OnTick()
        {
            Position myPosition = Positions.Find("myLabel");
            if (myPosition != null && myPosition.GrossProfit > 10)
            {
                ClosePosition(myPosition);
                Stop();
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD (TP: 10)
  • Executing Market Order to Buy 10000 EURUSD (TP: 10) SUCCEEDED, Position PID14579740
  • Closing position PID14579300
  • Closing position PID14579300 SUCCEEDED, Position PID14579300
  • cBot "New cBot" was stopped for EURUSD, h1.

Placing Limit and Stop Orders Asynchronously

As stated above, placing pending orders is similar to creating market orders.

However, there are some slight differences in the arguments between these two methods. The market range is absent from the arguments list. Moreover, you have to specify the target price, and you can pass an optional argument specifying the order expiration date.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            DateTime expiry = Server.Time.AddHours(12);
            PlaceLimitOrderAsync(TradeType.Buy, SymbolName, 10000, Symbol.Bid, "myLabel", null, null, expiry);
            PlaceStopOrderAsync(TradeType.Buy, SymbolName, 10000, Symbol.Ask + 10 * Symbol.PipSize, "myLabel", null, null, expiry);
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19382, ExpireTime: 12/05/2018 00:18:19)
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19487, ExpireTime: 12/05/2018 00:18:19)
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19382, ExpireTime: 12/05/2018 00:18:19) SUCCEEDED, PendingOrder OID25221859
  • Placing Stop Order to Buy 10000 EURUSD (Price: 1.19487, ExpireTime: 12/05/2018 00:18:19) SUCCEEDED, PendingOrder OID25221860

Modify Pending Orders Asynchronously

The following cBot modifies limit orders asynchronously.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            DateTime expiry = Server.Time.AddHours(12);
            PlaceLimitOrderAsync(TradeType.Buy, SymbolName, 10000, Symbol.Bid, "myLabel", null, 10, expiry);

        }
        protected override void OnTick()
        {
            foreach (var order in PendingOrders)
            {
                if (order.Label == "myLabel" && order.StopLoss == null)
                    ModifyPendingOrderAsync(order, order.TargetPrice, 10, 10, null);
            }
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19347, TP: 10, ExpireTime: 12/05/2018 00:22:08)
  • Modifying pending order OID25221860 (Volume: 10000, Price: 1.19487, SL: 10, TP: 10, ExpireTime: 12/05/2018 00:18:19)
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19347, TP: 10, ExpireTime: 12/05/2018 00:22:08) SUCCEEDED, PendingOrder OID25221906
  • Modifying pending order OID25221860 (Volume: 10000, Price: 1.19487, SL: 10, TP: 10, ExpireTime: 12/05/2018 00:18:19) SUCCEEDED, PendingOrder OID25221860
  • Modifying pending order OID25221906 (Volume: 10000, Price: 1.19347, SL: 10, TP: 10, ExpireTime: 12/05/2018 00:22:08)
  • Modifying pending order OID25221906 (Volume: 10000, Price: 1.19347, SL: 10, TP: 10, ExpireTime: 12/05/2018 00:22:08) SUCCEEDED, PendingOrder OID25221906

Canceling Pending Orders Asynchronously

  • Canceling all pending orders

The cBot below asynchronously cancels all currently pending orders.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnBar()
        {
            foreach (var pendingOrder in PendingOrders)
            {
                CancelPendingOrderAsync(pendingOrder);
            }
        }
    }

Log Output

  • cBot "cancel pending order" was started successfully for EURUSD, h1.
  • Cancelling pending order OID274705
  • Cancelling pending order OID274706
  • Cancelling pending order OID274707
  • Cancelling pending order OID274708
  • Cancelling pending order OID274709
  • Cancelling pending order OID274705 SUCCEEDED, PendingOrder OID274705
  • Cancelling pending order OID274706 SUCCEEDED, PendingOrder OID274706
  • Cancelling pending order OID274707 SUCCEEDED, PendingOrder OID274707
  • Cancelling pending order OID274708 SUCCEEDED, PendingOrder OID274708
  • Cancelling pending order OID274709 SUCCEEDED, PendingOrder OID274709
  • Canceling pending orders with a certain label

This cBot only cancels pending orders with a certain label.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnBar()
        {
            foreach (var pendingOrder in PendingOrders)
            {
                if (pendingOrder.Label == "myLabel")
                    CancelPendingOrderAsync(pendingOrder);
            }
        }
    }

Callback Functions for Asynchronous Methods

Once a result is returned, using asynchronous operations often requires controlling execution. To handle this, you can add a callback function at the end of the list of parameters of all asynchronous methods.

This function will be called as soon as a response is received from the server. For instance, it could be called when a position is opened, modified, or closed.

  • Asynchronous market order with a callback
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            TradeOperation operation = ExecuteMarketOrderAsync(TradeType.Buy, SymbolName, 10000, PositionOpened);
            if (operation.IsExecuting)
                Print(operation.ToString());
            else
                Print(operation.TradeResult.ToString());

        }

        private void PositionOpened(TradeResult tradeResult)
        {
            var position = tradeResult.Position;
            Print(tradeResult.ToString());
            if (tradeResult.IsSuccessful)
                Print("Position {0} opened at {1}", position.Id, position.EntryPrice);
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy 10000 EURUSD
  • TradeOperation (Executing Market Order to Buy 10000 EURUSD EXECUTING)
  • Executing Market Order to Buy 10000 EURUSD SUCCEEDED, Position PID14579835
  • TradeResult (Success, Position: PID14579835)
  • Position 14579835 opened at 1.19414
  • Using lambda expressions

Instead of defining a named callback method you can use lambda expressions.

In the following example, when an order is placed the description of the result will be printed to the log.

1
2
3
4
5
6
7
8
9
    [Robot()]
    public class Sample_cBot : Robot
    {
        protected override void OnStart()
        {
            PlaceLimitOrderAsync(TradeType.Buy, SymbolName, 10000,
                       Symbol.Ask - 20 * Symbol.PipSize, "myLabel", result => Print(result.ToString()));
        }
    }

Log Output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19320)
  • Placing Limit Order to Buy 10000 EURUSD (Price: 1.19320) SUCCEEDED, PendingOrder OID25222083
  • TradeResult (Success, PendingOrder: OID25222083)