NEW YORK — Rapper DMX was ordered confined to his suburban New York City home Friday by a judge who said he repeatedly violated bail conditions on tax fraud charges.

U.S. District Judge Jed Rakoff also said the rapper must wear an electronic bracelet and ask his permission at least a week in advance if he wants to travel.

“A very strong argument could be made for keeping him in jail,” Rakoff said, but he added that judicial authorities are sometimes too quick in the United States to incarcerate people before trial.

The judge described several times DMX has been convicted of drug or gun possession crimes since 2002 but said he has largely avoided jail time and maybe only learned that “he’s free to thumb his nose at the court” and Pretrial Services officers because he knows that his lawyer, Murray Richman, will always get him out of trouble.

Rakoff said he was told DMX, 46, traveled to St. Louis and Chicago without permission and tested positive for cocaine since his arrest last month. The judge said DMX then rejected a Pretrial Services officer’s offer of drug treatment, telling the officer he would remain drug-free on his own. In subsequent tests, he also tested positive for marijuana and opiates, the judge said.

“The violations are very troubling,” the judge said. “In addition, it sounds like he’s a liar.”

DMX’s lawyer demurred and said the drug tests weren’t telling the whole story.

“He’s a very rational, decent, human being,” Richman told Rakoff. The lawyer said that drugs can linger in the body for a month even after someone stops using them and that DMX had an opiates prescription for pain relief.

DMX, whose given name is Earl Simmons, hugged friends outside the courtroom and called it a “blessing” that he was free as he walked away from the courthouse to a hot dog stand, where he ate a hot dog and posed for pictures.

When he was asked how he would celebrate his freedom, the multiplatinum hip-hop artist said: “That’s a celebration right there. Just being in there and being able to walk out.”

Prosecutors say DMX owes $1.7 million in taxes. They say he moved hundreds of thousands of dollars in music royalty income into his managers’ bank accounts, letting them pay him in cash so he could hide it from the Internal Revenue Service. He has pleaded not guilty and declined to comment on the charges outside court Friday.

His songs include the 2003 hit “X Gon’ Give it to Ya.”