Topics
Forum Topics not found
Replies
amusleh
25 Aug 2021, 18:17
Hi,
You just have to subtract the current price from MA value:
using cAlgo.API;
using cAlgo.API.Indicators;
using System;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class SimpleMovingAverageSample : Robot
{
private double _volumeInUnits;
private SimpleMovingAverage _simpleMovingAverage;
[Parameter("Source", Group = "MA")]
public DataSeries MaSource { get; set; }
[Parameter("Period", DefaultValue = 9, Group = "MA")]
public int MaPeriod { get; set; }
[Parameter("Volume (Lots)", DefaultValue = 0.01, Group = "Trade")]
public double VolumeInLots { get; set; }
[Parameter("Stop Loss (Pips)", DefaultValue = 10, Group = "Trade")]
public double StopLossInPips { get; set; }
[Parameter("Take Profit (Pips)", DefaultValue = 10, Group = "Trade")]
public double TakeProfitInPips { get; set; }
[Parameter("Label", DefaultValue = "Sample", Group = "Trade")]
public string Label { get; set; }
public Position[] BotPositions
{
get
{
return Positions.FindAll(Label);
}
}
protected override void OnStart()
{
_volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots);
_simpleMovingAverage = Indicators.SimpleMovingAverage(MaSource, MaPeriod);
}
protected override void OnTick()
{
if (BotPositions.Length > 0) return;
var priceDistanceFromMa = Bars.ClosePrices.LastValue - _simpleMovingAverage.Result.LastValue;
var priceDistanceFromMaInPips = priceDistanceFromMa * (Symbol.TickSize / Symbol.PipSize * Math.Pow(10, Symbol.Digits));
if (priceDistanceFromMaInPips >= 150)
{
ExecuteMarketOrder(TradeType.Buy, SymbolName, _volumeInUnits, Label, StopLossInPips, TakeProfitInPips);
}
}
}
}
@amusleh
amusleh
25 Aug 2021, 15:57
Hi,
You can use this method to get the number of bars since last cross between two moving averages:
private int GetNumberOfBarsFromLastCross(MovingAverage fastMa, MovingAverage slowMa)
{
var index = Bars.Count - 1;
var barCount = 0;
for (int iBarIndex = index; iBarIndex >= 1; iBarIndex--)
{
if ((fastMa.Result[iBarIndex] > slowMa.Result[iBarIndex] && fastMa.Result[iBarIndex - 1] <= slowMa.Result[iBarIndex - 1]) || (fastMa.Result[iBarIndex] < slowMa.Result[iBarIndex] && fastMa.Result[iBarIndex - 1] >= slowMa.Result[iBarIndex - 1]))
{
break;
}
barCount++;
}
return barCount;
}
@amusleh
amusleh
25 Aug 2021, 15:48
Hi,
Our example on API documentation does exactly that, please check: cAlgo API Reference - SimpleMovingAverage Interface (ctrader.com)
There are other examples for other moving average types and indicators, please check.
@amusleh
amusleh
25 Aug 2021, 15:46
Hi,
Please check the simple moving average example cBot: cAlgo API Reference - SimpleMovingAverage Interface (ctrader.com)
The example cBot opens a buy position if faster MA cross upward the slower MA and a sell position if faster M<A cross downward the slower MA.
If you need something more complicated you can post a job request or ask one of our consultants to develop your cBot.
@amusleh
amusleh
23 Aug 2021, 15:00
Hi,
You can develop a multi time frame MACD indicator based on built-in MACD indicator easily, try this:
using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
namespace cAlgo
{
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class MACDMTF : Indicator
{
private MacdCrossOver _macd;
private Bars _baseTimeFrameBars;
[Parameter("Base TimeFrame", DefaultValue = "Daily")]
public TimeFrame BaseTimeFrame { get; set; }
[Parameter("Source", DefaultValue = DataSource.Close)]
public DataSource DataSource { get; set; }
[Parameter("Long Cycle", DefaultValue = 26)]
public int LongCycle { get; set; }
[Parameter("Long Cycle", DefaultValue = 12)]
public int ShortCycle { get; set; }
[Parameter("Signal Periods", DefaultValue = 9)]
public int SignalPeriods { get; set; }
[Output("MACD", LineColor = "Blue", LineStyle = LineStyle.Solid, PlotType = PlotType.Line)]
public IndicatorDataSeries Macd { get; set; }
[Output("Signal", LineColor = "Red", LineStyle = LineStyle.Lines, PlotType = PlotType.Line)]
public IndicatorDataSeries Signal { get; set; }
[Output("Histogram", LineColor = "Brown", LineStyle = LineStyle.Solid, PlotType = PlotType.Histogram)]
public IndicatorDataSeries Histogram { get; set; }
protected override void Initialize()
{
_baseTimeFrameBars = MarketData.GetBars(BaseTimeFrame);
var dataSeries = GetDataSource();
_macd = Indicators.MacdCrossOver(dataSeries, LongCycle, ShortCycle, SignalPeriods);
}
public override void Calculate(int index)
{
var baseIndex = _baseTimeFrameBars.OpenTimes.GetIndexByTime(Bars.OpenTimes[index]);
Macd[index] = _macd.MACD[baseIndex];
Signal[index] = _macd.Signal[baseIndex];
Histogram[index] = _macd.Histogram[baseIndex];
}
private DataSeries GetDataSource()
{
switch (DataSource)
{
case DataSource.Open:
return _baseTimeFrameBars.OpenPrices;
case DataSource.High:
return _baseTimeFrameBars.HighPrices;
case DataSource.Low:
return _baseTimeFrameBars.LowPrices;
case DataSource.Close:
return _baseTimeFrameBars.ClosePrices;
default:
throw new InvalidOperationException("Not supported data source type");
}
}
}
public enum DataSource
{
Open,
High,
Low,
Close
}
}
@amusleh
amusleh
20 Aug 2021, 09:17
RE: RE:
Neilsh said:
PanagiotisCharalampous said:
Hi Neilsh,
Can you please confirm that there is no custom indicator being used when this happens?
Best Regards,
Panagiotis
Hi ctrader becomes unresponsive with 7 charts open with HMA on a couple of them.
Hi,
Please remove all custom indicators/cBots from your charts, and then monitor your RAM usage for sometime.
Most of the time the high RAM usage is due to poor coding of custom indicators/cBots.
If the RAM usage was still high without any custom indicator/cBot then let us know.
@amusleh
amusleh
16 Aug 2021, 15:36
Hi,
When you are using a custom indicator on a cBot you must pass a value for all of the indicator parameters, for TDI you can use it like this:
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
public class TDISystem : Robot
{
//parameters
private TradersDynamicIndex _TDI;
protected override void OnStart()
{
_TDI = Indicators.GetIndicator<TradersDynamicIndex>(Bars.ClosePrices, 13, 2, 7, 34, 2, MovingAverageType.Simple, MovingAverageType.Simple);
}
protected override void OnBar()
{
// Put your core logic here
}
protected override void OnStop()
{
// Put your deinitialization logic here
}
}
}
The parameters you pass must be in same order that is defined in indicator.
@amusleh
amusleh
16 Aug 2021, 15:33
Hi,
You can use any other time frame data for drawing objects on a chart, the code you have posted draws an horizontal line on latest closed hourly chart bar high, try this:
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class Test : Indicator
{
private Bars oneHrBars;
protected override void Initialize()
{
oneHrBars = MarketData.GetBars(TimeFrame.Hour);
}
public override void Calculate(int index)
{
if (Chart.TimeFrame != TimeFrame.Hour)
{
var a = Chart.DrawHorizontalLine("Hourly High", oneHrBars.HighPrices.Last(1), Color.Cyan);
a.IsInteractive = true;
}
}
}
}
Change your time frame to a chart other than hourly chart, and you will see that indicator will draw an horizontal line, then switch back to hourly chart and you will see that the horizontal line is on last closed candle high price.
For matching one time data to another time frame you can use GetIndexByTime method of Bars.OpenTimes.
@amusleh
amusleh
16 Aug 2021, 08:10
RE: RE:
opusensemble said:
Hi Panagiotis;
What method would be recommended if one wants to get the P&L updating in real time?
Thank you,
opus
PanagiotisCharalampous said:Hi namth0712,
The balance is available in ProtoOATrader.balance. The P&L of each position needs to be calculated using the position's entry price and the current symbol bid/ask price.
Best Regards,
Panagiotis
Hi,
You should use ExecutionEvent to get every trade operation on user account, and also you must subscribe to each position symbol so you will be able to calculate the real time tick value of each symbol for calculating P&L.
We have complete examples of this on our .NET library for Open API: GitHub - spotware/OpenAPI.Net: Spotware Open API .NET Rx library
Try our ASP.NET core or WPF samples.
We can't develop a sample for all programming languages but we will try to do at least for some of the most popular ones.
And I recommend you to read the tutorials on our new Open API documentation: Open API (spotware.github.io)
@amusleh
amusleh
12 Aug 2021, 20:21
Hi,
Try this:
using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
namespace cAlgo
{
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class AWMACDMTF : Indicator
{
private StochasticOscillator _stoch;
private Bars _baseTimeFrameBars;
// you could change default Value to Minute,Minute15,Hour2 and ...
[Parameter("Base Timeframe", DefaultValue = "Minute15")]
public TimeFrame BaseTimeFrame { get; set; }
[Parameter("K%", DefaultValue = 5)]
public int kPeriod { get; set; }
[Parameter("K slowing", DefaultValue = 3)]
public int kslowing { get; set; }
[Parameter("D%", DefaultValue = 3)]
public int dPeriod { get; set; }
[Output("K%,", LineColor = "Red", LineStyle = LineStyle.Solid, Thickness = 2)]
public IndicatorDataSeries k_Line { get; set; }
[Output("D%,", LineColor = "Blue", LineStyle = LineStyle.Solid, Thickness = 2)]
public IndicatorDataSeries d_Line { get; set; }
protected override void Initialize()
{
_baseTimeFrameBars = MarketData.GetBars(BaseTimeFrame);
_stoch = Indicators.StochasticOscillator(_baseTimeFrameBars, kPeriod, kslowing, dPeriod, MovingAverageType.Simple);
}
public override void Calculate(int index)
{
var baseSeriesIndex = _baseTimeFrameBars.OpenTimes.GetIndexByTime(Bars.OpenTimes[index]);
k_Line[index] = _stoch.PercentK[baseSeriesIndex];
d_Line[index] = _stoch.PercentD[baseSeriesIndex];
}
}
}
@amusleh
amusleh
10 Aug 2021, 16:18
( Updated at: 10 Aug 2021, 16:20 )
Hi,
Not sure what's your exact problem, but you can try this method to get volume in percentage:
/// <summary>
/// Returns the amount of volume based on your provided risk percentage and stop loss
/// </summary>
/// <param name="symbol">The symbol</param>
/// <param name="riskPercentage">Risk percentage amount</param>
/// <param name="accountBalance">The account balance</param>
/// <param name="stopLossInPips">Stop loss amount in Pips</param>
/// <returns>double</returns>
public double GetVolume(Symbol symbol, double riskPercentage, double accountBalance, double stopLossInPips)
{
return symbol.NormalizeVolumeInUnits(riskPercentage / (Math.Abs(stopLossInPips) * symbol.PipValue / accountBalance * 100));
}
@amusleh
amusleh
09 Aug 2021, 15:28
Hi,
Try this:
using System;
using System.Linq;
using cAlgo.API;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class Test : Robot
{
[Parameter(DefaultValue = "Test")]
public string Label { get; set; }
protected override void OnStop()
{
var openPoisitionPipsSum = Positions.FindAll(Label).Sum(position => position.Pips);
var historicalTradesPipsSum = History.Where(trade => trade.Label.Equals(Label, StringComparison.OrdinalIgnoreCase)).Sum(trade => trade.Pips);
Print("Open Positions Pips: {0} | Historical Trades Pips: {1}", openPoisitionPipsSum, historicalTradesPipsSum);
}
}
}
@amusleh
amusleh
30 Aug 2021, 08:51
Hi,
You can download the DLL files from Github releases: Release 2.2.2 · afhacker/ctrader-alert_popup (github.com)
The release.zip file contains all DLL files.
I strongly recommend you to use Visual Studio for developing indicators/cBots, that's the best IDE for developing .NET on Windows.
In case you are using .NET on a Linux then use VS Code.
For VS Code you can use the Nuget Package Manager GUI extension: Nuget Package Manager GUI - Visual Studio Marketplace
@amusleh