This paper formulates an optimization-based algorithm for the compensation of unwanted current terms by means of distributed electronic power converters, such as active power filters and grid-connected inverters. The compensation goal consists in achieving suitable load conformity factors, defined at the source side and within a feasible power region in terms of the power converter capability. Based on the measured load quantities and on a certain objective function, the algorithm tracks the expected source currents, which are thereupon used to calculate proper scaling coefficients and, therefore, the compensation current references. It improves the power quality at the point of common coupling and enables full exploitation of distributed energy resources, increasing their efficiency. The compensation is based on a decoupled current decomposition and on an optimization-based algorithm. In this paper, the strategy is applied to nonlinear and unbalanced three-phase four-wire circuit, under nonsinusoidal and asymmetrical voltage conditions. The steady-state and dynamic behaviors have been analyzed by theoretical, simulation, and experimental results. Furthermore, the proposed approach is also compared to other compensation strategies showing its effectiveness.