I consider a New Keynesian model of a small open economy where international financial markets are imperfect and the exchange rate is determined by capital flows. I use this framework to study the effects of exchange rate fluctuations driven by capital flows and characterize the optimal foreign exchange intervention. Capital flow shocks cause inefficient exchange rate fluctuations that trigger boom-bust cycles in the domestic economy. The optimal policy response is to use both foreign exchange intervention and monetary policy to stabilize the economy. Foreign exchange intervention “leans against the wind” and stabilizes the path of the exchange rate, while monetary policy corrects the inefficiencies caused by price rigidity. The two tools are complements rather than substitutes. I derive the optimal foreign exchange intervention rule in closed form as a function of three implicit targets: a wedge in the Bakus-Smith condition, domestic net foreign assets, and the level of foreign reserves.