This paper introduces a new method to design a PID controller using a data driven approach for identification. The tuning algorithm is developed within the subspace identification framework, which is used to identify an open loop model from closed-loop data. The PID parameters are calculated by minimising a quadratic performance index over a finite future horizon. The inclusion of a closed-loop condition to guarantee stability results in a constrained nonlinear optimisation problem. The paper includes simulation results for the case of a dissolved oxygen control loop in an activated sludge wastewater treatment plant.