This life is a test and the test is not over till death. So anything you do till you death, (and three thing after that) goes in your "book of deeds" for which you are accountable.
The other thing to note is that not all sins are equal. It a great blessing of God that if we keep away from major sins, He will wash away our minor ones.
Thus a major sin done in the end of life can over-weigh all the good deeds that you have done. So you have to be careful till the very end.
The first major sin is associating partners with God. It will not be forgiven (without repentance). All the other sins can be forgiven. You can find the list of others in Quran.
Genuinely repenting a sin, erases it. If you do a sin and repent immediately, then God has taken it upon Himself to forgive it. If you delay it, till you see you death in front and then repent, then it will not be accepted. If you delay it, but not till your death, then He may or may not forgive it. We can only hope that He does. If the sin is done against another person then in addition to repenting to God, you should compensate it to the person, otherwise your repentance is not considered genuine.
One thing to note that God is most forgiving, but also just. He is wise and his final decision will show all his attributes. If forgiving a sin might cause injustice to another person, He may choose not to forgive it. So please very careful of the sins done that cause injustice to other as that person will not be as forgiving as God especially on the day of judgment, where the only things to "buy and sell" will be your deeds.