Does capital gain happens when we withdraw the money OR when we sell the stocks

Salam i would like to know if i need to purify the capital gains right after selling the stock or only when withdraw the money from the brokerage account

Basically 2 situations: e.g.

  1. $100 capital gain from selling stock. But wishes to retain the money in brokerage to invest/prepare for other stocks

  2. $100 capital gain from selling stock. Withdraw the $100 from brokerage to bank account

Does purification applies to both or only number 2??
Also i believe in this case purifications of 5% ($5) is appropriate for all sharia compliant stocks since less than 5% (or none) of the stock is or could be non compliant

jazakallah khair