Hi and welcome to HCM.
First, you should stop masturbating when you feel pain.
It could be related to masturbation
,but some other possiuble causes should be considered such as STD or inguinal hernia. SO I suggest to do ultrasound and STD testing to evaluate this.
also can be caused by testical abnormality but various possible causes are there with most common inflammatory bowel disease
,IBD or stomach and gallbladder
disorders.You should go step by step and rule out inguinal hernias and STD. WIsh you good health.