I've coded a simple EMA cross strategy.
In this strategy, I tried to code the number of contracts to trade based on 1% of the account.
It seems to work but the only problem is that the number of contract for a given trade is actually applied to the next trade.
I guess it's a problem of code logic and architecture but I'm not sure how to re-arrange this.
Below is the code.
Thanks for your help!
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Enter the description for your new custom Strategy here.";
Name = "FirstStrategyunlocked";
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;
CrossEMA = 6;
RR_Reward = 5;
StopLossTicks = 200;
ProfitTargetTicks = 1000;
}
else if (State == State.Configure)
{
/* Safety SL, incrementend at entry */
SetStopLoss(CalculationMode.Ticks, StopLossTicks);
}
else if (State == State.DataLoaded)
{
/* Indicators */
EMA1 = EMA(Close, CrossEMA);
/* Visuals */
EMA1.Plots[0].Brush = Brushes.Goldenrod;
AddChartIndicator(EMA1);
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
bool market_open = ToTime(Time[0]) >= 000000 && ToTime(Time[0]) <= 230059;
bool cross_above = CrossAbove(Close, EMA1, 1);
bool cross_below = CrossBelow(Close, EMA1, 1);
Long = "Yes";
Short = "Yes";
if (Position.MarketPosition == MarketPosition.Flat)
{
TradeSet = "No";
SetProfitTarget(CalculationMode.Ticks, ProfitTargetTicks);
SetStopLoss(CalculationMode.Ticks, StopLossTicks);
}
if (TradeSet == "No")
{
if (Position.MarketPosition == MarketPosition.Long)
{
entryPrice = Position.AveragePrice;// Assuming entry price is one tick above the high
stopPrice = Low[1];
targetPrice = Position.AveragePrice + (Position.AveragePrice - stopPrice) * RR_Reward;
Print(ToTime(Time[0]));
Print("Entry Price:"+ entryPrice);
Print("stopPrice:"+ stopPrice);
Print("targetPrice:"+ targetPrice);
TradeSet = "Yes";
SetProfitTarget(CalculationMode.Price, targetPrice);
SetStopLoss(CalculationMode.Price, stopPrice);
}
if (Position.MarketPosition == MarketPosition.Short)
{
entryPrice = Position.AveragePrice;// Assuming entry price is one tick above the high
stopPrice = High[1];
targetPrice = Position.AveragePrice + (Position.AveragePrice - stopPrice) * RR_Reward;
Print(ToTime(Time[0]));
Print("Entry Price:"+ entryPrice);
Print("stopPrice:"+ stopPrice);
Print("targetPrice:"+ targetPrice);
TradeSet = "Yes";
SetProfitTarget(CalculationMode.Price, targetPrice);
SetStopLoss(CalculationMode.Price, stopPrice);
}
}
// Calculate position size based on account value (1% of cash value)
double accountSize = Account.Get(AccountItem.CashValue, Currency.UsDollar);
double myPositionSize = accountSize * 0.01;
// Print the calculated account size and position size
Print("Account Size (USD): " + accountSize.ToString("F2"));
Print("Position Size (USD): " + myPositionSize.ToString("F2"));
// Define tick value (replace tickValue with the actual tick value of your instrument)
double tickValue = 5;
// Print the tick value
Print("Tick Value: " + tickValue.ToString("F2"));
double TicksSL = Math.Abs(entryPrice - stopPrice) / TickSize;
// Print the calculated number of ticks for stop loss
Print("Ticks for Stop Loss: " + TicksSL.ToString("F2"));
int contractsToTrade = (int)Math.Floor(myPositionSize / tickValue / TicksSL); // Convert to integer number of contracts
// Print the calculated number of contracts to trade
Print("Contracts to Trade: " + contractsToTrade.ToString());
if (market_open)
{
if (cross_above)
{
if (Long == "Yes" && Position.MarketPosition == MarketPosition.Flat)
{
EnterLong(contractsToTrade,"Long"); //EnterLong(Convert.ToInt32(DefaultQuantity),"Long") , Convert.ToString(CurrentBar)+"LongEntry"
Print("TRADE");
Print(ToTime(Time[0]));
}
}
else if (cross_below && Short == "Yes")
{
if (Position.MarketPosition == MarketPosition.Flat)
{
EnterShort(contractsToTrade,"Short");
}
}

Comment