This section of Psalm 18:20-29, we find David explaining the reasons God has rewarded him. This isnt David boasting on his achievements or his character apart from the power of God. As we can see by how this passage ends, David is aware that he cannot take credit for it. David also makes a statement were he refers to "mine" iniquity. This, I believe, is Davids acknowledgement similar to Galatians 5:16 where Paul says to walk in the Spirit and you will not fulfill the lusts of the flesh. David expresses that iniquity still dwells within himself but by the power of God he has kept himself from fulfilling it. As should we.

Psalm 18:20-29
King James Version
20 The Lord rewarded me according to my righteousness; according to the cleanness of my hands hath he recompensed me.

21 For I have kept the ways of the Lord, and have not wickedly departed from my God.

22 For all his judgments were before me, and I did not put away his statutes from me.

23 I was also upright before him, and I kept myself from mine iniquity.

24 Therefore hath the Lord recompensed me according to my righteousness, according to the cleanness of my hands in his eyesight.

25 With the merciful thou wilt shew thyself merciful; with an upright man thou wilt shew thyself upright;

26 With the pure thou wilt shew thyself pure; and with the froward thou wilt shew thyself froward.

27 For thou wilt save the afflicted people; but wilt bring down high looks.

28 For thou wilt light my candle: the Lord my God will enlighten my darkness.

29 For by thee I have run through a troop; and by my God have I leaped over a wall.