Objective. Suboptimal electrode placement during subthalamic nucleus deep brain stimulation (STN DBS) surgery may arise from several sources, including frame-based targeting errors and intraoperative brain shift. We present a computer algorithm that can accurately localize intraoperative microelectrode recording (MER) tracks on preoperative magnetic resonance imaging (MRI) in real-time, thereby predicting deviation between the surgical plan and the MER trajectories. Approach. Random forest (RF) modeling was used to derive a statistical relationship between electrophysiological features on intraoperative MER and voxel intensity on preoperative T2-weighted MR imaging. This model was integrated into a larger algorithm that can automatically localize intraoperative MER recording tracks on preoperative MRI in real-time. To verify accuracy, targeting error of both the planned intraoperative trajectory (‘planned’) and the algorithm-derived trajectory (‘calculated’) was estimated by measuring deviation from the final DBS lead location on postoperative high-resolution computed tomography (‘actual’). Main results. MR imaging and MERs were obtained from 24 STN DBS implant trajectories. The cross-validated RF model could accurately distinguish between gray and white matter regions along MER trajectories (AUC 0.84). When applying this model within the localization algorithm, the calculated MER trajectory estimate was found to be significantly closer to the actual DBS lead when compared to the planned trajectory recorded during surgery (1.04 mm vs 1.52 mm deviation, p < 0.002), with improvement shown in 19/24 cases (79%). When applying the algorithm to simulated DBS trajectory plans with randomized targeting error, up to 4 mm of error could be resolved to <2 mm on average (p < 0.0001). Significance. This work presents an automated system for intraoperative localization of electrodes during STN DBS surgery. This neuroengineering solution may enhance the accuracy of electrode position estimation, particularly in cases where high-resolution intraoperative imaging is not available.