Combining energy harvesting (EH) and device-to-device (D2D) communication underlaying 5G cellular networks is a very promising direction to improve both energy and spectral efficiencies. Unlike conventional relay-aided D2D communication that assumes one-way relaying (OWR) protocols, this paper proposes a two-way relaying (TWR) model. It aims to maximize the TWR D2D link rate that shares the uplink (UL) resources of the conventional cellular user (CU) considering the quality of service (QoS) constraints of all users. Besides, the relays are considered to harvest renewable energy (RE) from the ambient environment by relying on an attached solar panel. Also, they can harvest radio frequency (RF) energy from the received signal based on the power splitting (PS) EH protocol. Assuming that the UL resource allocation (RA) is already performed, the paper's objective is to jointly optimize the transmission power of all users in addition to the PS factor of relays based on the well-known meta-heuristic algorithm particle swarm optimization (PSO). Also, the best relay is selected by relying on the delimited area (DA) mechanism and the balanced residual energy (BRE) leading to TWR D2D link rate maximization and better energy efficiency (EE). The performance of the proposed algorithm is investigated through the results as well as comparing its performance to two of the most recent relay-aided D2D algorithms.INDEX TERMS Device-to-device, two-way relaying, energy harvesting, power splitting, particle swarm optimization, power allocation, decode-and-forward, relay selection.