One of the main challenges of Transmission System Operators (TSO) is the management of unexpected congestions due to sudden increases in demand levels or equipment failure. They can rely on demand-side flexibility resources to deal with these difficulties in this situation. The fact that these resources are often located in the distribution network necessitates coordination between TSOs and Distribution System Operators (DSOs). The purpose of this study is to present a market-based framework for transmission system congestion management through demand-side flexibility resources considering distribution network loss reduction. The proposed framework consists of two levels. At the first level, the TSO clears the flexibility market, and the only participants in this market are DSOs. The second level consists of local markets implemented in each distribution network and settled by DSOs. Prosumers can sell their proposed flexibility services in these markets. DSOs amend the prosumers’ bid prices for distribution network performance optimization and then submit them to the first level flexibility market. To evaluate the performance of the bi-level flexibility market, the proposed structure has been implemented on the IEEE 9-Bus transmission system. The system consists of two distribution networks that provide the flexibility required by TSO. Based on two constraints, the loading state of the distribution network (Technical) and the convenience of prosumers (Behavioral), three scenarios have been considered. According to simulation results, ignoring both technical and behavioral constraints will result in lower costs for the TSO.