Bank of America secretly routed trades in order to enrich clients like Bernie Madoff while misleading other customers through “masked” messages for five years through 2013, according to the $45 million settlement with New York Attorney General Eric Schneiderman on Friday.

BofA, which is led by CEO Brian Moynihan, sold stock at discounted prices to ultra-fast electronic trading companies, even though they told clients that they were being routed to public markets at fair prices by the bank’s in-house brokers, according to the settlement.

“Bank of America Merrill Lynch went to astonishing lengths to defraud its own institutional clients about who was seeing and filling their orders, who was trading in its dark pool, and the capabilities of its electronic trading services,” Schneiderman said in a statement.

For five years, the bank routed about 4 billion trades to giant electronic traders like Citadel Securities, D.E. Shaw, Getco, Knight, Two Sigma, Sun Trading, ATD and Madoff Securities, according to the settlement.

The bank secretly routed the trades “based on other revenue opportunities currently being discussed with them,” the head of electronic trading said in the settlement.

But while the traders were getting stock orders directed to them, the bank’s executives had purposely programmed electronic statements that made it seem like they were handled internally — a process known as “masking,” the settlement said.

It was so important to keep the ruse going that the head of electronic trading emailed the then-COO in July 2008 to say that there was a glitch that would show who had actually been trading those shares.

“[We] have to lock this down asap,” the electronic trading head wrote. “It’s a huge business risk to have these invoices include ‘Trading Partners’ as a line item.”

The COO agreed and confirmed that the lines were “deleted.”

Bank of America admitted to the wrongdoing in the settlement.

“The settlement primarily relates to conduct that occurred as long as 10 years ago,” William Haldin, a bank spokesman, said in a statement. “At all times we met our obligation to deliver the best prices to clients. About five years ago, we addressed the issues concerning communicating to clients about where their trades were executed.“