Code: Select all
using System;
using System.Diagnostics;
using System.Threading;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class LatencyMeter : Robot
{
[Parameter("Number of Tests", DefaultValue = 10)]
public int NumberOfTests { get; set; }
[Parameter("Distance (Pips)", DefaultValue = 100)]
public double DistancePips { get; set; }
protected override void OnStart()
{
Print("--- Starting cTrader Broker Latency Test ---");
long minLatency = long.MaxValue;
long maxLatency = 0;
long totalLatency = 0;
int successfulTests = 0;
for (int i = 0; i < NumberOfTests; i++)
{
// Calculate safe price far below the market
double safePrice = Symbol.Ask - (DistancePips * Symbol.PipSize);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Synchronous method blocks until the broker server responds
TradeResult result = PlaceLimitOrder(TradeType.Buy, SymbolName, Symbol.VolumeInUnitsMin, safePrice, "LatencyTest");
stopwatch.Stop();
long latency = stopwatch.ElapsedMilliseconds;
if (result.IsSuccessful)
{
successfulTests++;
totalLatency += latency;
if (latency < minLatency) minLatency = latency;
if (latency > maxLatency) maxLatency = latency;
Print("Test {0} Latency: {1} ms", i + 1, latency);
// Clean up: Cancel the pending order
TradeResult cancelResult = CancelPendingOrder(result.PendingOrder);
if (!cancelResult.IsSuccessful)
{
Print("Warning: Failed to cancel test order.");
}
}
else
{
Print("Test {0} Failed. Error: {1}", i + 1, result.Error);
}
// Pause briefly between pings so we don't spam the API
Thread.Sleep(500);
}
// Calculate and print final statistics
if (successfulTests > 0)
{
double avgLatency = (double)totalLatency / successfulTests;
Print("=====================================");
Print("cTRADER LATENCY TEST RESULTS ({0}/{1} successful)", successfulTests, NumberOfTests);
Print("Average Latency: {0:F1} ms", avgLatency);
Print("Minimum Latency: {0} ms", minLatency);
Print("Maximum Latency: {0} ms", maxLatency);
Print("=====================================");
}
else
{
Print("All test attempts failed. Check margin or distance parameters.");
}
// Stop the cBot automatically when the test is finished
Stop();
}
}
}