Here is my environment -
3 min chart
trading hours are set to regular stock/options trading hours i.e. 6:30am to 1pm PST
The premise is pretty straight forward -
When a market opens, on the very first bar of the day I want to go long/short if 34ema is above/below 63ema. I am using isFirstBarOfTheSession as 'true' with emas.
As the crossover happens I exit my long/short and open the opposite position. E.g. At open if ema 34 > ema 63 I go long and when the 34 crosses below 63 I use "exit long" and "enter short"
In theory it should work but when executing a strategy above I am seeing a situation where my position goes from 1 contract when the market opens and then switches to 2 contracts at the first crossover. How do I fix that? Any help would be appreciated.
here is the code for my strategy generated by the wizard
================================================== ===========
public class Test : Strategy
{
private EMA EMA1;
private EMA EMA2;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"34 EMA 63 EMA crossover";
Name = "Test";
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;
Ema34 = 34;
Ema63 = 63;
}
else if (State == State.Configure)
{
AddDataSeries("ES 06-21", Data.BarsPeriodType.Minute, 3, Data.MarketDataType.Last);
}
else if (State == State.DataLoaded)
{
EMA1 = EMA(Close, Convert.ToInt32(Ema34));
EMA2 = EMA(Close, Convert.ToInt32(Ema63));
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < 1)
return;
// Set 1
if (CrossAbove(EMA1, EMA2, 1))
{
EnterLong(Convert.ToInt32(DefaultQuantity), "");
ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
}
// Set 2
if (CrossBelow(EMA1, EMA2, 1))
{
EnterShort(Convert.ToInt32(DefaultQuantity), "");
ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
}
// Set 3
if ((EMA1[0] < EMA2[0])
&& (Bars.IsFirstBarOfSession == true))
{
EnterShort(Convert.ToInt32(DefaultQuantity), "");
}
// Set 4
if ((EMA1[0] > EMA2[0])
&& (Bars.IsFirstBarOfSession == true))
{
EnterLong(Convert.ToInt32(DefaultQuantity), "");
}
}
================================================== ===========
Comment