I have a strategy that doesn't works as expected. One of the exit rules is to exit a trade Exit Trade if it's unprofitable after N days. Here's part of the code.
Entry:
if (entryOrder == null && profitTakerOrder == null && stopLossOrder == null)
{
BackBrush = Brushes.LightGreen;
SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Market,
Convert.ToInt32(Math.Round(AssetAmount / Open[0], 0, MidpointRounding.ToEven)), 0, 0, "", entryName);
}
if (entryOrder != null)
{
if (BarsSinceEntryExecution(entryName) >= 4 && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) <= 0)
{
BackBrush = Brushes.LightSalmon;
Print(Instrument.FullName + " --- " + Time[0] + " --- ExitLongByUnprofitableRule --- " + entryOrder.ToString());
CancelOrder(entryOrder);
}
}
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
{
if (execution.Order.OrderState != OrderState.Filled)
return;
Print("Execution: " + execution.ToString());
if (entryOrder == null)
{
if (profitTakerOrder != null && (profitTakerOrder.OrderState == OrderState.Accepted || profitTakerOrder.OrderState == OrderState.Working))
CancelOrder(profitTakerOrder);
else if (stopLossOrder != null && (stopLossOrder.OrderState == OrderState.Accepted || stopLossOrder.OrderState == OrderState.Working))
CancelOrder(stopLossOrder);
}
if (entryOrder != null && execution.Order == entryOrder)
{
// Stop Loss
stopLossOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket,
execution.Order.Filled, 0, execution.Order.AverageFillPrice - ((execution.Order.AverageFillPrice / 100) * PctgSl), string.Empty, "Stop Loss");
// Profit Taker
profitTakerOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit,
execution.Order.Filled, execution.Order.AverageFillPrice + ((execution.Order.AverageFillPrice / 100) * PctgPl), 0, string.Empty, "Profit Taker");
if (execution.Order.OrderState != OrderState.PartFilled)
entryOrder = null;
}
if ((stopLossOrder != null && stopLossOrder == execution.Order) || (profitTakerOrder != null && profitTakerOrder == execution.Order))
{
if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
{
stopLossOrder = null;
profitTakerOrder = null;
}
}
}
Thanks for your help.

Comment