Brendan McDermid/Reuters

When Thomas M. Joyce arrived at Knight Capital’s Jersey City offices on Sunday, the fate of his company and the legacy of his long Wall Street career were in jeopardy. His lawyers were preparing a potential bankruptcy filing throughout the day, according to people briefed on the matter, and the company’s last hope rested with an eclectic group of investors.

But by 9 p.m., when Mr. Joyce departed for home while lawyers reached a deal over a meal of Chinese food, the crisis was largely contained. The Knight Capital Group, the company that Mr. Joyce nurtured into one of the most powerful brokerage firms on Wall Street, had just survived the most harrowing week in its 17-year history.

Hobbled by recent knee surgery and haggard from several sleepless nights, Mr. Joyce on Monday announced that Knight Capital had struck a $400 million deal with the group of investors, staving off collapse after a devastating trading mishap.

The rescue package, which was assembled and led by the Jefferies Group, includes investments from TD Ameritrade and the Blackstone Group. Getco, a high-speed trading firm, and the investment bank Stifel, Nicolaus & Company, also invested.

The group appears poised to cash in on the deal. The investors are afforded the right to buy more than 260 million shares, or 73 percent of the firm, at $1.50 a piece. Before the trading blunder, the firm’s shares traded above $10.

Timeline: Trading Errors

Under the terms of the deal, Knight will also expand its board by adding three new members from the investor group. Jefferies, which led the group with a $125 million investment, will take one seat.

“The array of participants in this capital infusion underscores Knight’s critical role in the capital markets,” Mr. Joyce, the firm’s chairman and chief executive, said on Monday.

The lifeline capped a rapid recovery for a firm that, just days ago, was on the brink of collapse.

On Wednesday, Knight Capital sustained a $440 million trading loss stemming from a technology error that generated erroneous orders to buy shares of major stocks. The orders affected the shares of 148 companies, including Ford Motor, RadioShack and American Airlines, sending the markets into upheaval.

Despite the embarrassing setback, investors saw plenty of potential in Knight, a sharp contrast from times when other Wall Street firms — like Lehman Brothers and more recently, MF Global — faced extinction.

Knight, stumbling at a healthier time for the financial industry, had more choices. Mr. Joyce fielded about 100 phone calls from potential buyers, who coveted Knight’s giant presence in the profitable electronic trading game. In the first half of the year, Knight accounted for 11 percent of all stock trading in the United States.

Still, the firm faces significant challenges. A company built on the strength of its technological prowess, Knight suffered a major electronic mishap that rattled investor confidence.

And the deal comes at a cost as it will significantly dilute existing shareholders of the company. Shares of Knight Capital fell more than 24 percent on Monday.

Most of the losses will be borne by mutual funds that owned 54 percent of Knight’s outstanding shares before the trading errors, according to data from Morningstar. Fidelity and its mutual funds were the largest owners of Knight shares, holding 15 percent of the company, the fund manager reported in its most recent filings.

But the individual who has lost the most money since the problems last Wednesday may be Mr. Joyce. A longtime trader who rose to prominence at Merrill Lynch and at the Sanford C. Bernstein & Company, his 1.2 million shares dropped in value by about $9 million from last Wednesday to Monday.

Knight Capital also faces heavy regulatory scrutiny. The Securities and Exchange Commission is examining potential legal violations as it pieces together the firm’s missteps.

The New York Stock Exchange said on Monday it “temporarily” reassigned the firm’s market-making responsibilities for more than 600 securities to Getco, the trading firm that also invested in Knight. Market makers buy and sell securities on behalf of clients.

The problems for Knight Capital began on Wednesday when the New York Stock Exchange’s opening bell rang. The Exchange opened a new trading platform — and Knight had tweaked its computer coding to push itself onto the system then.

But when Knight’s new system went live, the firm “experienced a human error and/or a technology malfunction,” the firm explained in a regulatory filing on Monday.

Chaos ensued. The error caused Knight to place unauthorized offers to buy and sell shares of big American companies, driving up the volume of trading and causing a stir among traders.

Mr. Joyce, who had knee surgery that week, went into work on crutches.

Knight later had to sell the stocks that it accidentally bought, prompting the $440 million loss. The loss would drain Knight’s capital cushion and cause “liquidity pressures,” the firm said in the filing.

The firm also consulted restructuring lawyers at Kirkland & Ellis on a potential Chapter 11 filing, according to people with direct knowledge of the matter who did not want to be identified because the negotiations were not public. The lawyers worked on the filing until about 4 a.m. on Monday, when a deal was mostly done.

As the firm’s health soured, the S.E.C. kept a closer watch. The agency dispatched officials to the firm’s Jersey City offices. In the agency’s Washington headquarters, senior officials worked through the night in offices without air-conditioning to monitor the firm’s liquidity position. The office’s air-conditioning bad been programmed to shut off before midnight as an energy-saving measure.

But events soon turned in the firm’s favor. Knight secured emergency short-term financing that allowed it to operate on Friday. Some of the firm’s biggest customers, including Scottrade, said they had resumed doing business with Knight.

Investor interest was heating up, too. Citadel, a big hedge fund and trading firm, was interested in buying portions of the company. Jefferies was aiming to build a coalition of investors. By Friday night, Knight aligned with Jefferies, accelerating negotiations into the weekend.

Jefferies, which signed a document outlining the terms of the deal on Saturday night, had little trouble recruiting other investors. TD Ameritrade, the online brokerage house, ramped up its interest on Saturday after concluding the terms of the deal were reasonable, according to the people briefed on the matter.

One of the last to join was Blackstone, though it was well aware of Knight’s business. The private equity company first approached Knight about a potential takeover just months ago, a person briefed on the matter said. Blackstone’s chief financial officer, Laurence Tosi, knew Mr. Joyce from their days together at Merrill Lynch.

On Sunday, the deal teams were split into various locations. Some investors, including TD Ameritrade, remained with Mr. Joyce in Jersey City poring over Knight’s documents. Others huddled at the Manhattan offices of White & Case, the law firm representing Jefferies in the deal.

In the evening hours, a deal looked promising. While firms typically need a shareholder vote to bless such a deal, the exchange allowed Knight to proceed because the firm’s survival was at stake. The S.E.C. was monitoring Knight’s compliance with capital rules. Robert W. Cook, the head of the agency’s division of trading and markets, spent his birthday on Sunday tracking the final stages of the deal.

By 9 p.m., when Mr. Joyce left his offices, the deal was all but signed.

Jefferies would invest $125 million, Blackstone and Getco would spend $87.5 million and TD Ameritrade contributed $40 million. The payments came in waves over the next several hours, with the last few dollars rolling in just before the trading opened on Monday morning.

Michael J. de la Merced contributed reporting.