Optimization of energy exchanges in utility grids with applications to residential, industrial and tertiary cases