Skip to content

CMB (China Merchants Bank)

About This Page

What: CMB BST (Bank-Securities Transfer) channel-side Socket protocol specification + moomoo-side adaptation logic Audience: PMs understanding integration details / Developers locating code / Operations understanding bank characteristics Prerequisites: Bank Capability Matrix · BST OverviewReading time: 8 minutes Owner: Deposit & Withdrawal Product Team

Key Takeaway: CMB uses SM2-encrypted Socket bidirectional links for second-level BST, making it the most protocol-complex but fastest-responding of the three BST banks.


Capability Overview

CapabilitySupportedProtocol/ChannelCore Service
Deposit (BST)Binary Socket bidirectional linkcmb_stock_trans Entry Server
Withdrawal (BST Auto)Binary Socket bidirectional linkcmb_stock_trans Exit Server
SM2 National CryptoSM2 Signature + EncryptionBuilt-in crypto module
eDDA/eDDI
FPS

CMB is one of moomoo's core BST channels, using dedicated Socket bidirectional persistent connections for real-time deposit notifications and withdrawal instruction delivery. Supports SM2 national cryptography to ensure fund instruction security.


Core Parameters Quick Reference

ParameterValueDescription
IMPORT_BANK_ID7System bank identifier (CMBCCHINA)
TransType102 (BST) / 205 (Regular)BST / Regular deposit types
AUTO_SETTING_ID2Limit configuration ID in auto_settings table
Protocol TypeBinary SocketFixed byte-length message frames
EncryptionSM2 National CryptoOptional, default 'N' (unencrypted)
Communication ModeBidirectional persistent connectionEntry Server + Exit Server

Channel Interface Overview

Protocol Architecture

DimensionDescription
Protocol TypeBinary Socket (fixed byte-length message frames)
EncryptionSM2 National Crypto (optional, default 'N' unencrypted)
Data FormatBinary (fixed-length fields, ASCII encoding)
Communication ModeBidirectional persistent connection (Entry Server receives + Exit Server sends)
Heartbeat0009/1009 and 0010/1010 bidirectional heartbeat keepalive
Connection ManagementAuto-switch to backup Exit Server on disconnect

Message Frame Structure

Each Socket message consists of a fixed-format header + variable-length business data:

PartLengthFormatDescription
Encryption Type1 bytechar'N' = unencrypted, 'Y' = SM2 encrypted
Total Packet Length2 byteslittle-endian uint16Total message frame length
Signature64 bytesbinarySM2 digital signature (blank-padded when unencrypted)
Command Code4 bytesASCIIe.g., "0001", "4001"
TX Packet Length2 byteslittle-endian uint16Business data length
Header Total73 bytes
Business DataVariablebinaryFixed-length fields concatenated

Byte Order Note

Packet length fields use little-endian byte order. Pay attention to encoding/decoding direction during development.


Channel-Side Interface Details — Complete Command Code Table

Login & Authentication

Command CodeDirectionMessage NamePurpose
0001Broker→BankBrokerageLoginToBankReqBroker logs into bank, establishes Entry link
1001Bank→BrokerBrokerageLoginToBankRspLogin response, returns auth result
0002Bank→BrokerBankLoginToBrokerageReqBank logs into broker, establishes Exit link
1002Broker→BankBankLoginToBrokerageRspBank login response
0003Broker→BankBrokerageLoginoutReqBroker initiates logout
1003Bank→BrokerBrokerageLoginoutRspLogout confirmation response

Password & Configuration

Command CodeDirectionMessage NamePurpose
0004/1004BidirectionalModifyPwdModify communication password
0005/1005BidirectionalChangeDateModify reconciliation date

Heartbeat Keepalive

Command CodeDirectionMessage NamePurpose
0009/1009Broker→BankKeepaliveBroker-side heartbeat (moomoo initiated)
0010/1010Bank→BrokerKeepaliveBank-side heartbeat (CMB initiated)

Bidirectional heartbeat ensures connection survival. If either side times out without receiving a heartbeat, the connection is deemed broken, triggering reconnection.

Customer Management

Command CodeDirectionMessage NamePurpose
2001/3001Bank→BrokerGetCustmorInfoBank queries customer info at broker
2002/3002Broker→BankNotifyCustmorResultNotify customer verification result (account opening/verification)
2003/3003Bank→BrokerCancelCancel customer's BST authorization

