Stalin was a loyal Bolshevik, a member since the party first formed in 1903, whereas Trotsky was not a member of the party until 1917, when he fixed his relationship with Lenin and became his right-hand man.
In 1923, before Lenin's death in 1924, Stalin fell out with Lenin, which lowered his chances of becoming the next leader.
In 1908, Stalin was called to carry out military defense, but didn't, which was disliked by Lenin.
In 1918, Trotsky led the Red Army to victory in Civi War, proving him to be a capable leader.