### Execute Timers in c# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Demonstrates how to use timers for scheduled operations in cAlgo. It shows how to start, stop, and handle timer ticks using `Timer.Start`, `Timer.Stop`, and `Timer.TimerTick` event, as well as the `OnTimer` override method. This is useful for periodic tasks independent of market events. ```csharp using cAlgo.API; using System; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class TimerSample : Robot { protected override void OnStart() { // Start timer with 1 second interval Timer.Start(TimeSpan.FromSeconds(1)); // Alternative: use event handler Timer.TimerTick += Timer_TimerTick; } private void Timer_TimerTick() { Print($"Timer tick at {Server.Time}"); // Perform periodic operations } protected override void OnTimer() { Print($"OnTimer called at {Server.Time}"); // Alternative timer handler } protected override void OnStop() { Timer.Stop(); } } } ``` -------------------------------- ### Breakout Strategy with Bollinger Bands in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Implements a breakout trading strategy using Bollinger Bands. It identifies consolidation periods and trades breakouts above the upper band or below the lower band. Requires cAlgo.API and cAlgo.API.Indicators namespaces. Inputs include trading parameters like quantity, stop loss, take profit, and Bollinger Bands settings. ```csharp using cAlgo.API; using cAlgo.API.Indicators; namespace cAlgo { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None, AddIndicators = true)] public class SampleBreakoutcBot : Robot { [Parameter("Quantity (Lots)", DefaultValue = 1, MinValue = 0.01)] public double Quantity { get; set; } [Parameter("Stop Loss (pips)", DefaultValue = 20, MinValue = 1)] public int StopLossInPips { get; set; } [Parameter("Take Profit (pips)", DefaultValue = 40, MinValue = 1)] public int TakeProfitInPips { get; set; } [Parameter("Source")] public DataSeries Source { get; set; } [Parameter("Band Height (pips)", DefaultValue = 40.0)] public double BandHeightPips { get; set; } [Parameter("Bollinger Bands Periods", DefaultValue = 20)] public int Periods { get; set; } [Parameter("Consolidation Periods", DefaultValue = 2)] public int ConsolidationPeriods { get; set; } private BollingerBands _bollingerBands; private int _consolidation; protected override void OnStart() { _bollingerBands = Indicators.BollingerBands(Source, Periods, 2, MovingAverageType.Simple); } protected override void OnBar() { var top = _bollingerBands.Top.Last(1); var bottom = _bollingerBands.Bottom.Last(1); // Check for consolidation if (top - bottom <= BandHeightPips * Symbol.PipSize) _consolidation += 1; else _consolidation = 0; if (_consolidation >= ConsolidationPeriods) { var volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity); // Breakout above top band if (Ask > top) { ExecuteMarketOrder(TradeType.Buy, SymbolName, volumeInUnits, "Breakout", StopLossInPips, TakeProfitInPips); _consolidation = 0; } // Breakout below bottom band else if (Bid < bottom) { ExecuteMarketOrder(TradeType.Sell, SymbolName, volumeInUnits, "Breakout", StopLossInPips, TakeProfitInPips); _consolidation = 0; } } } } } ``` -------------------------------- ### Create Trading Panel with Buttons in c# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Demonstrates the creation of a custom trading panel on the chart using UI controls. It includes buttons for 'Buy' and 'Sell' orders, styled with background and foreground colors, and configured with click event handlers to execute market orders. The buttons are arranged in a `Grid` layout and added to the chart. ```csharp using cAlgo.API; namespace cAlgo { [Indicator(AccessRights = AccessRights.None, IsOverlay = true)] public class TradingPanel : Indicator { protected override void Initialize() { var tradeButtonBuy = new Button { Text = "Buy", ForegroundColor = Color.White, BackgroundColor = Color.Green, Height = 25, Width = 75, Margin = 2 }; tradeButtonBuy.Click += args => ExecuteMarketOrderAsync(TradeType.Buy, SymbolName, 1000); var tradeButtonSell = new Button { Text = "Sell", ForegroundColor = Color.White, BackgroundColor = Color.Red, Height = 25, Width = 75, Margin = 2 }; tradeButtonSell.Click += args => ExecuteMarketOrderAsync(TradeType.Sell, SymbolName, 1000); var grid = new Grid(1, 2); grid.AddChild(tradeButtonBuy, 0, 0); grid.AddChild(tradeButtonSell, 0, 1); Chart.AddControl(grid); } public override void Calculate(int index) { } } } ``` -------------------------------- ### Market Order Execution with SL/TP in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Demonstrates executing market orders in cTrader with configurable stop loss, take profit, and trailing stop options. Supports both synchronous and asynchronous execution patterns. Requires cAlgo.API and cAlgo.API.Internals namespaces. ```csharp using cAlgo.API; using cAlgo.API.Internals; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class PositionExecutionSample : Robot { [Parameter("Direction", DefaultValue = TradeType.Buy)] public TradeType Direction { get; set; } [Parameter("Volume (Lots)", DefaultValue = 0.01)] public double VolumeInLots { get; set; } [Parameter("Stop (Pips)", DefaultValue = 10, MinValue = 0)] public double StopInPips { get; set; } [Parameter("Target (Pips)", DefaultValue = 10, MinValue = 0)] public double TargetInPips { get; set; } [Parameter("Trailing Stop", DefaultValue = false)] public bool HasTrailingStop { get; set; } [Parameter("Stop Loss Trigger Method", DefaultValue = StopTriggerMethod.Trade)] public StopTriggerMethod StopLossTriggerMethod { get; set; } [Parameter("Async", DefaultValue = false)] public bool IsAsync { get; set; } protected override void OnStart() { var volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots); var stopLoss = StopInPips == 0 ? null : (double?)StopInPips; var takeProfit = TargetInPips == 0 ? null : (double?)TargetInPips; TradeResult result = null; if (IsAsync) ExecuteMarketOrderAsync(Direction, SymbolName, volumeInUnits, "MyLabel", stopLoss, takeProfit, "Comment", HasTrailingStop, StopLossTriggerMethod, OnCompleted); else result = ExecuteMarketOrder(Direction, SymbolName, volumeInUnits, "MyLabel", stopLoss, takeProfit, "Comment", HasTrailingStop, StopLossTriggerMethod); if (!IsAsync) OnCompleted(result); } private void OnCompleted(TradeResult result) { if (!result.IsSuccessful) Print("Error: ", result.Error); Stop(); } } } ``` -------------------------------- ### Position Management in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Provides functionality to manage open positions, including finding, modifying, and closing them based on various criteria like label, comment, or symbol. It allows for complete control over the position lifecycle. Requires cAlgo.API and System.Linq namespaces. Inputs include position label and risk management parameters. ```csharp using cAlgo.API; using System.Linq; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class PositionManagementSample : Robot { [Parameter("Position Label")] public string PositionLabel { get; set; } [Parameter("Stop Loss (Pips)", DefaultValue = 10)] public double StopLossInPips { get; set; } [Parameter("Take Profit (Pips)", DefaultValue = 10)] public double TakeProfitInPips { get; set; } [Parameter("Has Trailing Stop", DefaultValue = false)] public bool HasTrailingStop { get; set; } protected override void OnStart() { // Find position by label var position = Positions.Find(PositionLabel); if (position == null) { Print("Position not found"); Stop(); return; } var positionSymbol = Symbols.GetSymbol(position.SymbolName); // Calculate stop loss and take profit prices var stopLossPrice = StopLossInPips > 0 ? (position.TradeType == TradeType.Buy ? position.EntryPrice - StopLossInPips * positionSymbol.PipSize : position.EntryPrice + StopLossInPips * positionSymbol.PipSize) : position.StopLoss; var takeProfitPrice = TakeProfitInPips > 0 ? (position.TradeType == TradeType.Buy ? position.EntryPrice + TakeProfitInPips * positionSymbol.PipSize : position.EntryPrice - TakeProfitInPips * positionSymbol.PipSize) : position.TakeProfit; // Modify position ModifyPosition(position, stopLossPrice, takeProfitPrice, HasTrailingStop, StopTriggerMethod.Trade); } } } ``` -------------------------------- ### Create Bollinger Bands Indicator with Multiple Outputs in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code implements a Bollinger Bands indicator, which calculates a moving average and its upper and lower bands based on standard deviation. It utilizes built-in indicators (`MovingAverage`, `StandardDeviation`) via the `Indicators` accessor. The `Initialize` method sets up these dependencies, and the `Calculate` method computes and outputs three data series: Main (MA), Top, and Bottom bands. Dependencies include `cAlgo.API` and `cAlgo.API.Indicators`. ```csharp using cAlgo.API; using cAlgo.API.Indicators; namespace cAlgo { [Indicator(IsOverlay = true, AutoRescale = false, AccessRights = AccessRights.None)] public class BollingerBands : Indicator { private MovingAverage _movingAverage; private StandardDeviation _standardDeviation; [Parameter] public DataSeries Source { get; set; } [Parameter(DefaultValue = 20, MinValue = 1)] public int Periods { get; set; } [Parameter("Standard Dev", DefaultValue = 2.0, MinValue = 0.0001, MaxValue = 10)] public double StandardDeviations { get; set; } [Parameter("MA Type", DefaultValue = MovingAverageType.Simple)] public MovingAverageType MAType { get; set; } [Output("Main")] public IndicatorDataSeries Main { get; set; } [Output("Top")] public IndicatorDataSeries Top { get; set; } [Output("Bottom")] public IndicatorDataSeries Bottom { get; set; } protected override void Initialize() { _movingAverage = Indicators.MovingAverage(Source, Periods, MAType); _standardDeviation = Indicators.StandardDeviation(Source, Periods, MAType); } public override void Calculate(int index) { var deviationShift = _standardDeviation.Result[index] * StandardDeviations; Main[index] = _movingAverage.Result[index]; Bottom[index] = _movingAverage.Result[index] - deviationShift; Top[index] = _movingAverage.Result[index] + deviationShift; } } } ``` -------------------------------- ### Access Market Depth (Level 2) in c# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Shows how to access and display market depth (Level 2) data, which includes bid and ask volumes at different price levels. It uses `MarketData.GetMarketDepth` and subscribes to the `Updated` event to process order book changes. The output is visualized using `IndicatorDataSeries` for bid and ask entries. ```csharp using cAlgo.API; using cAlgo.API.Internals; namespace cAlgo { [Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class MarketDepthSample : Indicator { private MarketDepth _marketDepth; [Output("Bid Entries", LineColor = "Red", PlotType = PlotType.Histogram, Thickness = 5)] public IndicatorDataSeries BidResult { get; set; } [Output("Ask Entries", LineColor = "Blue", PlotType = PlotType.Histogram, Thickness = 5)] public IndicatorDataSeries AskResult { get; set; } protected override void Initialize() { _marketDepth = MarketData.GetMarketDepth(SymbolName); _marketDepth.Updated += MarketDepth_Updated; } private void MarketDepth_Updated() { var index = Bars.ClosePrices.Count - 1; var askNo = 0; var bidNo = 0; foreach (var entry in _marketDepth.AskEntries) { AskResult[index - askNo] = (-1) * entry.VolumeInUnits; askNo++; } foreach (var entry in _marketDepth.BidEntries) { BidResult[index - bidNo] = entry.VolumeInUnits; bidNo++; } } public override void Calculate(int index) { } } } ``` -------------------------------- ### Create Simple Moving Average Indicator in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code defines a custom indicator that calculates a Simple Moving Average (SMA). It inherits from the `Indicator` base class and uses parameters for the data source, period, and shift. The `Calculate` method computes the SMA for each bar and stores it in the `Result` output series. Dependencies include the `cAlgo.API` namespace. ```csharp using cAlgo.API; namespace cAlgo { [Indicator(IsOverlay = true, AutoRescale = false, AccessRights = AccessRights.None)] public class SimpleMovingAverage : Indicator { [Parameter] public DataSeries Source { get; set; } [Parameter(DefaultValue = 14, MinValue = 1)] public int Periods { get; set; } [Parameter(DefaultValue = 0, MinValue = -1000, MaxValue = 1000)] public int Shift { get; set; } [Output("Main", LineColor = "Turquoise")] public IndicatorDataSeries Result { get; set; } public override void Calculate(int index) { var outputIndex = index + Shift; double sum = 0; var startBarIndex = index - Periods + 1; for (var i = startBarIndex; i <= index; i++) sum += Source[i]; Result[outputIndex] = sum / Periods; } } } ``` -------------------------------- ### Send Sound and Email Alerts in cTrader Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code snippet demonstrates how to send sound and email notifications based on trading conditions within cTrader. It utilizes the cAlgo API for playing sounds and sending emails. Ensure the sound file path and email addresses are correctly configured. ```csharp using cAlgo.API; namespace cAlgo { [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class NotificationsSample : Indicator { private int _lastNotifiedBarIndex; [Parameter("Sound File Path", DefaultValue = "C:\\Windows\\Media\\notify.wav")] public string SoundFilePath { get; set; } [Parameter("Sender Email")] public string SenderEmail { get; set; } [Parameter("Receiver Email")] public string ReceiverEmail { get; set; } public override void Calculate(int index) { if (!IsLastBar || _lastNotifiedBarIndex == index) return; _lastNotifiedBarIndex = index; if (Bars.Last(1).Close > Bars.Last(1).Open) Notify("Up Bar Closed"); else if (Bars.Last(1).Close < Bars.Last(1).Open) Notify("Down Bar Closed"); } private void Notify(string message) { if (!string.IsNullOrWhiteSpace(SoundFilePath)) Notifications.PlaySound(SoundFilePath); if (!string.IsNullOrWhiteSpace(SenderEmail) && !string.IsNullOrWhiteSpace(ReceiverEmail)) Notifications.SendEmail(SenderEmail, ReceiverEmail, "Notification", message); } } } ``` -------------------------------- ### Place Pending Orders with Expiry and Triggers (C#) Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code snippet demonstrates how to place various types of pending orders (Limit, Stop, Stop-Limit) in cTrader. It allows for specifying expiry times and includes parameters for distance, stop loss, and take profit. The functionality relies on the cAlgo.API namespace. ```csharp using cAlgo.API; using System; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class PendingOrderPlacingSample : Robot { [Parameter("Type", DefaultValue = PendingOrderType.Limit)] public PendingOrderType OrderType { get; set; } [Parameter("Direction", DefaultValue = TradeType.Buy)] public TradeType OrderTradeType { get; set; } [Parameter("Volume (Lots)", DefaultValue = 0.01)] public double VolumeInLots { get; set; } [Parameter("Distance (Pips)", DefaultValue = 20, MinValue = 1)] public double DistanceInPips { get; set; } [Parameter("Stop (Pips)", DefaultValue = 10)] public double StopInPips { get; set; } [Parameter("Target (Pips)", DefaultValue = 10)] public double TargetInPips { get; set; } protected override void OnStart() { var volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots); var distancePrice = DistanceInPips * Symbol.PipSize; var stopLoss = StopInPips == 0 ? null : (double?)StopInPips; var takeProfit = TargetInPips == 0 ? null : (double?)TargetInPips; var expiryTime = Server.Time.AddHours(1); switch (OrderType) { case PendingOrderType.Limit: var limitPrice = OrderTradeType == TradeType.Buy ? Symbol.Ask - distancePrice : Symbol.Ask + distancePrice; PlaceLimitOrder(OrderTradeType, SymbolName, volumeInUnits, limitPrice, "MyOrder", stopLoss, takeProfit, expiryTime); break; case PendingOrderType.Stop: var stopPrice = OrderTradeType == TradeType.Buy ? Symbol.Ask + distancePrice : Symbol.Ask - distancePrice; PlaceStopOrder(OrderTradeType, SymbolName, volumeInUnits, stopPrice, "MyOrder", stopLoss, takeProfit, expiryTime); break; case PendingOrderType.StopLimit: var stopLimitPrice = OrderTradeType == TradeType.Buy ? Symbol.Ask + distancePrice : Symbol.Ask - distancePrice; PlaceStopLimitOrder(OrderTradeType, SymbolName, volumeInUnits, stopLimitPrice, 10, "MyOrder", stopLoss, takeProfit, expiryTime); break; } } } } ``` -------------------------------- ### Add Custom TradeWatch Tab with Interactive Controls (c#) Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Extends the TradeWatch panel by adding a custom tab with interactive controls like labels and buttons. This sample utilizes the cAlgo API to create UI elements and handle user interactions, such as executing market orders when a button is clicked. It also updates a label dynamically when the active chart frame changes. ```csharp using cAlgo.API; namespace cAlgo.Plugins { [Plugin(AccessRights = AccessRights.None)] public class TradeWatchTabSample : Plugin { protected override void OnStart() { var tab = TradeWatch.AddTab("My Custom Tab"); var panel = new StackPanel { Orientation = Orientation.Vertical, HorizontalAlignment = HorizontalAlignment.Center }; var label = new TextBlock { Text = "Active Symbol Info", FontSize = 16, Margin = 10 }; panel.AddChild(label); var tradeButton = new Button { Text = "Execute Trade", Margin = 10 }; tradeButton.Click += args => { if (ChartManager.ActiveFrame is ChartFrame chartFrame) ExecuteMarketOrder(TradeType.Buy, chartFrame.Symbol.Name, 1000); }; panel.AddChild(tradeButton); tab.Child = panel; ChartManager.ActiveFrameChanged += frame => { if (ChartManager.ActiveFrame is ChartFrame chartFrame) label.Text = $"Symbol: {chartFrame.Symbol.Name}"; }; } } } ``` -------------------------------- ### Martingale Strategy with Position Events (C#) Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code snippet implements a Martingale trading strategy in cTrader, triggered by position closure events. It dynamically adjusts trade volume based on whether the previous trade was a win or a loss, doubling the quantity on losses and resetting to initial quantity on wins. Dependencies include the cAlgo.API namespace and System namespace. ```csharp using System; using cAlgo.API; namespace cAlgo { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class SampleMartingalecBot : Robot { [Parameter("Initial Quantity (Lots)", DefaultValue = 1, MinValue = 0.01)] public double InitialQuantity { get; set; } [Parameter("Stop Loss", DefaultValue = 40)] public int StopLoss { get; set; } [Parameter("Take Profit", DefaultValue = 40)] public int TakeProfit { get; set; } private readonly Random _random = new Random(); protected override void OnStart() { Positions.Closed += OnPositionsClosed; ExecuteOrder(InitialQuantity, GetRandomTradeType()); } private void ExecuteOrder(double quantity, TradeType tradeType) { var volumeInUnits = Symbol.QuantityToVolumeInUnits(quantity); var result = ExecuteMarketOrder(tradeType, SymbolName, volumeInUnits, "Martingale", StopLoss, TakeProfit); if (result.Error == ErrorCode.NoMoney) Stop(); } private void OnPositionsClosed(PositionClosedEventArgs args) { var position = args.Position; if (position.Label != "Martingale" || position.SymbolName != SymbolName) return; // Win: reset to initial quantity with random direction if (position.GrossProfit > 0) ExecuteOrder(InitialQuantity, GetRandomTradeType()); // Loss: double the quantity, same direction else ExecuteOrder(position.Quantity * 2, position.TradeType); } private TradeType GetRandomTradeType() { return _random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell; } } } ``` -------------------------------- ### Integrate WebSocket Client in cTrader Plugin Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code snippet shows how to integrate a WebSocket client within a cTrader plugin to connect to external services for real-time data. It uses the cAlgo API for WebSocket communication and UI elements. Ensure the target URI is correct and the server supports WebSocket connections. ```csharp using System; using cAlgo.API; namespace cAlgo.Plugins { [Plugin(AccessRights = AccessRights.None)] public class WebSocketSample : Plugin { private TextBlock _textBlock = new TextBlock { Text = "Starting...", FontSize = 20, FontWeight = FontWeight.ExtraBold, TextAlignment = TextAlignment.Center, Padding = new Thickness(5, 5, 5, 5), }; private static WebSocketClientOptions _webSocketClientOptions = new WebSocketClientOptions { KeepAliveInterval = new TimeSpan(0, 1, 30), UseDefaultCredentials = true, }; private WebSocketClient _webSocketClient = new WebSocketClient(_webSocketClientOptions); private readonly Uri _targetUri = new Uri("ws://example.com:8000"); protected override void OnStart() { _webSocketClient.Connect(_targetUri); _webSocketClient.Send("Hello"); _webSocketClient.TextReceived += NewsReceived; var aspBlock = Asp.SymbolTab.AddBlock("News"); aspBlock.IsExpanded = true; aspBlock.Height = 300; aspBlock.Child = _textBlock; } protected override void OnStop() { _webSocketClient.Close(WebSocketClientCloseStatus.NormalClosure); } private void NewsReceived(WebSocketClientTextReceivedEventArgs args) { if (args.Text.Length != 0) _textBlock.Text = args.Text; } } } ``` -------------------------------- ### RSI Trading Bot Implementation in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt A cTrader trading robot that uses the Relative Strength Index (RSI) indicator to generate buy and sell signals. It opens market orders when RSI is below 30 (oversold) or above 70 (overbought), and closes existing positions before opening new ones. Requires cAlgo.API and cAlgo.API.Indicators namespaces. ```csharp using cAlgo.API; using cAlgo.API.Indicators; namespace cAlgo { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None, AddIndicators = true)] public class SampleRSIcBot : Robot { [Parameter("Quantity (Lots)", Group = "Volume", DefaultValue = 1, MinValue = 0.01, Step = 0.01)] public double Quantity { get; set; } [Parameter("Source", Group = "RSI")] public DataSeries Source { get; set; } [Parameter("Periods", Group = "RSI", DefaultValue = 14)] public int Periods { get; set; } private RelativeStrengthIndex _rsi; protected override void OnStart() { _rsi = Indicators.RelativeStrengthIndex(Source, Periods); } protected override void OnTick() { // RSI below 30 = oversold, buy signal if (_rsi.Result.LastValue < 30) { Close(TradeType.Sell); Open(TradeType.Buy); } // RSI above 70 = overbought, sell signal else if (_rsi.Result.LastValue > 70) { Close(TradeType.Buy); Open(TradeType.Sell); } } private void Close(TradeType tradeType) { foreach (var position in Positions.FindAll("SampleRSI", SymbolName, tradeType)) ClosePosition(position); } private void Open(TradeType tradeType) { var position = Positions.Find("SampleRSI", SymbolName, tradeType); var volumeInUnits = Symbol.QuantityToVolumeInUnits(Quantity); if (position == null) ExecuteMarketOrder(tradeType, SymbolName, volumeInUnits, "SampleRSI"); } } } ``` -------------------------------- ### Implement Ichimoku Kinko Hyo Indicator in C# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code implements the Ichimoku Kinko Hyo indicator for cTrader. It calculates Tenkan Sen, Kijun Sen, Chikou Span, Senkou Span A, and Senkou Span B based on specified periods. The indicator requires historical price data and outputs multiple data series for visualization. ```csharp using cAlgo.API; namespace cAlgo { [Indicator(IsOverlay = true, AutoRescale = false, AccessRights = AccessRights.None)] public class IchimokuKinkoHyo : Indicator { [Parameter("Tenkan Sen Periods", DefaultValue = 9, MinValue = 1)] public int TenkanSenPeriods { get; set; } [Parameter("Kijun Sen Periods", DefaultValue = 26, MinValue = 1)] public int KijunSenPeriods { get; set; } [Parameter("Senkou Span B Periods", DefaultValue = 52, MinValue = 1)] public int SenkouSpanBPeriods { get; set; } [Output("Tenkan Sen", LineColor = "DodgerBlue")] public IndicatorDataSeries TenkanSen { get; set; } [Output("Kijun Sen", LineColor = "Crimson")] public IndicatorDataSeries KijunSen { get; set; } [Output("Chikou Span", LineColor = "MediumSpringGreen")] public IndicatorDataSeries ChikouSpan { get; set; } [Output("Senkou Span A", LineColor = "SeaGreen")] public IndicatorDataSeries SenkouSpanA { get; set; } [Output("Senkou Span B", LineColor = "Red")] public IndicatorDataSeries SenkouSpanB { get; set; } public override void Calculate(int index) { if (index < TenkanSenPeriods || index < SenkouSpanBPeriods) return; // Calculate highest high and lowest low for each period double maxFast = Bars.HighPrices[index], minFast = Bars.LowPrices[index]; double maxMedium = Bars.HighPrices[index], minMedium = Bars.LowPrices[index]; double maxSlow = Bars.HighPrices[index], minSlow = Bars.LowPrices[index]; for (var i = 0; i < TenkanSenPeriods; i++) { if (maxFast < Bars.HighPrices[index - i]) maxFast = Bars.HighPrices[index - i]; if (minFast > Bars.LowPrices[index - i]) minFast = Bars.LowPrices[index - i]; } for (var i = 0; i < KijunSenPeriods; i++) { if (maxMedium < Bars.HighPrices[index - i]) maxMedium = Bars.HighPrices[index - i]; if (minMedium > Bars.LowPrices[index - i]) minMedium = Bars.LowPrices[index - i]; } for (var i = 0; i < SenkouSpanBPeriods; i++) { if (maxSlow < Bars.HighPrices[index - i]) maxSlow = Bars.HighPrices[index - i]; if (minSlow > Bars.LowPrices[index - i]) minSlow = Bars.LowPrices[index - i]; } TenkanSen[index] = (maxFast + minFast) / 2; KijunSen[index] = (maxMedium + minMedium) / 2; ChikouSpan[index - KijunSenPeriods] = Bars.ClosePrices[index]; SenkouSpanA[index + KijunSenPeriods] = (TenkanSen[index] + KijunSen[index]) / 2; SenkouSpanB[index + KijunSenPeriods] = (maxSlow + minSlow) / 2; } } } ``` -------------------------------- ### Manage Custom Frames in cTrader Plugin Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code snippet demonstrates how to create and manage detachable custom frames within a cTrader plugin. It allows users to add and remove custom frames programmatically using the cAlgo API. The frames can contain custom UI elements. ```csharp using System.Linq; using cAlgo.API; namespace cAlgo.Plugins { [Plugin(AccessRights = AccessRights.None)] public class CustomFrameSample : Plugin { protected override void OnStart() { var aspBlock = Asp.SymbolTab.AddBlock("Custom Frame Sample"); var panel = new StackPanel(); var addButton = new Button { Text = "Add Custom Frame", Margin = 5 }; addButton.Click += args => { var customFrame = ChartManager.AddCustomFrame("Custom Frame"); customFrame.Child = new TextBlock { Text = $"Custom Frame {customFrame.Id}", FontSize = 32, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; }; panel.AddChild(addButton); var removeButton = new Button { Text = "Remove Custom Frame", Margin = 5 }; removeButton.Click += args => { var customFrame = ChartManager.OfType().FirstOrDefault(); if (customFrame != null) ChartManager.RemoveFrame(customFrame.Id); }; panel.AddChild(removeButton); aspBlock.Child = panel; } } } ``` -------------------------------- ### Draw Trend Lines on Chart in c# Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt Illustrates how to draw interactive chart objects, specifically a trend line, using the cAlgo API. The `Chart.DrawTrendLine` method is used to create the line between specified bar indices and prices. The trend line is made interactive and styled with color, thickness, and line style. ```csharp using cAlgo.API; namespace cAlgo { [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class ChartTrendLineSample : Indicator { protected override void Initialize() { var trendLine = Chart.DrawTrendLine( "trendLine", Chart.FirstVisibleBarIndex, Bars.LowPrices[Chart.FirstVisibleBarIndex], Chart.LastVisibleBarIndex, Bars.HighPrices[Chart.LastVisibleBarIndex], Color.Red, 2, LineStyle.Dots); trendLine.IsInteractive = true; } public override void Calculate(int index) { } } } ``` -------------------------------- ### Implement RSI Indicator with Levels in cAlgo (C#) Source: https://context7.com/spotware/ctrader-algo-samples/llms.txt This C# code snippet defines a custom Relative Strength Index (RSI) indicator for cTrader. It calculates RSI based on a provided data series and displays it in a separate panel with configurable periods and horizontal levels at 30 and 70. The indicator is set to display as a percentage. ```csharp using cAlgo.API; using cAlgo.API.Indicators; namespace cAlgo { [Indicator(ScalePrecision = 0, IsOverlay = false, AccessRights = AccessRights.None, IsPercentage = true)] [Levels(30, 70)] public class RelativeStrengthIndex : Indicator { [Parameter] public DataSeries Source { get; set; } [Parameter(DefaultValue = 14, MinValue = 1)] public int Periods { get; set; } [Output("Main", LineColor = "Green")] public IndicatorDataSeries Result { get; set; } private IndicatorDataSeries _gains; private IndicatorDataSeries _losses; private MovingAverage _exponentialMovingAverageGain; private MovingAverage _exponentialMovingAverageLoss; protected override void Initialize() { _gains = CreateDataSeries(); _losses = CreateDataSeries(); var emaPeriods = 2 * Periods - 1; _exponentialMovingAverageGain = Indicators.MovingAverage(_gains, emaPeriods, MovingAverageType.Exponential); _exponentialMovingAverageLoss = Indicators.MovingAverage(_losses, emaPeriods, MovingAverageType.Exponential); } public override void Calculate(int index) { var currentValue = Source[index]; var previousValue = Source[index - 1]; _gains[index] = currentValue > previousValue ? currentValue - previousValue : 0.0; _losses[index] = currentValue < previousValue ? previousValue - currentValue : 0.0; var relativeStrength = _exponentialMovingAverageGain.Result[index] / _exponentialMovingAverageLoss.Result[index]; Result[index] = 100 - 100 / (1 + relativeStrength); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.