Fund Transfer (Core)

Command CodeDirectionMessage NamePurpose
4001/5001Bank→BrokerBankMarginInDeposit notification — Bank informs broker that a customer transferred funds in
4002/5002Broker→BankBrokerageMarginOutWithdrawal instruction — Broker instructs bank to transfer funds out to customer
4003/5003Bank→BrokerBankMarginOutWithdrawal result notification — Bank informs withdrawal processing result
4004/5004Broker→BankBankMarginOutRejectReject withdrawal — Broker rejects bank-side initiated withdrawal request

Reconciliation

Command CodeDirectionMessage NamePurpose
6001/7001BidirectionalMarginCheckReconciliation request initiation
6011/7011Bank→BrokerBankMarginInListDeposit reconciliation list
6013/7013Bank→BrokerBankNewCustmoerListNew customer list
6014/7014Bank→BrokerBankCancelListCancelled authorization customer list
6015/7015Bank→BrokerBankMarginOutListWithdrawal reconciliation list
6003/7003Broker→BankNewCustmoerCheckNew customer reconciliation confirmation
6004/7004Broker→BankCancelCheckCancelled authorization reconciliation confirmation
6005/7005Broker→BankMarginOutCheckWithdrawal reconciliation confirmation

Core Interface Field Details

4001 BankMarginInReq (Deposit Notification)

Bank notifies broker of a deposit credited — the core BST deposit message.

FieldLengthTypeDescription
m_brokerage_custmor_id20BstringBroker customer ID. Value: moomoo UID
m_bank_custmor_id16BstringBank customer ID. Value: Bank card number
m_currency3BstringCurrency. Value: HKD / USD / CNH
m_amount20BstringAmount. e.g., "50000.00"
m_tx_date8BstringTransaction date. Format YYYYMMDD
m_tx_time6BstringTransaction time. Format HHMMSS
m_tx_seq16BstringTransaction sequence. Unique identifier (dedup key)
m_reconciliation_date8BstringReconciliation date. Format YYYYMMDD
Field Encoding Notes

All fields are fixed-length ASCII strings, right-padded with spaces. Amount field includes decimal point, e.g., "50000.00" padded with spaces to 20 bytes. Currency is strictly 3 bytes: HKD, USD, CNH.

4002 BrokerageMarginOutReq (Withdrawal Instruction)

Broker sends withdrawal instruction to bank, transferring customer funds from securities account back to bank account.

FieldLengthTypeDescription
m_brokerage_custmor_id20BstringBroker customer ID. moomoo UID
m_bank_custmor_id16BstringBank customer ID. Bank card number
m_bank_custmor_name20BstringBank customer name. Used for bank-side verification
m_currency3BstringCurrency. HKD / USD / CNH
m_amount20BstringAmount. Withdrawal amount
m_tx_date8BstringTransaction date. Format YYYYMMDD
m_tx_time6BstringTransaction time. Format HHMMSS
m_tx_seq16BstringTransaction sequence. Unique identifier
m_reconciliation_date8BstringReconciliation date. Format YYYYMMDD

Common Response Fields

FieldLengthTypeDescription
m_rsp_code4BstringResponse code, "0000" = success

moomoo-Side Adaptation

Entry/Exit Server Bidirectional Architecture

CMB BST uses a bidirectional persistent connection architecture. moomoo deploys two Servers to handle inbound and outbound messages respectively:

ServerProcess NameResponsibilityConnection Direction
Entry Serverentrance_businessReceives messages from bank (deposit notifications, reconciliation lists etc.) -> forwards to CRMBank -> moomoo
Exit Serverexit_businessReceives CRM withdrawal instructions -> sends to bankmoomoo -> Bank

Disconnect handling: Exit Server supports backup addresses. When the primary connection drops, it auto-switches to the backup exit_server address, ensuring withdrawal instructions are not interrupted.

SM2 National Crypto Encryption Flow

CMB BST supports SM2 national crypto for message signing and encryption, ensuring fund instruction security.

