Hi I have a dc motor and I was wondering if there some kind of way I can control its speed by code?its connected with an external power source and I control it by code with a transistor:

Yes, that circuit will work fine with an Arduino. Note the ground wire goes to both the external power source and the arduino ground pin. Be sure the transistor you use is rated will above the maximum current and voltage that the motor requires.

You can control the speed of the motor using the Arduino analogWrite(pin,speed) command. Where pin is the correct output pin to use (see link below) for PWM outputs and speed is 0-255, where 0 is full stop, and 255 is max rpm that the external voltage allows the motor to turn at.

Yes it is confusing. The Arduino team decided in their wisdom to name the PWM output command "analogWrite" when it is indeed using a digital output pin in a PWM output mode, giving a quasi analog output capability. Go by the reference given for analogWrite commands and wire it to an available PWM digital output pin.