Basically there are three trading emotions, all working against you (fear, greed, hope).
Hope works against you when you are in a loosing trade. You don't survive long until you at least put in rigid stop loss rule in your trading plan and adhere to them.
Fear causes you to exit early. Best solution is switch to the "adding to a winning position" mind set. You have a winning trade, where will you add on?
Greed causes you to think the market will run your direction forever. You must combat greed with a profit taking plan. Either A) targets or B) Time (e.g. exit on close in a trending market) C) trailing stop or D) some combination of A or B with C.
As to why you enter countertrend when you exited the trend early - you are mad at yourself and you are trying to take out your anger on the market. Same way people will be angry at themselves and yell at the people around them. You want the market to give to you what you couldn't do for yourself. Best way to counter this -
1) Realize you have this tendency (we pretty much all do - though I conquered it in my human relationships long ago, it took a while to recognize and conquer it in my "market relationship.")
2) In trading don't be afraid to jump back on the trend, even if you lost a few points of the trend by premature exit. Think of it as part of your first trade.
3) Even better, exit only part of your position with a target, and use a trailing stop on the other part. Then when you realized the trend is continuing, it is easier to add more positions.
Part of successful trading is the painful process of self examination. Why did I do that? How can I stop? You are on the right track by asking.
Good luck.
mBear