how to let OpenCV save the last few seconds of analyzed video
You may create a memory buffer worth of 10sec of video (~about 300 frames for most web-cameras), then save frames to that buffer, removing the old ones while adding the new ones.
Once your ball is out of the frame -- open a video file, and save your frames from the buffer.
I am trying to program a python OpenCV app for my own use because I can't go to gyms for some time. I would like to do the following:

Capture frames from a video flow using OpenCV [ done ]
Have OpenCV track a yellow soccer and return the coordinate of this soccer in the frame [done]
Come up with an algorithm to detect when a soccer juggling failed, for example the soccer went out of frame and so on [ done ]

Now my question is: let's say I want to save the "10 seconds right before this event" of video into a mp4 file. How should I do it? Is there any good template that I can follow?
Thanks!