Praise be to Allah.
The Muslim has to guard his hearing, his vision and all his faculties against doing that which Allah, may He be exalted, has forbidden to him. The basic principle is that fasting purifies the soul and is a shield that protects a person from falling into whims and desires.
The scholars differed as to whether the fast is invalidated by emitting maniy as a result of thinking. The Maalikis said that it does invalidate the fast, but the majority of scholars did not regard it as invalidating the fast. It seems that they did not regard it as invalidating the fast because the individual has no control over it; it is something that crossed his mind that he could not ward off. But in the case of deliberately thinking and giving one’s imagination free rein with the aim of ejaculating, there is no difference – in that case – between that and deliberately looking at something for the purpose of ejaculating. The majority are of the view that the fast is invalidated by deliberately looking until one ejaculates.
It says in al-Mawsoo‘ah al-Fiqhiyyah, 26/267:
The Hanafis and Shaafa‘is are of the view that emission of maniy or madhiy as a result of looking or thinking does not invalidate the fast. But the more correct view according to the Shaafa‘is is that if one habitually ejaculates by looking, or one looks repeatedly and then ejaculates, that invalidates the fast.
The Maalikis and Hanbalis are of the view that the emission of maniy as a result of persistent looking invalidates the fast, because it is emitted as a result of an action that is enjoyed and that one could have put a stop to.
With regard to ejaculation as a result of thinking, it invalidates the fast according to the Maalikis, but according to the Hanbalis it does not invalidate it because it was difficult to avoid it. End quote.
See the answer to question no. 22750
If the fast is spoiled, then you have to make up that day but you do not have to offer any expiation, because the expiation is only required of the one who spoils his fast by having intercourse.
What you have to do is:
1.Repent from the sin of engaging in the secret habit
For information on the prohibition thereon, see the answer to question no. 329
2.Make up that day.
And Allah knows best.