The paper proposes an innovative approach for the analytical solution of agent-based models. The approach is termed Dynamic Stochastic Generalized Aggregation (DSG-A) and is tested on a macroeconomic model articulated in a job and in a goods markets with a large number of heterogeneous and interacting agents (namely firms and workers). The agents heuristically adapt their expectations by interpreting the signals from the market and give rise to macroeconomic regularities. The model is analytically solved in two different scenarios. In the first, the emergent proper- ties of the system are determined uniquely by the myopic behavior of the agents while, in the second, a social planner quantifies the optimal number of agents adopting a particular strategy. The integration of the DSG-A approach with intertemporal optimal control allows the identification of multiple equilibria and their qualitative classification.