Why did China have a favorable balance of trade with Great Britain until the Second Opium War?
Through its long history, China has often considered the rest of the world to be barbaric and has traditionally limited trade; in the 19th Century, this became a major problem.
The traditional Chinese view of outsiders was that they were inferiors and barbarians. While civilizations in Europe and the Middle East had to deal with rival cultures, China spent almost 2,000 years in relative isolation. Notwithstanding occasional exceptions, input from outside their cultural borders was regarded as disruptive and therefore unwelcome.
Starting with the Portuguese in the early 16th Century, Europeans increasingly appeared in Chinese ports and were eager to acquire silk, ceramics, tea and other goods. However, Chinese officials turned up their noses at most Western goods... except for silver. Besides, in Ming China (1368-1644) and Qing China (1644-1911), silver was practically the only internal medium of exchange and the appetite for it was insatiable.
In the early 19th Century, the Western demand for Chinese products grew enormously, but Qing-Era mandarins refused to accept any goods in return except for silver. As a result, there was a growing shortage of silver in Europe and the Americas which caused major economic difficulties. The British-owned East India Company did their homework, and found that there was an appetite in China for opium... and fed it.
Like crack and crystal meth today, the increasing flood of opium into China was causing all manner of social problems (including corruption with colluding local officials). Attempts by China's rulers to curtail this flood -- while still refusing other forms of trade -- irritated the British. So too did the official Qing position that the British and all other foreigners were vassals and barbarians. As China attempted to shut off the flow of opium, Britain and other trading countries resisted every measure. Conflict became inevitable.