Encryption Configuration
  • Encryption type field = 'Y' enables SM2
  • Default is 'N' (unencrypted), can be enabled as needed
  • Certificate files located in cmb_stock_trans/conf/ directory

Deposit: BST Real-time Deposit

Deposit Flow

The biggest advantage of BST deposits is real-time certainty: the bank directly provides customer ID and amount, eliminating the need for fuzzy matching like regular bank transfers.


Withdrawal: BST Auto Withdrawal (auto_bs)

Withdrawal Flow

Processing Hours

CurrencyProcessing HoursNotes
HKD / USDTrading days 08:40 ~ 15:59Full trading day
CNHTrading days 08:40 ~ 10:59Morning only, not available in afternoon
Margin withdrawalTrading days 08:40 ~ 10:59Same window as CNH

CNH Withdrawal Time Restriction

The CNH (offshore RMB) withdrawal window is only until 10:59 AM, much shorter than HKD/USD. Operations and users should note to initiate CNH withdrawals within this window; timeouts will be deferred to the next trading day.

CNH Withdrawal Restrictions

The calcMethod() method has additional restrictions for CNH:

  • CNH + non-Hong Kong bank -> method = null (not supported)
  • i.e., CNH withdrawal to Mainland bank card = not supported
  • CNH only supports withdrawal to Hong Kong local CMB accounts

Withdrawal Cancellation Rules

ScenarioCancellableCondition
Non-trading hours (< 08:20 or >= 16:00)Unconditionally cancellable
Trading day 08:20 ~ 16:00✅ / ❌Cancellable if >= 10 minutes before scheduled execution
Non-trading dayUnconditionally cancellable

Why the 10-minute restriction during trading hours? Once a withdrawal instruction enters the bank's processing queue, it cannot be recalled. The 10-minute buffer ensures the cancellation request arrives before the bank actually executes.

Callback Result Codes

resultMeaningSystem ActionManual Needed
0SuccessTask status -> DONE
-5TimeoutAuto-switch to backup exit_server and retry
-6Bank rejectedTask status -> Exception✅ Manual processing
Timeout Retry Mechanism

When result = -5 (timeout) is received:

  1. Log timeout event for current exit_server
  2. Switch to backup exit_server address
  3. Resend withdrawal instruction using the same m_tx_seq
  4. If backup exit_server also times out, mark as exception and await manual processing

Withdrawal Limit Configuration

CMB BST withdrawal limits are configured via the auto_settings table (WHERE id = 2):

FieldMeaningDescription
hk_max_amountPer-transaction maximumRejected if exceeded
hk_alarm_amountAlarm amountTriggers alert but does not block
hk_stop_amountCircuit breaker amountSuspends auto-withdrawal if exceeded

Three-tier threshold logic:

  • Amount <= alarm_amount: Normal auto-processing
  • alarm_amount < Amount <= max_amount: Auto-processing + triggers alert notification
  • Amount > max_amount or cumulative > stop_amount: Suspend auto-withdrawal, route to manual approval

Exception Scenarios & Alerts

Socket Disconnection

Alert ItemSeverityResponse TimeDescription
Entry Server disconnectCriticalWithin 15 minCannot receive deposit notifications
Exit Server disconnectCriticalWithin 15 minCannot send withdrawal instructions
Bidirectional heartbeat timeoutWarningWithin 30 minMay disconnect soon

Socket disconnection is one of the most critical alerts — during disconnection, all BST deposit notifications and withdrawal instructions are interrupted. The system will auto-attempt reconnection, but if not recovered within 15 minutes, developer intervention is needed.

Common Exception Handling

Exception ScenarioSymptomResolution
Socket disconnectDeposit/Withdrawal interruptedAuto-reconnect; manual intervention if not recovered in 15 min
SM2 signature verification failureMessage rejectedCheck if certificate expired or replaced
Withdrawal timeout (result=-5)Bank not respondingAuto-switch to backup exit_server
Bank rejected (result=-6)Withdrawal failedManually verify reason then retry or refund
Reconciliation mismatchDeposit/Withdrawal amounts inconsistentOperations investigates discrepancy, contacts CMB for reconciliation
CNH out-of-window withdrawalWithdrawal rejectedDefer to next trading day morning

Bilateral Function Mapping Matrix

