disclaimer: I'm quite new to c# and handling orders in ninjatrader.
I try to build a risk manager that flattens my trade if the positions are too much in loss. Currently I'm using OnAccountItemUpdate event for checking if the account is below my allowed limit and if yes then I try to flatten the trades. unfortunately something is wrong with my code is I just got ninjatrader in a state that I couldn't flatten my trades by anymeans from ninjatrader UI. The error can be in many places and now I start to narrow it down. I don't know if my general idea is a correct one, so please let me know if this should work as intended or is there better way to approach this issue?:
private void OnAccountItemUpdate(object sender, AccountItemEventArgs e) { lock (m_account.Positions) { foreach (Position position in m_account.Positions) { double profitLoss = position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency); if(profitLoss <= singlePositionMaxRisk) { NinjaTrader.Code.Output.Process(string.Format("Ris kManager Max trade loss triggered at loss of: {0} at price of {1}", profitLoss, position.AveragePrice), PrintTo.OutputTab1); flattenAllTrades();// kill the trades m_status = string.Format("Position max loss reached. 5min cooloff time started at {0} ",DateTime.Now); PlaySound(@"F:\TRADING\NinjaTrader\riskManagerAudi o\maxStopAmountHit.wav"); } } }//END of LOCK }
private void flattenAllTrades() //kill all trades { NinjaTrader.Code.Output.Process(string.Format("fla ttenAllTrades called"), PrintTo.OutputTab1); foreach (Position position in m_account.Positions) { NinjaTrader.Code.Output.Process(string.Format("fla ttening trade on instrument {0} ", position.Instrument), PrintTo.OutputTab1); m_account.Flatten(new [] {position.Instrument}); m_account.CancelAllOrders(position.Instrument); } }
Comment