Skip to content

Code Samples

This page provides several examples of cBot code. Please, note that none of the cBots listed below guarantee any financial returns. For better results, make sure to backtest and customize your robots before deploying any instances on your live account(s).

Synchronous Operations

All cBots in this section execute their code in sequence.

Executing Market Orders

  • A simple cBot performing successful operations

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

If the 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 containing an error

If we modify the volume parameter in the previous example to -1 (which is not a valid value for a trading volume), we will get an error printed in the log.

This example shows how you can modify cBots to stop in case there is an error.

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

            if (!result.IsSuccessful)
                Stop();
        }
    }

Log output

  • cBot "New cBot" was started successfully for EURUSD, h1.
  • Executing Market Order to Buy -1 EURUSD
  • Executing Market Order to Buy -1 EURUSD FAILED with error "BadVolume"
  • cBot "New cBot" was stopped for EURUSD, h1.
  • A simple cBot with customizable parameters

When declaring various cBot properties, you can turn them into customizable parameters using the [Parameter()] attribute. When a new instance of your cBot is launched, users will be able to input custom values into these parameters depending on what you have specified in your code.

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 Automate UI ("SMA Period").
  • The default value of the parameter that will apply to all new instances unless 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 customizable SmaPeriod property and, on start, passes it to the #c!c# Indicators.GetIndicator<SampleSMA>() method. This method returns a certain simple moving average value for the specified period.

When creating a cBot instance, all adjustable parameters can be set up in the 'Parameters' tab located to the left of the 'Trade Watch' display.

Image title

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.

For a brief on parameters and data types, please, consult our reference library and our intro to C# and .NET.

  • Executing a market order with more parameters

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

The ExecuteMarketOrder method can be called with additional parameters 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.

To omit the StopLoss parameter, we have to write null in its place.

 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 creates 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
  • Doing 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 `#!c# Positions.FindAll() method. It returns an array 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 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' events to positions. For example, to test whether a position is opened, we subscribe an event to all Position objects.

The event will also be raised if a position is opened manually by a trader or automatically by another cBot.

 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 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

Asynchronous Execution

The code samples above are designed to implement cBots using synchronous trade operation methods. As we have stated previously, C# also supports asynchronous operations. Apart from ulti-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 very similar to that of the synchronous ones, they accept the same type of argument lists, the main difference is that the return type is TradeOperation instead of TradeResult.

  • Asynchronous operations

The following cBot demonstrates asynchronous operations. A market order is created; in the next statement, the robot 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 creates 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 executes a market order and then modifies the 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 the position 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, you have to specify the target price, and you can set up an additional optional parameter 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
 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 the label myLabel
 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 mode 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 callback method you can 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)

Last update: November 25, 2022

Comments