Modern Tokamaks have evolved from the initial axisymmetric circular plasma shape to an elongated axisymmetric plasma shape that improves the energy confinement time and the triple product, which is a generally used figure of merit for the conditions needed for fusion reactor performance. However, the elongated plasma cross section introduces a vertical instability that demands a real-time feedback control loop to stabilize the plasma vertical position and velocity. At the Tokamak \`a Configuration Variable (TCV) in-vessel poloidal field coils driven by fast switching power supplies are used to stabilize highly elongated plasmas. TCV plasma experiments have used a PID algorithm based controller to correct the plasma vertical position. In late 2013 experiments a new optimal real-time controller was tested improving the stability of the plasma. This contribution describes the new optimal real-time controller developed. The choice of the model that describes the plasma response to the actuators is discussed. The high order model that is initially implemented demands the application of a mathematical order reduction and the validation of the new reduced model. The lower order model is used to derive the time optimal control law. A new method for the construction of the switching curves of a bang-bang controller is presented that is based on the state-space trajectories that optimize the time to target of the system. A closed loop controller simulation tool was developed to test different possible algorithms and the results were used to improve the controller parameters. The final control algorithm and its implementation are described and preliminary experimental results are discussed.