FunctionChannel-Side (CMB)moomoo-SideDescription
Login AuthenticationBidirectional handshakeEntry/Exit Server0001-1003, establishes bidirectional link
Heartbeat KeepaliveBidirectional heartbeatEntry/Exit Server0009-1010, every 30s
Deposit Notification4001 BankMarginInEntry -> CRMm_brokerage_custmor_id etc., real-time deposit
Withdrawal Instruction5002 receives and executesCRM -> Exit -> Bankm_amount / m_currency etc., auto withdrawal
Withdrawal Result4003 BankMarginOutEntry -> CRMresult code, callback notification
Reconciliation6xxx seriesEntry/ExitMultiple lists, daily reconciliation
EncryptionSM2 verify and decryptSM2 sign and encrypt64B signature in message header, optional

Cron Jobs

TaskFrequencyDescription
Heartbeat checkEvery 30 secondsEntry/Exit Server bidirectional heartbeat
Disconnect checkEvery 5 minutesCheck Socket connection status, alert on anomaly
Reconciliation initiationDaily after market closeInitiate 6001 reconciliation request
Reconciliation verificationDaily T+1Compare deposit/withdrawal/customer lists

Change Guide

Change RequirementLocationDescription
Modify withdrawal limitsauto_settings WHERE id = 2Adjust max/alarm/stop three-tier thresholds
Modify processing hoursexit_business -> time period configAdjust processing windows per currency
Modify CNH restrictionscalcMethod() -> CNH judgment logicModify CNH withdrawal bank/region restrictions
Modify cancellation rulesWithdrawal cancellation logic -> time checkAdjust 10-minute buffer period
Replace SM2 certificatecmb_stock_trans/conf/Replace public/private key files and restart service
Adjust heartbeat intervalcmb_stock_trans -> keepalive configModify heartbeat frequency
Add new command codecmb_stock_trans/comm/pact.hProtocol definition file
Modify Entry Server logiccmb_stock_trans/entrance_business/Inbound message processing
Modify Exit Server logiccmb_stock_trans/exit_business/Outbound message processing
Adjust backup exit_serverExit Server configModify backup address list

Code Location Quick Reference

ModulePathDescription
Protocol definitionscmb_stock_trans/comm/pact.hAll command codes and message structure definitions
Entry Servercmb_stock_trans/entrance_business/Inbound message receiving and forwarding
Exit Servercmb_stock_trans/exit_business/Outbound message sending (withdrawal instructions)
SM2 Encryptioncmb_stock_trans/ built-in moduleSign / Encrypt / Decrypt
Limit configauto_settings table id = 2Database configuration
Withdrawal channelwithdraw/.../Method.php -> auto_bsWithdrawal method registration

Comparison with Other BST Banks

DimensionCMBCMBCAirstar
ProtocolBinary Socket
EncryptionSM2 National Crypto
Connection ModeBidirectional persistent
Deposit✅ Real-time notification
Withdrawal✅ auto_bs
CNH Support✅ (Morning only)
ReconciliationAuto reconciliation

BST Advantage

Compared to regular bank transfer deposits that require fuzzy matching, the biggest advantage of BST is certainty — the bank directly provides customer ID and amount, no matching engine involvement needed, deposits credited in real-time.


Top 3 Customer Complaints

#User FeedbackCauseCS Response
1"BST withdrawal timed out"Socket connection jitter, callback code -5"Your withdrawal is being processed. The system has auto-retried, please check the result shortly."
2"BST withdrawal rejected"Callback code -6, bank-side rejection"The bank was temporarily unable to process your withdrawal. Please try again later or contact support."
3"Why can't I withdraw via CMB"BST authorization not active or expired"Please confirm your BST authorization status is active. If expired, please re-sign the agreement."

After Reading

I want to...Go to
Understand the overall BST architectureBST Overview
See CMB's position among all banksBank Capability Matrix
Understand withdrawal channel execution detailsChannel Execution Manual
Understand withdrawal approval rulesWithdrawal Rules & Approval
Look up TransType and Bank ID mappingDeposit Rules Quick Reference
Look up error codes and status codesUnified Error Code Center
Understand other deposit matching logicMatching & Auto-Deposit
Was this page helpful?

内部业务文档 · 仅限 moomoo 团队使用