### Find Max/Min in DataSeries Range (C#) Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt Demonstrates how to use `Maximum` and `Minimum` extension methods on cAlgo's DataSeries to find the highest high, lowest low, highest close, and lowest close within a specified lookback period. These are crucial for support/resistance analysis and determining price range positions. The example includes basic trading logic based on price proximity to support or resistance levels. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Series.Helpers; using System; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class SupportResistanceBot : Robot { [Parameter("Lookback Period", DefaultValue = 20)] public int LookbackPeriod { get; set; } protected override void OnBar() { if (Bars.Count < LookbackPeriod + 1) return; int endIndex = Bars.Count - 2; // Last completed bar int startIndex = endIndex - LookbackPeriod + 1; // Find highest high and lowest low in lookback period double highestHigh = Bars.HighPrices.Maximum(startIndex, endIndex); double lowestLow = Bars.LowPrices.Minimum(startIndex, endIndex); // Find highest close and lowest close double highestClose = Bars.ClosePrices.Maximum(startIndex, endIndex); double lowestClose = Bars.ClosePrices.Minimum(startIndex, endIndex); Print($"--- {LookbackPeriod} Bar Analysis ---"); Print($"Resistance Level: {highestHigh}"); Print($"Support Level: {lowestLow}"); Print($"Range: {(highestHigh - lowestLow) / Symbol.PipSize:F2} pips"); // Current price position double currentPrice = Bars.ClosePrices[endIndex + 1]; double rangePosition = (currentPrice - lowestLow) / (highestHigh - lowestLow) * 100; Print($"Current price is at {rangePosition:F1}% of range"); // Trading logic if (currentPrice <= lowestLow + (highestHigh - lowestLow) * 0.2) { Print("Near support - potential buy opportunity"); if (Positions.FindAll("SRBot", SymbolName).Length == 0) { double stopLoss = lowestLow - 10 * Symbol.PipSize; double takeProfit = currentPrice + (highestHigh - currentPrice); ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000, "SRBot"); } } else if (currentPrice >= highestHigh - (highestHigh - lowestLow) * 0.2) { Print("Near resistance - potential sell opportunity"); if (Positions.FindAll("SRBot", SymbolName).Length == 0) { double stopLoss = highestHigh + 10 * Symbol.PipSize; double takeProfit = currentPrice - (currentPrice - lowestLow); ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000, "SRBot"); } } } } } ``` -------------------------------- ### Analyze OhlcBar Data and Metrics in cAlgo Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt This C# code demonstrates how to utilize the OhlcBar model within cAlgo to access and analyze bar data. It initializes a RenkoBars object (though the analysis focuses on OhlcBar properties) and subscribes to its OnBar event. Inside the event handler, it prints detailed information about the bar, including its timestamp, OHLC values, volume, and automatically determined type (Bullish, Bearish, Neutral). It also calculates and prints various bar metrics such as range, body size, and wick lengths. Dependencies include cAlgo.API and its extensions. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Enums; using cAlgo.API.Extensions.Models; using cAlgo.API.Extensions.Series; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class BarAnalyzerBot : Robot { private RenkoBars _renkoBars; [Parameter("Renko Size", DefaultValue = 10)] public double RenkoSize { get; set; } protected override void OnStart() { _renkoBars = new RenkoBars(RenkoSize, Symbol, this); _renkoBars.OnBar += AnalyzeBar; } private void AnalyzeBar(object sender, OhlcBar newBar, OhlcBar oldBar) { if (oldBar == null) return; // Access bar properties Print($"Bar #{oldBar.Index}"); Print($"Time: {oldBar.Time}"); Print($"OHLC: {oldBar.Open}/{oldBar.High}/{oldBar.Low}/{oldBar.Close}"); Print($"Volume: {oldBar.Volume}"); // Bar type is automatically determined switch (oldBar.Type) { case BarType.Bullish: Print("Bullish bar detected (Close > Open)"); break; case BarType.Bearish: Print("Bearish bar detected (Close < Open)"); break; case BarType.Neutral: Print("Neutral bar detected (Close == Open)"); break; } // Calculate bar metrics double barRange = oldBar.High - oldBar.Low; double bodySize = Math.Abs(oldBar.Close - oldBar.Open); double upperWick = oldBar.High - Math.Max(oldBar.Open, oldBar.Close); double lowerWick = Math.Min(oldBar.Open, oldBar.Close) - oldBar.Low; Print($"Range: {barRange}, Body: {bodySize}, Upper Wick: {upperWick}, Lower Wick: {lowerWick}"); } } } ``` -------------------------------- ### Implement Renko Bars in cBot for Trading Source: https://github.com/spotware/calgo.api.extensions.series/blob/master/README.md This C# code demonstrates how to integrate the RenkoBars class into a cBot. It initializes Renko bars with a specified size and symbol, then handles new bar events to manage trading positions based on bar type (Bullish/Bearish). It requires the cAlgo.API.Extensions.Series library. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Enums; using cAlgo.API.Extensions.Models; using cAlgo.API.Extensions.Series; using cAlgo.API.Internals; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class RenkoBot : Robot { // Use RangeBars for Range bars private RenkoBars _renkoBars; // Rernko bar/box size in Pips [Parameter("Size (Pips)", DefaultValue = 10)] public double RankoSizeInPips { get; set; } protected override void OnStart() { // You can pass any symbol and it will create its Renko/Range bars for you _renkoBars = new RenkoBars(RankoSizeInPips, Symbol, this); _renkoBars.OnBar += RenkoBars_OnBar; } // This method is called on new Renko/Range bars, you should use this method instead of OnBar method of your Robot // The old bar is the latest completed/closed Renko/Range bar and the new bar it the current open bar private void RenkoBars_OnBar(object sender, OhlcBar newBar, OhlcBar oldBar) { var positionsToClose = Positions.FindAll("RenkoBot"); if (oldBar.Type == BarType.Bullish) { foreach (var position in positionsToClose) { if (position.TradeType == TradeType.Buy) continue; ClosePosition(position); } ExecuteMarketOrder(TradeType.Buy, Symbol.Name, 1000, "RenkoBot", 10, 20); } else if (oldBar.Type == BarType.Bearish) { foreach (var position in positionsToClose) { if (position.TradeType == TradeType.Sell) continue; ClosePosition(position); } ExecuteMarketOrder(TradeType.Sell, Symbol.Name, 1000, "RenkoBot", 10, 20); } } } } ``` -------------------------------- ### Generate Renko Bars from Tick Data - C# Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt This C# code demonstrates how to initialize and use the RenkoBars class from the cAlgo.API.Extensions.Series library. It subscribes to new Renko bar events and executes trades based on the direction of completed Renko bars. It requires the cAlgo.API and cAlgo.API.Extensions namespaces. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Enums; using cAlgo.API.Extensions.Models; using cAlgo.API.Extensions.Series; using cAlgo.API.Internals; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class RenkoTradingBot : Robot { private RenkoBars _renkoBars; [Parameter("Renko Size (Pips)", DefaultValue = 10)] public double RenkoSizeInPips { get; set; } protected override void OnStart() { // Initialize Renko bars with 10 pip box size _renkoBars = new RenkoBars(RenkoSizeInPips, Symbol, this); // Subscribe to new bar events _renkoBars.OnBar += OnRenkoBar; } private void OnRenkoBar(object sender, OhlcBar newBar, OhlcBar oldBar) { // Trade on completed Renko bars if (oldBar == null) return; Print($"New Renko Bar - Type: {oldBar.Type}, Open: {oldBar.Open}, Close: {oldBar.Close}"); if (oldBar.Type == BarType.Bullish) { // Close short positions and open long foreach (var position in Positions.FindAll("RenkoBot", SymbolName)) { if (position.TradeType == TradeType.Sell) ClosePosition(position); } ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000, "RenkoBot", 50, 100); } else if (oldBar.Type == BarType.Bearish) { // Close long positions and open short foreach (var position in Positions.FindAll("RenkoBot", SymbolName)) { if (position.TradeType == TradeType.Buy) ClosePosition(position); } ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000, "RenkoBot", 50, 100); } } protected override void OnTick() { // Renko bars are updated automatically on each tick // Access current bar data if (_renkoBars.Count > 0) { double currentClose = _renkoBars.ClosePrices.LastValue; double currentOpen = _renkoBars.OpenPrices.LastValue; } } } } ``` -------------------------------- ### Generate Range Bars and Execute Trades in cAlgo Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt This C# code demonstrates how to use the RangeBars extension to generate custom range bars. It initializes the RangeBars object with a specified range size and subscribes to the OnBar event to process new bars. Within the event handler, it analyzes the last three bars to detect uptrends or downtrends and executes market orders (buy or sell) accordingly, including stop loss and take profit levels. Dependencies include cAlgo.API and its extensions. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Enums; using cAlgo.API.Extensions.Models; using cAlgo.API.Extensions.Series; using cAlgo.API.Internals; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class RangeBarsBot : Robot { private RangeBars _rangeBars; [Parameter("Range Size (Pips)", DefaultValue = 15)] public double RangeSizeInPips { get; set; } [Parameter("Stop Loss (Pips)", DefaultValue = 30)] public double StopLossPips { get; set; } [Parameter("Take Profit (Pips)", DefaultValue = 60)] public double TakeProfitPips { get; set; } protected override void OnStart() { // Initialize Range bars with 15 pip range _rangeBars = new RangeBars(RangeSizeInPips, Symbol, this); _rangeBars.OnBar += OnRangeBar; Print($"Range Bars initialized with {RangeSizeInPips} pips range"); } private void OnRangeBar(object sender, OhlcBar newBar, OhlcBar oldBar) { if (oldBar == null || _rangeBars.Count < 3) return; // Analyze last 3 bars for trend var bar1 = _rangeBars.GetBar(_rangeBars.Index - 2); var bar2 = _rangeBars.GetBar(_rangeBars.Index - 1); var bar3 = oldBar; bool uptrend = bar1.Type == BarType.Bullish && bar2.Type == BarType.Bullish && bar3.Type == BarType.Bullish; bool downtrend = bar1.Type == BarType.Bearish && bar2.Type == BarType.Bearish && bar3.Type == BarType.Bearish; if (uptrend && Positions.FindAll("RangeBarsBot", SymbolName, TradeType.Buy).Length == 0) { ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000, "RangeBarsBot", StopLossPips, TakeProfitPips); Print($"Buy signal at {oldBar.Close}"); } else if (downtrend && Positions.FindAll("RangeBarsBot", SymbolName, TradeType.Sell).Length == 0) { ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000, "RangeBarsBot", StopLossPips, TakeProfitPips); Print($"Sell signal at {oldBar.Close}"); } } } } ``` -------------------------------- ### Retrieve Bar Object and Detect Patterns using c# Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt This C# code snippet demonstrates how to retrieve specific OhlcBar objects using Bars.GetBar and then checks for common candlestick patterns such as Bullish Engulfing, Bearish Engulfing, and Three White Soldiers. It includes logic to print detected patterns and execute market orders based on the Bullish/Bearish Engulfing patterns. Dependencies include cAlgo.API and related extensions. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Models; using cAlgo.API.Extensions.Series.Helpers; using cAlgo.API.Extensions.Enums; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class MultiBarPattern : Robot { protected override void OnBar() { if (Bars.Count < 4) return; // Get last 3 completed bars OhlcBar bar1 = Bars.GetBar(Bars.Count - 4); OhlcBar bar2 = Bars.GetBar(Bars.Count - 3); OhlcBar bar3 = Bars.GetBar(Bars.Count - 2); // Check for bullish engulfing pattern if (bar2.Type == BarType.Bearish && bar3.Type == BarType.Bullish) { bool engulfs = bar3.Open < bar2.Close && bar3.Close > bar2.Open; if (engulfs) { Print("Bullish Engulfing Pattern detected!"); Print($"Bar 2: O={bar2.Open}, C={bar2.Close}"); Print($"Bar 3: O={bar3.Open}, C={bar3.Close}"); // Execute buy order ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000, "Engulfing", 20, 40); } } // Check for bearish engulfing pattern if (bar2.Type == BarType.Bullish && bar3.Type == BarType.Bearish) { bool engulfs = bar3.Open > bar2.Close && bar3.Close < bar2.Open; if (engulfs) { Print("Bearish Engulfing Pattern detected!"); Print($"Bar 2: O={bar2.Open}, C={bar2.Close}"); Print($"Bar 3: O={bar3.Open}, C={bar3.Close}"); // Execute sell order ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000, "Engulfing", 20, 40); } } // Check for three white soldiers (bullish continuation) if (bar1.Type == BarType.Bullish && bar2.Type == BarType.Bullish && bar3.Type == BarType.Bullish && bar2.Close > bar1.Close && bar3.Close > bar2.Close) { Print("Three White Soldiers pattern - strong uptrend"); } } } } ``` -------------------------------- ### Calculate Heiken Ashi Bars - c# Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt Demonstrates the calculation of Heiken Ashi bars using the IndicatorBars.CalculateHeikenAshi method. It shows how to apply optional moving average smoothing based on user-defined parameters for MA period and type. The snippet also includes logic for trend and reversal detection using the calculated Heiken Ashi bars. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Series; using cAlgo.API.Extensions.Series.Helpers; using cAlgo.API.Extensions.Enums; using cAlgo.API.Indicators; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class HeikenAshiBot : Robot { private IndicatorBars _heikenAshiBars; [Parameter("Use MA Smoothing", DefaultValue = false)] public bool UseMASmoothing { get; set; } [Parameter("MA Period", DefaultValue = 5)] public int MAPeriod { get; set; } [Parameter("MA Type", DefaultValue = MovingAverageType.Simple)] public MovingAverageType MAType { get; set; } protected override void OnStart() { _heikenAshiBars = new IndicatorBars(TimeFrame, SymbolName, this); // Calculate Heiken Ashi for historical bars for (int i = 0; i < Bars.Count; i++) { if (UseMASmoothing && i > MAPeriod) { _heikenAshiBars.CalculateHeikenAshi(Bars, i, MAPeriod, MAType); } else { _heikenAshiBars.CalculateHeikenAshi(Bars, i); } } } protected override void OnBar() { int index = Bars.Count - 1; // Update Heiken Ashi if (UseMASmoothing && index > MAPeriod) { _heikenAshiBars.CalculateHeikenAshi(Bars, index, MAPeriod, MAType); } else { _heikenAshiBars.CalculateHeikenAshi(Bars, index); } if (_heikenAshiBars.Count < 3) return; // Get Heiken Ashi bars var currentBar = _heikenAshiBars.GetBar(_heikenAshiBars.Index); var previousBar = _heikenAshiBars.GetBar(_heikenAshiBars.Index - 1); // Heiken Ashi trend detection bool strongUptrend = currentBar.Type == BarType.Bullish && previousBar.Type == BarType.Bullish && currentBar.Low == currentBar.Open; // No lower wick bool strongDowntrend = currentBar.Type == BarType.Bearish && previousBar.Type == BarType.Bearish && currentBar.High == currentBar.Open; // No upper wick // Trend reversal detection bool bullishReversal = previousBar.Type == BarType.Bearish && currentBar.Type == BarType.Bullish; bool bearishReversal = previousBar.Type == BarType.Bullish && currentBar.Type == BarType.Bearish; if (strongUptrend) { Print("Strong uptrend - hold long positions"); } else if (strongDowntrend) { Print("Strong downtrend - hold short positions"); } else if (bullishReversal) { Print("Bullish reversal detected"); ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000, "HABot", 30, 60); } else if (bearishReversal) { Print("Bearish reversal detected"); ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000, "HABot", 30, 60); } } } } ``` -------------------------------- ### Calculate Bar Range with MarketSeriesExtensions.GetBarRange in C# Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt Calculates the range of a bar, either as the total high-low spread or the open-close body size. This method, found in cAlgo.API.Extensions.Series.Helpers, is useful for volatility analysis. It takes an index and an optional boolean `useBarBody` as input. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Series.Helpers; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class VolatilityFilter : Robot { [Parameter("Min Range (Pips)", DefaultValue = 5)] public double MinRangePips { get; set; } [Parameter("Max Range (Pips)", DefaultValue = 50)] public double MaxRangePips { get; set; } protected override void OnBar() { int index = Bars.Count - 2; // Previous completed bar // Get full bar range (high to low) double fullRange = Bars.GetBarRange(index, useBarBody: false); double fullRangePips = fullRange / Symbol.PipSize; // Get bar body size (open to close) double bodyRange = Bars.GetBarRange(index, useBarBody: true); double bodyRangePips = bodyRange / Symbol.PipSize; Print($"Bar {index}: Full Range = {fullRangePips:F2} pips, Body = {bodyRangePips:F2} pips"); // Filter based on volatility if (fullRangePips < MinRangePips) { Print("Low volatility - skipping trade"); return; } if (fullRangePips > MaxRangePips) { Print("High volatility - skipping trade"); return; } // Calculate wick sizes double upperWick = Bars.HighPrices[index] - Math.Max(Bars.OpenPrices[index], Bars.ClosePrices[index]); double lowerWick = Math.Min(Bars.OpenPrices[index], Bars.ClosePrices[index]) - Bars.LowPrices[index]; double upperWickPips = upperWick / Symbol.PipSize; double lowerWickPips = lowerWick / Symbol.PipSize; // Doji pattern: small body with large wicks if (bodyRangePips < 2 && (upperWickPips > 10 || lowerWickPips > 10)) { Print("Doji pattern detected - potential reversal"); } // Strong trend bar: large body, small wicks if (bodyRangePips > fullRangePips * 0.8) { Print("Strong trend bar - continuation signal"); } } } } ``` -------------------------------- ### Detect Bar Type with MarketSeriesExtensions.GetBarType in C# Source: https://context7.com/spotware/calgo.api.extensions.series/llms.txt Determines if a bar is bullish, bearish, or neutral based on its open and close prices. This method is part of the cAlgo.API.Extensions.Series.Helpers namespace and can be used with any Bars object. It returns a BarType enum value. ```csharp using cAlgo.API; using cAlgo.API.Extensions.Enums; using cAlgo.API.Extensions.Series.Helpers; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class BarTypeAnalyzer : Robot { protected override void OnBar() { // Get bar type for current and previous bars BarType currentBarType = Bars.GetBarType(Bars.Count - 1); BarType previousBarType = Bars.GetBarType(Bars.Count - 2); Print($"Current bar: {currentBarType}"); Print($"Previous bar: {previousBarType}"); // Count consecutive bullish/bearish bars int consecutiveBullish = 0; int consecutiveBearish = 0; for (int i = Bars.Count - 1; i >= Math.Max(0, Bars.Count - 10); i--) { BarType barType = Bars.GetBarType(i); if (barType == BarType.Bullish) { consecutiveBullish++; consecutiveBearish = 0; } else if (barType == BarType.Bearish) { consecutiveBearish++; consecutiveBullish = 0; } else { break; } } if (consecutiveBullish >= 3) { Print($"Strong uptrend: {consecutiveBullish} consecutive bullish bars"); } else if (consecutiveBearish >= 3) { Print($"Strong downtrend: {consecutiveBearish} consecutive bearish bars"); } } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.