Topics
Replies
vamsi.rc
11 Aug 2020, 16:16
( Updated at: 21 Dec 2023, 09:22 )
RE: RE:
This is the exact issue which I am referring to.
1. Indicator applied on cBot - Before Reapply Indicator:
2. Indicator applied on cBot - After Reapply Indicator:
3. Indicator applied on Chart Window:
If you observe above 3 screenshots, Last Signal Index is same in all three, but difference in plotting signals, in chart no.1 it plots somewhere which is not related to either 2 or 3. I am considering the signal arrows which is creating the problem while placing orders.
Hope this help to understand the exact issue. Kindly let me know, if you need more information.
Thanks
R C Vamsi Vardhan
vamsi.rc said:
Same Indicator and cBot as mentioned here. I am working and referring to this same Indicator and cBot.
PanagiotisCharalampous said:
Hi Vamsi,
Can you share the source code of this indicator?
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
04 Aug 2020, 12:03
( Updated at: 21 Dec 2023, 09:22 )
RE:
If I use it as Output Parameter, it plots the data series on chart. Then the chart looks like this.
In this case, I should use 2 Indicators one for display and another for cBot. Let me try this.
PanagiotisCharalampous said:
Hi Vamsi,
To get rid of the exception, you need to change
//[Output("Signal")] public IndicatorDataSeries SignalsData; //[Output("Signal Index")] public IndicatorDataSeries SignalsIndexData;
to
[Output("Signal")] public IndicatorDataSeries SignalsData { get; set; } [Output("Signal Index")] public IndicatorDataSeries SignalsIndexData { get; set; }
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
04 Aug 2020, 10:59
RE:
Complete Build and Code available in this below link.
https://drive.google.com/drive/folders/1av4y9hrZbepsJhJ5LUQoUw-oj6ZyvuEd?usp=sharing
INDICATOR CODE:
using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
using System.Data.SqlClient;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
public class STRSSignalsv2 : Indicator
{
#region "Declarations"
[Parameter("Display Arrow Signal", DefaultValue = true)]
public bool DisplayArrowSignal { get; set; }
[Parameter("Opp Signal Validate", DefaultValue = true)]
public bool OppSignalValidation { get; set; }
[Parameter("Arrow Spacing from Line", DefaultValue = 3)]
public int ArrowSpacing { get; set; }
[Parameter("RSI Period", DefaultValue = 14)]
public int RSIPeriod { get; set; }
public string upArrow = "▲";
public string downArrow = "▼";
public bool bullishArrowDrawn = false;
public bool bearishArrowDrawn = false;
public int SignalIndex;
public RelativeStrengthIndex rsi;
public bool RSIBullish = false, RSIBearish = false;
public bool IsBullish, IsBearish;
public DateTime lastsignaltime;
public string signal;
public string signalstatus;
public int signalBackPeriods;
#endregion
//[Output("Signal")]
public IndicatorDataSeries SignalsData;
//[Output("Signal Index")]
public IndicatorDataSeries SignalsIndexData;
protected override void Initialize()
{
#region "Initilization"
rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, RSIPeriod);
#endregion
}
public override void Calculate(int index)
{
int s = 0;
IsBullish = false;
IsBearish = false;
int period = 1;
#region "Logic"
RSIBullish = rsi.Result.HasCrossedAbove(10, period) || /*rsi.Result.HasCrossedAbove(20, period) ||*/rsi.Result.HasCrossedAbove(30, period) || /*rsi.Result.HasCrossedAbove(40, period) ||*/ /*rsi.Result.HasCrossedAbove(50, period) ||*/ /*rsi.Result.HasCrossedAbove(60, period) ||*/rsi.Result.HasCrossedAbove(70, period) || /*rsi.Result.HasCrossedAbove(80, period) ||*/ /*|| rsi.Result.HasCrossedAbove(100, period)*/rsi.Result.HasCrossedAbove(90, period);
RSIBearish = rsi.Result.HasCrossedBelow(10, period) || /*rsi.Result.HasCrossedBelow(20, period) ||*/rsi.Result.HasCrossedBelow(30, period) || /*rsi.Result.HasCrossedBelow(40, period) ||*/ /*rsi.Result.HasCrossedBelow(50, period) ||*/ /*rsi.Result.HasCrossedBelow(60, period) ||*/rsi.Result.HasCrossedBelow(70, period) || /*rsi.Result.HasCrossedBelow(80, period) ||*/ /*|| rsi.Result.HasCrossedBelow(100, period)*/rsi.Result.HasCrossedBelow(90, period);
IsBullish = RSIBullish;
IsBearish = RSIBearish;
#endregion
if (IsBullish)
{
SignalIndex = index;
DisplayArrows(index, "Buy");
lastsignaltime = Bars.OpenTimes.Last(SignalIndex);
signal = "Buy";
SignalsData[index] = 1;
SignalsIndexData[index] = index;
}
if (IsBearish)
{
SignalIndex = index;
DisplayArrows(index, "Sell");
lastsignaltime = Bars.OpenTimes.Last(SignalIndex);
signal = "Sell";
SignalsData[index] = 2;
SignalsIndexData[index] = index;
}
if (SignalIndex == index)
{
signalstatus = "Running";
}
if (SignalIndex < index)
{
signalstatus = "Confirmed";
signalBackPeriods = index - SignalIndex;
}
Chart.DrawStaticText("LastSignalTime", SetNewLine(s) + "Last Signal Time \t: " + "\t" + lastsignaltime.ToString("yyyy-MM-dd HH:mm:ss"), VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
s = s + 1;
Chart.DrawStaticText("LastSignalIndex", SetNewLine(s) + "Last Signal Index \t: " + "\t" + SignalIndex + " Current Index : " + index, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
s = s + 1;
Chart.DrawStaticText("LastSignal", SetNewLine(s) + "Last Signal \t: " + "\t" + signal, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
s = s + 1;
Chart.DrawStaticText("TimeFrame", SetNewLine(s) + "Time Frame \t: " + "\t" + Chart.TimeFrame, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
s = s + 1;
Chart.DrawStaticText("SignalStatus", SetNewLine(s) + "Signal Status \t: " + "\t" + signalstatus, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
s = s + 1;
Chart.DrawStaticText("SignalBackPeriodsCount", SetNewLine(s) + "Periods Ago \t: " + "\t" + signalBackPeriods, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
}
public string SetNewLine(int count)
{
string _newline = "";
int i = 0;
while (i < count)
{
_newline = _newline + Environment.NewLine;
i++;
}
return _newline;
}
public void DisplayArrows(int index, string signal)
{
int idx;
if (DisplayArrowSignal)
{
if (signal == "Buy")
{
if (OppSignalValidation)
{
if (!bullishArrowDrawn)
{
idx = index;
// _breakoutCandleIndexBuy;
double y = Bars.LowPrices.Last(0) - (Symbol.PipSize * ArrowSpacing);
string TextName = string.Format("BuySignal {0}", idx);
ChartObjects.DrawText(TextName, upArrow, idx, y, VerticalAlignment.Top, HorizontalAlignment.Center, Colors.Green);
bullishArrowDrawn = true;
bearishArrowDrawn = false;
}
}
else
{
idx = index;
// _breakoutCandleIndexBuy;
double y = Bars.LowPrices.Last(0) - (Symbol.PipSize * ArrowSpacing);
string TextName = string.Format("BuySignal {0}", idx);
ChartObjects.DrawText(TextName, upArrow, idx, y, VerticalAlignment.Top, HorizontalAlignment.Center, Colors.Green);
bullishArrowDrawn = true;
bearishArrowDrawn = false;
}
}
else if (signal == "Sell")
{
if (OppSignalValidation)
{
if (!bearishArrowDrawn)
{
idx = index;
// _breakoutCandleIndexSell;
double y = Bars.HighPrices.Last(0) + (Symbol.PipSize * ArrowSpacing);
string TextName = string.Format("SellSignal {0}", idx);
ChartObjects.DrawText(TextName, downArrow, idx, y, VerticalAlignment.Bottom, HorizontalAlignment.Center, Colors.Red);
bearishArrowDrawn = true;
bullishArrowDrawn = false;
}
}
else
{
idx = index;
// _breakoutCandleIndexSell;
double y = Bars.HighPrices.Last(0) + (Symbol.PipSize * ArrowSpacing);
string TextName = string.Format("SellSignal {0}", idx);
ChartObjects.DrawText(TextName, downArrow, idx, y, VerticalAlignment.Bottom, HorizontalAlignment.Center, Colors.Red);
bearishArrowDrawn = true;
bullishArrowDrawn = false;
}
}
}
}
}
}
cBot:
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class STRSSignalsBotv2 : Robot
{
#region "Parameters"
[Parameter("Allow Trading", DefaultValue = true, Group = "Trading")]
public bool AllowTrading { get; set; }
[Parameter("LotSize", DefaultValue = 0.01, Group = "Trading")]
public double Quantity { get; set; }
[Parameter("Label", DefaultValue = "RTBv1", Group = "Trading")]
public string BandsLabel { get; set; }
[Parameter("Order Expire Minutes", DefaultValue = 0, Group = "Trading")]
public int OrderExpireMinutes { get; set; }
[Parameter("Double Lot Size On Loss", DefaultValue = false, Group = "Trading")]
public bool DoubleLotSize { get; set; }
[Parameter("Max Double Lot Size", DefaultValue = 0.04, Group = "Trading")]
public double MaxDoubleQuantity { get; set; }
[Parameter("Allow Order Expire", DefaultValue = false, Group = "Trading")]
public bool OrderExpire { get; set; }
[Parameter("Allow Opp Position Close", DefaultValue = true, Group = "Trading")]
public bool AllowOppPosClose { get; set; }
[Parameter("Allow Opp Pending Orders Cancel", DefaultValue = true, Group = "Trading")]
public bool AllowOppPendingOrdersCancelled { get; set; }
[Parameter("Allow Limit Orders", DefaultValue = true, Group = "Trading")]
public bool AllowLimitOrders { get; set; }
[Parameter("Allow Target In Pips", DefaultValue = true, Group = "Profit")]
public bool AllowPipsTarget { get; set; }
[Parameter("Target In Pips", DefaultValue = 10, Group = "Profit")]
public int TargetPips { get; set; }
[Parameter("Allow StopLoss", DefaultValue = false, Group = "StopLoss")]
public bool AllowStopLoss { get; set; }
[Parameter("Allow Target", DefaultValue = false, Group = "Profit")]
public bool AllowTarget { get; set; }
[Parameter("RSI Period", DefaultValue = 14)]
public int RSIPeriod { get; set; }
#endregion
public STRSSignalsv2 strssignals;
protected override void OnStart()
{
strssignals = Indicators.GetIndicator<STRSSignalsv2>(false, false, 3, 4);
// Subscribe to the positions opened event.
Positions.Opened += PositionsOnOpened;
// Subscribe to the positions closed event.
//Positions.Closed += PositionsOnClosed;
//// Subscribe to the positions modified event.
//Positions.Modified += OnPositionsModified;
//// Subscribe to the pending order created event.
//PendingOrders.Created += OnPendingOrdersCreated;
//// Subscribe to the pending order modified event.
//PendingOrders.Modified += OnPendingOrdersModified;
//// Subscribe to the pending order cancelled event.
//PendingOrders.Cancelled += OnPendingOrdersCancelled;
}
protected override void OnTick()
{
// Put your core logic here
}
bool IsBullish, IsBearish;
protected override void OnBar()
{
try
{
string signal = strssignals.SignalsData.Last(1).ToString();
string signalindex = strssignals.SignalsIndexData.Last(1).ToString();
Print(signal + " - " + signalindex);
} catch (Exception ex)
{
Print(ex.Message + " - OB001");
}
//try
//{
// if (IsBullish == true)
// {
// if (AllowTrading)
// {
// ClosePositions(TradeType.Buy, SymbolName.ToString());
// PlaceOrder(TradeType.Buy, Bars.HighPrices.Last(1), SymbolName, "RB - " + Chart.TimeFrame + " - " + Convert.ToDateTime(Bars.OpenTimes.Last(0)).ToString("yyyy-MM-dd HH:mm:ss"), TargetPips, 0, Symbol.PipSize);
// }
// }
// if (IsBearish == true)
// {
// if (AllowTrading)
// {
// ClosePositions(TradeType.Sell, SymbolName.ToString());
// PlaceOrder(TradeType.Sell, Bars.LowPrices.Last(1), SymbolName, "RS - " + Chart.TimeFrame + " - " + Convert.ToDateTime(Bars.OpenTimes.Last(0)).ToString("yyyy-MM-dd HH:mm:ss"), 0, Symbol.PipSize);
// }
// }
//}
//catch (Exception ex)
//{
// Print(ex.Message + " - PO002");
//}
}
private void ClosePositions(TradeType tradeType, string symbol)
{
if (AllowOppPosClose)
{
if (tradeType == TradeType.Buy)
{
var possell = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbol).Where(pos => pos.TradeType == TradeType.Sell);
//if (possell.Count() > 0)
//{
foreach (Position sellpos in possell)
{
ClosePosition(possell.First());
}
//}
}
if (tradeType == TradeType.Sell)
{
var posbuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbol).Where(pos => pos.TradeType == TradeType.Buy);
//if (posbuy.Count() > 0)
//{
foreach (Position buypos in posbuy)
{
ClosePosition(posbuy.First());
}
//}
}
}
}
private void PlaceOrder(TradeType ttype, double entryPrice, string symbolName, string commentSuffix, double takeProfit = 0, double stopLoss = 0, double pipsize = 0)
{
int buyposcount = 0, sellposcount = 0;
//, buyordcount = 0, sellordcount = 0;
double Qty;
Qty = Quantity;
try
{
if (!(AllowStopLoss))
{
stopLoss = 0;
}
//if (AllowStopLoss)
//{
// stopLoss = Math.Abs((entryPrice - stopLoss) / pipsize);
//}
if (!(AllowTarget))
{
takeProfit = 0;
}
if (AllowPipsTarget)
{
if (takeProfit == 0)
{
takeProfit = TargetPips;
}
}
//if (AllowPipsStopLoss)
//{
// if (stopLoss == 0)
// {
// stopLoss = StoplossPips;
// }
//}
//// Lot Optimization
if (History.Where(his => his.SymbolName == SymbolName).Where(his => his.Label == BandsLabel).Count() > 0)
{
var prevtrade = History.Where(his => his.SymbolName == SymbolName).Where(his => his.Label == BandsLabel).Last();
//Print(prevtrade.PositionId + " - " + prevtrade.TradeType + " - " + prevtrade.EntryTime + " - " + prevtrade.Quantity + " - " + prevtrade.ClosingTime + " - " + prevtrade.NetProfit);
if (DoubleLotSize)
{
if (prevtrade.NetProfit < 0)
{
if (prevtrade.Quantity < MaxDoubleQuantity)
{
Qty = prevtrade.Quantity * 2;
}
if (prevtrade.Quantity == MaxDoubleQuantity)
{
Qty = MaxDoubleQuantity;
takeProfit = 0;
}
}
}
}
var volumeInUnits = Symbol.QuantityToVolumeInUnits(Qty);
DateTime OrderExpire = Server.Time.AddMinutes(OrderExpireMinutes);
try
{
if (ttype == TradeType.Buy)
{
var pendingOrders = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Buy);
foreach (PendingOrder o in pendingOrders)
{
o.Cancel();
}
// Finding if any open positions with same signal
buyposcount = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Buy).Count();
//< MaxOpenPosPerSymbol)
if (buyposcount == 0)
{
if (AllowLimitOrders)
{
if (entryPrice <= Bars.ClosePrices.LastValue)
{
if (OrderExpireMinutes > 0)
{
var result = PlaceLimitOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
}
if (OrderExpireMinutes == 0)
{
var result = PlaceLimitOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
}
}
else if (entryPrice >= Bars.ClosePrices.LastValue)
{
if (OrderExpireMinutes > 0)
{
var result = PlaceStopOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
}
if (OrderExpireMinutes == 0)
{
var result = PlaceStopOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
}
}
}
else
{
var result = ExecuteMarketOrder(TradeType.Buy, symbolName, volumeInUnits, BandsLabel, stopLoss, takeProfit, "Market - " + commentSuffix, false);
}
}
}
if (ttype == TradeType.Sell)
{
// Finding and Cancelling any old same signal pending orders
var pendingOrdersSell = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Sell);
foreach (PendingOrder o in pendingOrdersSell)
{
o.Cancel();
}
// Finding if any open positions with same signal
sellposcount = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Sell).Count();
// < MaxOpenPosPerSymbol)
if (sellposcount == 0)
{
if (AllowLimitOrders)
{
if (entryPrice <= Bars.ClosePrices.LastValue)
{
if (OrderExpireMinutes > 0)
{
var result = PlaceStopOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
}
if (OrderExpireMinutes == 0)
{
var result = PlaceStopOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
}
}
else if (entryPrice >= Bars.ClosePrices.LastValue)
{
if (OrderExpireMinutes > 0)
{
var result = PlaceLimitOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
}
if (OrderExpireMinutes == 0)
{
var result = PlaceLimitOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
}
}
}
else
{
var result = ExecuteMarketOrder(TradeType.Sell, symbolName, volumeInUnits, BandsLabel, stopLoss, takeProfit, "Market - " + commentSuffix, false);
}
}
}
} catch (Exception ex)
{
Print(ex.Message + " - PO001");
}
} catch (Exception ex)
{
Print(ex.Message + " - POM001");
}
}
#region "Order Events"
private void PositionsOnOpened(PositionOpenedEventArgs args)
{
var apos = args.Position;
//Print("Position opened at {0}", pos.EntryPrice);
//if (AllowOppPosClose)
//{
// if (apos.TradeType == TradeType.Buy)
// {
// var possell = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == apos.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);
// //if (possell.Count() > 0)
// //{
// foreach (Position sellpos in possell)
// {
// ClosePosition(possell.First());
// }
// //}
// }
// if (apos.TradeType == TradeType.Sell)
// {
// var posbuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == apos.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);
// //if (posbuy.Count() > 0)
// //{
// foreach (Position buypos in posbuy)
// {
// ClosePosition(posbuy.First());
// }
// //}
// }
//}
//TrailStopLoss(TrailStoplossIndex, "Position", apos);
}
private void PositionsOnClosed(PositionClosedEventArgs args)
{
// the reason for closing can be captured.
switch (args.Reason)
{
case PositionCloseReason.StopLoss:
Print("Position closed as stop loss was hit");
break;
case PositionCloseReason.StopOut:
Print("Position closed as it was stopped out");
break;
case PositionCloseReason.TakeProfit:
Print("Position closed as take profit was hit");
//if (args.Position.TradeType == TradeType.Buy)
//{
// var pendingOrdersSell = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);
// foreach (PendingOrder o in pendingOrdersSell)
// {
// o.Cancel();
// }
// var positionsSell = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);
// foreach (Position o in positionsSell)
// {
// o.Close();
// }
//}
//if (args.Position.TradeType == TradeType.Sell)
//{
// var pendingOrdersBuy = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);
// foreach (PendingOrder o in pendingOrdersBuy)
// {
// o.Cancel();
// }
// var positionsBuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);
// foreach (Position o in positionsBuy)
// {
// o.Close();
// }
//}
break;
}
}
private void OnPositionsModified(PositionModifiedEventArgs args)
{
var pos = args.Position;
//Print("Position modified with a new stop loss of {0} pips", pos.ModifyStopLossPips);
}
private void OnPendingOrdersCreated(PendingOrderCreatedEventArgs obj)
{
var order = obj.PendingOrder;
if (AllowOppPendingOrdersCancelled)
{
if (order.TradeType == TradeType.Buy)
{
var pendingOrdersSell = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == order.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);
foreach (PendingOrder o in pendingOrdersSell)
{
o.Cancel();
}
}
if (order.TradeType == TradeType.Sell)
{
var pendingOrdersBuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == order.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);
foreach (PendingOrder o in pendingOrdersBuy)
{
o.Cancel();
}
}
}
//Print(" A {0} Pending order has been created.", order.OrderType);
}
private void OnPendingOrdersModified(PendingOrderModifiedEventArgs obj)
{
var order = obj.PendingOrder;
//Print("Pending order modified with a new target price of {0}", order.ModifyTargetPrice);
}
private void OnPendingOrdersCancelled(PendingOrderCancelledEventArgs obj)
{
switch (obj.Reason)
{
case PendingOrderCancellationReason.Cancelled:
Print("Pending order was cancelled");
break;
case PendingOrderCancellationReason.Expired:
Print("Pending order has expired");
break;
case PendingOrderCancellationReason.Rejected:
Print("Pending order was rejected");
break;
}
}
#endregion
}
}
PanagiotisCharalampous said:
Hi Vamsi,
I cannot build this indicator. Can you please provide the actual working indicator and cBot?
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
04 Aug 2020, 09:10
RE:
Thanks for your reply.
It looks like Cache issue in the system. I restarted and the issue resolved. Will come back to you if it persists again.
Thanks
R C Vamsi Vardhan
PanagiotisCharalampous said:
Hi vamsi.rc,
Can you please send us some troubleshooting information (Ctrl+Alt+Shift+T) and paste the link to this discussion in the description?
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
27 May 2020, 09:18
( Updated at: 21 Dec 2023, 09:22 )
RE:
Let me explain more
I want to plot Horizontal Lines for High and Low of last N Periods. I got the code snippet from below.
I want to plot lines like this. Above screenshot is for Daily High and Low.
using System; using cAlgo.API; namespace cAlgo.Indicators { [Indicator(IsOverlay = true)] public class DailyHighLow : Indicator { public override void Calculate(int index) { DateTime today = MarketSeries.OpenTime[index].Date; DateTime tomorrow = today.AddDays(1); double high = MarketSeries.High.LastValue; double low = MarketSeries.Low.LastValue; for (int i = MarketSeries.Close.Count - 1; i > 0; i--) { if (MarketSeries.OpenTime[i].Date < today) break; high = Math.Max(high, MarketSeries.High[i]); low = Math.Min(low, MarketSeries.Low[i]); } ChartObjects.DrawLine("high " + today, today, high, tomorrow, high, Colors.Pink); ChartObjects.DrawLine("low " + today, today, low, tomorrow, low, Colors.Pink); } } }
This is the code for above screenshot. But I want to plot High and Low for last 10 periods.
PanagiotisCharalampous said:
Hi Vamsi,
It is not clear what you are asking for. What lines do you want to plot? Could you post an example? What did you modify, what does it do and what should it be doing instead? What should this snippet do?
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
21 May 2020, 10:31
RE:
Thanks for your reply Panagiotis.
I am trying to code as below in cBot. Kindly help.
private IndicatorDataSeries maCalc;
private MovingAverage ma20, ma50, ma200;
protected override void OnStart()
{
// Put your initialization logic here
ma2 = Indicators.SimpleMovingAverage(Bars.ClosePrices, Periods2);
ma5 = Indicators.SimpleMovingAverage(Bars.ClosePrices, Periods5);
ma10 = Indicators.SimpleMovingAverage(Bars.ClosePrices, Periods10);
maCalc = (ma2.Result.LastValue + ma5.Result.LastValue + ma10.Result.LastValue) / 3;
}
Now I am looking for the crossover candle for this maCalc line as explained below.
if(Bars.OpenPrices < maCalc && Bars.ClosePrices > maCalc && Bars.HighPrices > maCalc && Bars.LowPrices < maCalc) (This is one condition of candle CrossOver).
{
_signalCandleIndex = Bars.ClosePrices.Count - 1;
_hasCrossedAbove = true;
}
From this I can get the CrossOver Candle index to proceed further. (But i am not succeed by trying this way)
Later, I need to find out the Breakout of that signal candle High or Low based on TradeType.
if (_hasCrossedAbove && Bars.HighPrices.Last(1) > Bars.HighPrices[_signalCandleIndex])
{
// If last bar high is above the signal bar high, we record the breakout index
_breakoutCandleIndex = _singalCandleIndex = Bars.ClosePrices.Count - 2;
//Print("Breakout Candle Index: " + _breakoutCandleIndex);
}
Once breakout candle close, I need to take position either on High or Low.
If (Bars.ClosePrices[0] > Bars.HighPrices.Last(_breakoutCandleIndex))
{
ExecuteMarketOrder();
}
To achieve this, I am spending hours of time to complete this task, lack of programming experience in cAlgo especially and unable to get desired result.
I request you for your help to complete this task. Kindly help.
Thanks
R C Vamsi Vardhan
PanagiotisCharalampous said:
Hi Vamsi,
Moving averages have a Result property which is a DataSeries that contains the values of the indicator. You will need to add these values individually e.g.
maCalc = (ma2.Result.LastValue + ma5.Result.LastValue + ma10.Result.LastValue) / 3;
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
21 May 2020, 08:09
RE: RE:
Hi Panagiotis,
Is there any way to add 2 moving averages?
I tried this.
protected override void OnStart()
{
// Put your initialization logic here
ma2 = Indicators.SimpleMovingAverage(Bars.ClosePrices, Periods2);
ma5 = Indicators.SimpleMovingAverage(Bars.ClosePrices, Periods5);
ma10 = Indicators.SimpleMovingAverage(Bars.ClosePrices, Periods10);
maCalc = (ma2 + ma5 + ma10) / 3;
}
Here I am getting error:
Operator '+' cannot be applied to operands of type 'MovingAverage' and 'MovingAverage'.
How to achieve this functionality?
vamsi.rc said:
Thank you very much Panagiotis. Let me try this.
PanagiotisCharalampous said:
Hi Vamsi,
Here is the example you requested
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class BreakoutSample : Robot { SimpleMovingAverage _sma1; SimpleMovingAverage _sma2; int _singalCandleIndex; bool _hasCrossedAbove; int _breakoutCandleIndex; protected override void OnStart() { _sma1 = Indicators.SimpleMovingAverage(Bars.ClosePrices, 5); _sma2 = Indicators.SimpleMovingAverage(Bars.ClosePrices, 20); } protected override void OnBar() { if (_sma1.Result.HasCrossedAbove(_sma2.Result, 0)) { // if sma 1 has crossed above sma 2, we record the index of the bar _singalCandleIndex = Bars.ClosePrices.Count - 1; _hasCrossedAbove = true; } if (_hasCrossedAbove && Bars.HighPrices.Last(1) > Bars.HighPrices[_singalCandleIndex]) { // If last bar high is above the signal bar high, we record the breakout index _breakoutCandleIndex = _singalCandleIndex = Bars.ClosePrices.Count - 2; Print("Breakout Candle Index: " + _breakoutCandleIndex); } } protected override void OnStop() { // Put your deinitialization logic here } } }
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
19 May 2020, 18:54
RE:
Thank you very much Panagiotis. Let me try this.
PanagiotisCharalampous said:
Hi Vamsi,
Here is the example you requested
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class BreakoutSample : Robot { SimpleMovingAverage _sma1; SimpleMovingAverage _sma2; int _singalCandleIndex; bool _hasCrossedAbove; int _breakoutCandleIndex; protected override void OnStart() { _sma1 = Indicators.SimpleMovingAverage(Bars.ClosePrices, 5); _sma2 = Indicators.SimpleMovingAverage(Bars.ClosePrices, 20); } protected override void OnBar() { if (_sma1.Result.HasCrossedAbove(_sma2.Result, 0)) { // if sma 1 has crossed above sma 2, we record the index of the bar _singalCandleIndex = Bars.ClosePrices.Count - 1; _hasCrossedAbove = true; } if (_hasCrossedAbove && Bars.HighPrices.Last(1) > Bars.HighPrices[_singalCandleIndex]) { // If last bar high is above the signal bar high, we record the breakout index _breakoutCandleIndex = _singalCandleIndex = Bars.ClosePrices.Count - 2; Print("Breakout Candle Index: " + _breakoutCandleIndex); } } protected override void OnStop() { // Put your deinitialization logic here } } }
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
07 May 2020, 09:13
RE: Will check and let you know.
Excellent Panagiotis!
Thanks for your time and support. I will go through it and update you.
R C Vamsi Vardhan
PanagiotisCharalampous said:
Hi Vamsi,
1. We will need more information about this. You will need to provide us with the source code and steps to reproduce this behavior. It is almost certain that there is something wrong on your side.
2. You can find OpenAPIMessagesFactory here. Note that there are no instructions to update the Open API Library project. The instructions refer to updating only the proto classes found in the Proto folder.
3. Positions and pending orders can be retrieved using ProtoOAReconcileReq.
4. It seems to be a bug in the example project. Please go to OpenApiMessagesPresentation, Line 114 and change
sbReconcile.Append("ID: " + position.HasPositionId + Environment.NewLine);
to
sbReconcile.Append("ID: " + position.PositionId + Environment.NewLine);
5. See point 4
Best Regards,
Panagiotis
@vamsi.rc
vamsi.rc
11 Aug 2020, 16:58
RE:
Thanks for your support Panagiotis. Let me check this way. But not sure, it will resolve the issue.
PanagiotisCharalampous said:
@vamsi.rc