Also, I think my sets 3 and 4, that should exit the positions if there is anopposite crossover, are not working. Could anyone please help?
region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class V12 : Strategy
{
private EMA EMA1;
private EMA EMA2;
private string atmStrategyId = string.Empty;
private string orderId = string.Empty;
private bool isAtmStrategyCreated = false;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Digite a descrição para seu novo Estratégia personalizado aqui.";
Name = "V12";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 0;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = false;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 20;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
Rapida = 9;
Lenta = 39;
ATMStrategy = @"ATM1";
StopLoss = -40;
Alvo = 120;
}
else if (State == State.Configure)
{
}
else if (State == State.DataLoaded)
{
EMA1 = EMA(Close, Convert.ToInt32(Rapida));
EMA2 = EMA(Close, Convert.ToInt32(Lenta));
EMA1.Plots[0].Brush = Brushes.Goldenrod;
EMA2.Plots[0].Brush = Brushes.Blue;
AddChartIndicator(EMA1);
AddChartIndicator(EMA2);
SetProfitTarget(@"Compra", CalculationMode.Ticks, Alvo);
SetStopLoss(@"Compra", CalculationMode.Ticks, StopLoss, false);
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < 1)
return;
if(State == State.Historical)
return;
// Definir 1
if (orderId.Length == 0 && atmStrategyId.Length == 0 && CrossAbove(EMA1, EMA2, 1))
{
isAtmStrategyCreated = false; // reset atm strategy created check to false
atmStrategyId = GetAtmStrategyUniqueId();
orderId = GetAtmStrategyUniqueId();
AtmStrategyCreate(OrderAction.Buy, OrderType.Limit, Close[0], 0, TimeInForce.Gtc, orderId, ATMStrategy, atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
//check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback
if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
isAtmStrategyCreated = true;
});
}
// Check that atm strategy was created before checking other properties
if (!isAtmStrategyCreated)
return;
// Check for a pending entry order
if (orderId.Length > 0)
{
string[] status = GetAtmStrategyEntryOrderStatus(orderId);
// If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
if (status.GetLength(0) > 0)
{
// Print out some information about the order to the output window
Print("The entry order average fill price is: " + status[0]);
Print("The entry order filled amount is: " + status[1]);
Print("The entry order order state is: " + status[2]);
// If the order state is terminal, reset the order id value
if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
orderId = string.Empty;
}
} // If the strategy has terminated reset the strategy id
else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
atmStrategyId = string.Empty;
if (atmStrategyId.Length > 0)
{
// You can change the stop price
if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
// Print some information about the strategy to the output window, please note you access the ATM strategy specific position object here
// the ATM would run self contained and would not have an impact on your NinjaScript strategy position and PnL
Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId)) ;
Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId)) ;
}
// Definir 2
if (orderId.Length == 0 && atmStrategyId.Length == 0 && CrossBelow(EMA1, EMA2, 1))
{
isAtmStrategyCreated = false; // reset atm strategy created check to false
atmStrategyId = GetAtmStrategyUniqueId();
orderId = GetAtmStrategyUniqueId();
AtmStrategyCreate(OrderAction.Sell, OrderType.Limit, Close[0], 0, TimeInForce.Gtc, orderId, ATMStrategy, atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
//check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback
if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
isAtmStrategyCreated = true;
});
}
// Check that atm strategy was created before checking other properties
if (!isAtmStrategyCreated)
return;
// Check for a pending entry order
if (orderId.Length > 0)
{
string[] status = GetAtmStrategyEntryOrderStatus(orderId);
// If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
if (status.GetLength(0) > 0)
{
// Print out some information about the order to the output window
Print("The entry order average fill price is: " + status[0]);
Print("The entry order filled amount is: " + status[1]);
Print("The entry order order state is: " + status[2]);
// If the order state is terminal, reset the order id value
if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
orderId = string.Empty;
}
} // If the strategy has terminated reset the strategy id
else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
atmStrategyId = string.Empty;
if (atmStrategyId.Length > 0)
{
// You can change the stop price
if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
AtmStrategyChangeStopTarget(0, Low[0] + 3 * TickSize, "STOP1", atmStrategyId);
// Print some information about the strategy to the output window, please note you access the ATM strategy specific position object here
// the ATM would run self contained and would not have an impact on your NinjaScript strategy position and PnL
Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId)) ;
Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId)) ;
}
// Definir 3
if ((Position.MarketPosition == MarketPosition.Long)
&& (CrossBelow(EMA1, EMA2, 1)))
{
ExitLong(1, "", "");
}
// Definir 4
if ((Position.MarketPosition == MarketPosition.Short)
&& (CrossAbove(EMA1, EMA2, 1)))
{
ExitShort(1, "", "");
}
}
region Properties
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Rapida", Order=1, GroupName="Parameters")]
public int Rapida
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Lenta", Order=2, GroupName="Parameters")]
public int Lenta
{ get; set; }
[NinjaScriptProperty]
[Display(Name="ATMStrategy", Order=3, GroupName="Parameters")]
public string ATMStrategy
{ get; set; }
[NinjaScriptProperty]
[Range(-9999, int.MaxValue)]
[Display(Name="StopLoss", Order=4, GroupName="Parameters")]
public int StopLoss
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Alvo", Order=5, GroupName="Parameters")]
public int Alvo
{ get; set; }
#endregion
}
}

Comment