Power grids include entities such as home-microgrids (H-MGs), consumers, and retailers, each of which has a unique and sometimes contradictory objective compared with others while exchanging electricity and heat with other H-MGs. Therefore, there is the need for a smart structure to handle the new situation. This paper proposes a bilevel hierarchical structure for designing and planning distributed energy resources (DERs) and energy storage in H-MGs by considering the demand response (DR). In general, the upper-level structure is based on H-MG generation competition to maximize their individual and/or group income in the process of forming a coalition with other H-MGs. The upper-level problem is decomposed into a set of low-level market clearing problems. Both electricity and heat markets are simultaneously modeled in this paper. DERs, including wind turbines (WTs), combined heat and power (CHP) systems, electric boilers (EBs), electric heat pumps (EHPs), and electric energy storage systems, participate in the electricity markets. In addition, CHP systems, gas boilers (GBs), EBs, EHPs, solar thermal panels, and thermal energy storage systems participate in the heat market. Results show that the formation of a coalition among H-MGs present in one grid will not only have a significant effect on programming and regulating the value of the power generated by the generation resources, but also impact the demand consumption and behavior of consumers participating in the DR program with a cheaper market clearing price.