Understanding of the state of bot Positions if there is trade occur in the loop

elysecooper since: 05 Oct 2021;

  14 Oct 2021, 00:50
Understanding of the state of bot Positions if there is trade occur in the loop


I will like to understand more when we execute bot.Positions.


                foreach (var pos in this.bot.Positions.Where(x => x.SymbolName == this.symbol.Name))
                   TradeResult res = this.bot.ExecuteMarketOrder(this.currDirection, this.symbol.Name, inputLot, this.symbol.VolumeInUnitsToQuantity(inputLot).ToString());


What will happen to the Positions state if we perform close trade/execute trade/modify trade during the looping? 

Will the looping immediately include the newly opened trade into the Positions? And will the Positions count will increase?



The Positions state still remains as previous(before closing the trade until I exited the loop? 


amusleh's avatar

amusleh since: 01 Mar 2021;

  05 Oct 2021, 18:43


Positions collection is an IEnumerable, and if you open a new position or close an old one the collection will change.

If collection change while you were iterating over it (with a loop) you will get a collection modified exception and your loop will break.

To protect your bot or indicator from collection modified exception you can create a local copy of positions collection and then loop over it:

var positionsCopy = Positions.ToArray();

foreach (var position in positionsCopy)
// Do something
Community Developer | Spotware | Telegram: @algodeveloper