Close a position
Close a position
07 May 2020, 15:19
I can't figure out how to close a position.
Here's an example, the position keeps running in backtest
using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo.Robots
{
[Robot(AccessRights = AccessRights.None)]
public class MacdBot : Robot
{
private MacdHistogram _macd;
private Position _position;
[Parameter(DefaultValue = 10000, MinValue = 0)]
public int Volume { get; set; }
[Parameter("Period", DefaultValue = 9)]
public int Period { get; set; }
[Parameter("Long Cycle", DefaultValue = 26)]
public int LongCycle { get; set; }
[Parameter("Short Cycle", DefaultValue = 12)]
public int ShortCycle { get; set; }
protected override void OnStart()
{
_macd = Indicators.MacdHistogram(LongCycle, ShortCycle, Period);
}
protected override void OnBar()
{
if (Trade.IsExecuting)
return;
bool isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
bool isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;
if (_macd.Histogram.LastValue > 0.0 && _macd.Signal.IsRising() && !isLongPositionOpen)
{
ClosePosition();
Buy();
}
if (_macd.Histogram.LastValue < 0.0 && _macd.Signal.IsFalling() && !isShortPositionOpen)
{
ClosePosition();
Sell();
}
}
private void ClosePosition()
{
if (_position != null)
{
Trade.Close(_position);
_position = null;
}
}
private void Buy()
{
Trade.CreateBuyMarketOrder(Symbol, Volume);
}
private void Sell()
{
Trade.CreateSellMarketOrder(Symbol, Volume);
}
protected override void OnPositionOpened(Position openedPosition)
{
_position = openedPosition;
}
}
}
Replies
amirus.stark
08 May 2020, 05:07
RE:
for example :
protected override void OnBar()
{
var lastIndex = Bars.ClosePrices.Count - 1;
_isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
_isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;
double close = Bars.ClosePrices[lastIndex];
double lastClose = Bars.ClosePrices[lastIndex];
double ema = _ema.Result[lastIndex];
double lastEma = _ema.Result[lastIndex];
foreach (var position in Positions)
{
if (close == _ema.Result.Last(0))
{
ClosePosition(position);
}
}
in this code the bars close above the ema but the position isn't being closed
@amirus.stark
PanagiotisCharalampous
08 May 2020, 08:51
Hi amirus.stark,
As I said above, we need cBot parameters, backtesting settings and exact dates where you expect your position to close but does not.
Best Regards,
Panagiotis
@PanagiotisCharalampous
PanagiotisCharalampous
07 May 2020, 15:36
Hi amirus.stark,
You need to provide more information about your issue like cBot parameters, backtesting settings and exact dates where you expect your position to close but does not.
Best Regards,
Panagiotis
Join us on Telegram
@PanagiotisCharalampous