Native SFTP Client in MQL5: Uploading Trade Reports over SSH Without External Tools
Contents
- Introduction
- What the client must support
- Cryptography in plain MQL5
- The handshake and host key pinning
- Reading packets safely
- Uploading through a temporary file
- The report EA and the uploader service
- Setting it up
- Testing the client
- Six backtests, one upload session
- Limitations
- Conclusion
Introduction
Sooner or later someone asks for your trade reports on their server—a risk desk, a prop firm, or your own VPS. Often the only door into that server is SFTP. MQL5 has WebRequest for HTTP and SendFTP for plain FTP, but nothing for SSH, so people end up running a WinSCP script next to the terminal.
This article removes that second program. The client below speaks SSH-2 and SFTP version 3 over the terminal's own sockets, with SHA-512, AES-128, X25519 and Ed25519 written in plain MQL5. An EA writes one CSV report for each day on which at least one of its trades closed, a service uploads the finished files, and six backtests check that the server ends up with the same trade count and net profit as the tester.
What the client must support
SocketCreate and SocketConnect give a raw TCP stream from an EA, a script or a service, but not from an indicator. The host must be in the list of URLs allowed for WebRequest (Tools > Options > Expert Advisors), or the connection is refused. Everything above TCP is ours to write.
The client offers a single suite: curve25519-sha256 for the key exchange, ssh-ed25519 for the host key, aes128-ctr for the cipher, hmac-sha2-256 for integrity and no compression. OpenSSH offers all of them in its default configuration, but a server's own policy can switch any of them off. The client then refuses with a message naming the missing algorithm (e.g., "server does not allow aes128-ctr"). Login is by password or by an unencrypted OpenSSH Ed25519 key file; password login was confirmed in the MQL5 runtime, and Ed25519 key login is implemented in the code but so far confirmed only by the C++ sandbox build, not by a run in the MQL5 runtime. Keyboard-interactive login and passphrase-protected keys are not supported.
The EA never touches the network. When a trade closes, it appends a row to that day's file in a work folder. When the day changes, it moves the finished file to an outbox; days without a closed trade produce no file. A service uploads whatever appears in the outbox, so a slow server cannot stall OnTick. Both programs use Common\Files, which lets the Strategy Tester and the live terminal share the same outbox. File names include BT or LIVE, the symbol, the timeframe and the date (e.g., Report_BT_XAUUSD_H1_20260701.csv). This keeps different symbols and timeframes in separate files, and a new tester run replaces its own earlier files. File names do not include the account or the magic number, so several terminals, or several copies of the EA on the same symbol and timeframe, must use different InpReportRoot folders.
Report pipeline

1. The EA appends each closed trade to that day's file in work\ and moves the file to outbox\ with FileMove when the day ends; days without a closed trade have no file. The SftpUploader service uploads each outbox file over SSH, logs it in upload_log.csv and moves it to sent\. All folders sit under Common\Files\NativeSFTP.
Cryptography in plain MQL5
Five primitives carry the protocol, and only SHA-256 comes from CryptEncode: SHA-256 for the handshake hash and key derivation, HMAC-SHA256 for packet integrity, AES-128 in counter mode for encryption, X25519 for the shared secret, and Ed25519 (with SHA-512 inside) for signatures. The Curve25519 arithmetic follows the TweetNaCl layout of sixteen 16-bit limbs in long values. Carries go through a helper that floors explicitly, so nothing depends on how a right shift treats negative numbers.
AES is written by hand too. CryptEncode offers AES, but its documentation does not state the block mode, and SSH needs a counter that runs on from one packet to the next. Counter mode needs only the forward cipher:
//+------------------------------------------------------------------+ //| XOR len bytes of buf (starting at off) with the keystream | //+------------------------------------------------------------------+ void CSshAesCtr::Process(uchar &buf[],const int off,const int len) { //--- encryption and decryption are the same operation in CTR mode for(int i=0;i<len;i++) { if(m_ks_pos==16) { //--- refill the keystream, then increment the 128-bit counter m_aes.EncryptBlock(m_ctr,0,m_ks,0); for(int j=15;j>=0;j--) { m_ctr[j]=(uchar)(m_ctr[j]+1); if(m_ctr[j]!=0) break; } m_ks_pos=0; } buf[off+i]=(uchar)(buf[off+i]^m_ks[m_ks_pos]); m_ks_pos++; } }
The script SftpSelfTest checks each primitive against published vectors. It runs 16 checks: SHA-256, SHA-512 (one and two blocks), HMAC-SHA256 (RFC 4231), AES-128 (FIPS-197), AES-128-CTR (SP 800-38A), four X25519 checks built on the RFC 7748 vectors, the RFC 8032 Ed25519 key and signature, verification of that signature, two rejection cases, and one check of the random generator. All 16 passed in all three sessions on my terminal.
That covers the primitives and nothing else. The random generator check only shows that two outputs differ, which says nothing about unpredictability. Constant-time behaviour is not shown either: the field arithmetic follows TweetNaCl's branch-free design, but timing and memory access in the MQL5 runtime were not measured. I also compiled the same .mqh files as C++ in a sandbox and compared them with the Python cryptography package on 1,123 random cases, with 0 mismatches. That checks the logic of the shared source, not the MQL5 runtime, whose integer types, overflow behaviour, I/O and timing could still differ.
Primitive timings in three terminal sessions

2. Single runs of SftpSelfTest on one laptop: session A at 14:53 (grey), B at 23:16 (blue), C at 23:37 (orange). Session A did not time RNG seeding, so that bar is absent. Bulk operations process 1 MiB.
Session A ran about twice as slow as B and C (AES 27.1 against 12.7 ms, X25519 2.0 against 0.9 ms), while B and C are close. Clock speed, power state or other load could explain it, and one run per session cannot separate them. A handshake requires RNG seeding, one X25519 exchange and one Ed25519 check: 0.9 + 0.9 + 1.7 = 3.5 ms in session B, or 1.6% of the 221.6 ms median handshake measured below.
The handshake and host key pinning
Message sequence of one upload session

3. Arrowheads show the direction of each message, and a grey arrow is the reply in a two-way step. The client checks the signature and the pinned fingerprint after KEX_ECDH_REPLY, then derives keys A to F. Every message after NEWKEYS is encrypted and authenticated.
Encryption alone does not stop a man-in-the-middle attack, since anyone can complete a key exchange with you. What proves you reached the right server is its host key, and the server proves it holds that key by signing the exchange hash H. The client checks the signature, then compares the key with a fingerprint you pin in the inputs:
//--- the server proves possession of the host key by signing H CSshReader sg; sg.Load(sig_blob); string sig_type=sg.Text(); uchar sig[]; sg.Str(sig); if(!sg.Ok() || sig_type!="ssh-ed25519" || !SshEd25519Verify(sig,h,host_pub)) return(Fail("host key signature is invalid: possible man-in-the-middle")); //--- pinning: refuse to continue unless the host key is the expected one if(m_pin=="") return(Fail("no fingerprint pinned; server presented "+m_fingerprint+" - verify it and set it in the inputs")); if(m_pin!=m_fingerprint) return(Fail("HOST KEY MISMATCH: expected "+m_pin+" but server presented "+m_fingerprint));
There is no "trust on first use". With an empty pin the client refuses to log in and prints the fingerprint in the format of ssh-keygen -lf, so you can check it on the server and paste it in.
The client also advertises strict key exchange. When the server agrees, sequence numbers restart at zero after each NEWKEYS and nothing else may come before it, which closes the prefix-truncation attack known as Terrapin. The client does not require it. If the server does not offer strict key exchange (e.g., OpenSSH before 9.6), the connection proceeds without that protection, so use a server that supports it if this matters to you. If the server re-keys mid-session, the same pin applies, and each direction switches to its new keys only at its own NEWKEYS. Swapping both at once breaks the MAC on whatever the server sends in between. In the sandbox, an OpenSSH server set to RekeyLimit 1M forced 21 key exchanges during 4 MB and 10 MB uploads, and both files arrived with matching hashes.
Reading packets safely
With hmac-sha2-256 the MAC covers the plaintext, so the length field has to be decrypted before the packet can be authenticated. That length is the only field used before the MAC check, and ReadPacket bounds it first: at least 5 bytes, at most SSH_MAX_PACKET (262,144 bytes), and a whole number of cipher blocks. The padding length and the payload are read only after the MAC matches:
//+------------------------------------------------------------------+ //| Read, decrypt and authenticate one packet; returns its payload | //+------------------------------------------------------------------+ bool CSshTransport::ReadPacket(uchar &payload[]) { //--- first block holds the length; decrypt it before trusting it int first=m_enc_in ? 16 : 8; uchar head[]; if(!RecvExact(head,first)) return(false); if(m_enc_in) m_cipher_in.Process(head,0,first); uint len=((uint)head[0]<<24)|((uint)head[1]<<16)|((uint)head[2]<<8)|(uint)head[3]; int block=m_enc_in ? 16 : 8; if(len<5 || len>SSH_MAX_PACKET || ((len+4)%block)!=0) return(Fail("invalid packet length "+IntegerToString(len))); //--- rest of the packet uchar rest[],pkt[]; int remain=(int)len+4-first; if(remain>0 && !RecvExact(rest,remain)) return(false); if(m_enc_in && remain>0) m_cipher_in.Process(rest,0,remain); ArrayResize(pkt,0); SshAppend(pkt,head); SshAppend(pkt,rest); //--- verify the MAC in constant time; only the bounded length is used before it if(m_enc_in) { uchar mac[]; if(!RecvExact(mac,32)) return(false); CSshWriter macin; macin.U32(m_seq_in); macin.Raw(pkt); uchar mac_data[],expect[]; macin.CopyTo(mac_data); SshHmacSha256(m_mac_key_in,mac_data,expect); if(!SshEqualCT(mac,0,expect,0,32)) return(Fail("MAC verification failed: data was altered in transit")); } m_seq_in++; //--- payload sits between the padding-length byte and the padding int pad=pkt[4]; int plen=(int)len-pad-1; if(plen<1) return(Fail("invalid padding length")); ArrayResize(payload,plen); ArrayCopy(payload,pkt,0,5,plen); return(true); }
The comparison runs in constant time. Flipping single bits through a proxy in the sandbox gave "host key signature is invalid" inside the handshake and "MAC verification failed" after it, during login, a directory request or an upload.
Uploading through a temporary file
A half-written report is worse than a missing one, because the reader cannot tell. Upload writes name.part with up to 16 pipelined writes of 32 KiB, ( SFTP_MAX_INFLIGHT =16 and SFTP_WRITE_CHUNK = 32768 in the attached .mqh), checks the size on the server, then moves the file onto the target name:
//+------------------------------------------------------------------+ //| Upload a byte array to remote_path: write remote_path.part with | //| up to SFTP_MAX_INFLIGHT pipelined writes, confirm its size, then | //| remove and rename it onto the target. The target name never | //| holds a partial file, but the swap is not atomic: name.part is | //| visible while it is written and the target is briefly absent | //+------------------------------------------------------------------+ bool CSftpClient::Upload(const uchar &data[],const string remote_path) { //--- refuse when the session is not ready if(!m_connected) return(Fail("not connected")); string part=remote_path+".part"; int total=ArraySize(data); //--- OPEN part file: write, create, truncate, mode 0644 uint id=m_next_id++; CSshWriter w; w.U32(id); w.Text(part); w.U32(SFTP_FXF_WRITE|SFTP_FXF_CREAT|SFTP_FXF_TRUNC); w.U32(SFTP_ATTR_PERMISSIONS); w.U32(0x1A4); if(!Send(SFTP_OPEN,w)) return(false); uchar handle[]; if(!ExpectHandle(id,handle)) return(false); //--- pipelined WRITE requests; replies must come back in send order, and a //--- reply with any other id stops the upload with an error uint pending[]; int pending_n=0; int offset=0; ArrayResize(pending,SFTP_MAX_INFLIGHT); while(offset<total || pending_n>0) { //--- keep the pipeline full while data remains while(offset<total && pending_n<SFTP_MAX_INFLIGHT) { int chunk=total-offset; if(chunk>SFTP_WRITE_CHUNK) chunk=SFTP_WRITE_CHUNK; uint wid=m_next_id++; CSshWriter wr; wr.U32(wid); wr.Str(handle); wr.U64((ulong)offset); wr.Str(data,offset,chunk); if(!Send(SFTP_WRITE,wr)) return(false); pending[pending_n++]=wid; offset+=chunk; } //--- collect the oldest reply uint code=0; string msg=""; if(!ExpectStatus(pending[0],code,msg)) return(false); if(code!=SFTP_FX_OK) return(Fail("write failed: "+msg)); for(int i=1;i<pending_n;i++) pending[i-1]=pending[i]; pending_n--; } //--- close, then confirm the server holds every byte if(!CloseHandle(handle)) return(false); bool exists=false; ulong size=0; if(!Stat(part,exists,size)) return(false); if(!exists || size!=(ulong)total) return(Fail("size check failed: sent "+IntegerToString(total)+" bytes, server has "+IntegerToString((long)size))); //--- swap the finished file into place if(!Remove(remote_path,true)) return(false); return(Rename(part,remote_path)); }
SFTP version 3 treats renaming onto an existing file as an error, so the old file is removed first. This is not an atomic replace. While the upload runs, name.part is visible in the remote folder, and between REMOVE and RENAME the target name does not exist at all. The guarantee is narrower: the target name never holds a partial file. Whoever reads the folder should skip *.part files and retry when a file is missing for a moment.
Two more limits apply here. The size check confirms the byte count, not the content. In transit every packet is covered by the MAC, but the code never reads the file back, so a strict check means comparing the server copy with the SHA-256 that the service logs, as shown in the setup section. Replies to the pipelined writes must also come back in the order they were sent. The OpenSSH sftp-server used here answers in order. A server that reordered replies would make the upload stop with an error naming the unexpected id. The reply would not be credited to the wrong write.
The report EA and the uploader service
The EA only exists to produce realistic files. It trades a 20-bar Donchian breakout on the bar close, with a stop at 2 ATR(14), a target at 2 times the stop and 0.5% of equity at risk. It lost money in all six runs below and is not offered as a strategy. Its profit and loss serve one purpose: the uploaded rows must sum to the tester's net profit.
That check found a trap in the Strategy Tester. When a test ends with a position open, the tester closes it before OnDeinit, and that closing deal does not reach OnTradeTransaction. With logging only in the event handler, the XAUUSD H1 run put 47 rows on the server against 48 trades, summing to −680.33 instead of −702.32. The missing row is −702.32 − (−680.33) = −21.99. Reconciling history in OnDeinit does not help if you filter by the closing deal's magic number, because the tester's close carries no magic of ours. Ownership has to come from the deal that opened the position:
//--- ownership comes from the opening deal: the tester's end-of-test //--- close carries no magic of ours, but the position it closes is ours double open_price=0.0,commission=0.0; bool ours=(deal_magic==InpMagic); if(HistorySelectByPosition(pos_id)) { for(int i=0;i<HistoryDealsTotal();i++) { ulong t=HistoryDealGetTicket(i); commission+=HistoryDealGetDouble(t,DEAL_COMMISSION); if(HistoryDealGetInteger(t,DEAL_ENTRY)==DEAL_ENTRY_IN) { open_price=HistoryDealGetDouble(t,DEAL_PRICE); if(HistoryDealGetInteger(t,DEAL_MAGIC)==InpMagic) ours=true; } } } if(!ours) return;
OnTradeTransaction and the end-of-test pass share that logger, and an array of written deal tickets stops any deal from being written twice. OnDeinit calls the pass only when MQL_TESTER is true:
//+------------------------------------------------------------------+ //| End of a tester run: the tester force-closes open positions | //| before OnDeinit and that deal never reaches OnTradeTransaction, | //| so the EA closes anything still open, then reconciles history | //+------------------------------------------------------------------+ void FinishTesterRun(void) { //--- close any position of ours still open (usually the tester has done it) for(int i=PositionsTotal()-1;i>=0;i--) { ulong ticket=PositionGetTicket(i); if(ticket==0) continue; if(PositionGetString(POSITION_SYMBOL)!=_Symbol || PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; if(!g_trade.PositionClose(ticket)) PrintFormat("Could not close position %s at the end of the test (retcode %d)", IntegerToString((long)ticket),g_trade.ResultRetcode()); } //--- collect the tickets first: LogClosingDeal re-selects history per position if(!HistorySelect(0,TimeCurrent()+1)) return; ulong tickets[]; int total=HistoryDealsTotal(); ArrayResize(tickets,total); for(int i=0;i<total;i++) tickets[i]=HistoryDealGetTicket(i); //--- write every closing deal that the event handler did not see int before=ArraySize(g_logged); for(int i=0;i<total;i++) LogClosingDeal(tickets[i]); int added=ArraySize(g_logged)-before; if(added>0) PrintFormat("End-of-test reconcile wrote %d closing deal(s) missed by OnTradeTransaction",added); PrintFormat("Report rows written this run: %d",ArraySize(g_logged)); }
The service opens one SSH session per batch. For each file it uploads, writes the size, the timings and the SHA-256 of the local bytes to upload_log.csv, and only then moves the file to sent. A failed connection or upload ends the batch, and the wait before the next try doubles, up to 600 seconds. Two mistakes of my own tested this on the real terminal. A pin pasted without its last two characters gave "HOST KEY MISMATCH", and the wait went from 60 to 120 seconds. Two stale copies of the service on the wrong port failed with error 5272 and backed off from 240 to 480 seconds. In both cases the files stayed in the outbox.
Those stale copies were harmless only because they could not connect. The service takes no lock on the outbox, sent or the log. Two working copies watching the same folder could upload the same file twice, collide on the same .part name, or interleave lines in upload_log.csv. Run one instance per outbox.
Setting it up
These are the steps I followed on the test laptop. The Docker route at the end of step 2 is an alternative I did not measure.
- Install the files. Unpack the attached archive into the terminal's data folder (File > Open Data Folder), so that the files land under MQL5\Include, MQL5\Experts, MQL5\Services and MQL5\Scripts, then compile the EA, the service and the script in MetaEditor.
- Prepare a test server. On Windows, install the Win64 MSI of OpenSSH from github.com/PowerShell/Win32-OpenSSH/releases, start the sshd service and create a local user (for example trader) with a password. The login lands in that user's home folder, so use port 22 and a relative remote folder such as upload/reports. Alternatively, Docker Desktop with the atmoz/sftp image works with the default inputs (port 2222, /upload/reports): docker run -d --name sftp -p 2222:22 atmoz/sftp trader:ChangeMe:::upload.
- Allow the address. Under Tools > Options > Expert Advisors, tick "Allow WebRequest for listed URL" and add the host, for example 127.0.0.1.
- Pin the host key. Run SftpSelfTest with InpRunNetwork = true and an empty InpFingerprint. It refuses to log in and prints the server's fingerprint. Confirm it on the server with ssh-keygen -lf C:\ProgramData\ssh\ssh_host_ed25519_key.pub (Docker: docker exec sftp ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub) and paste the whole SHA256:... value into InpFingerprint. One missing character gives "HOST KEY MISMATCH".
- Key login (optional). Create a dedicated key without a passphrase with ssh-keygen -t ed25519 -N "" -f id_ed25519, copy id_ed25519 to Common\Files\NativeSFTP (under %APPDATA%\MetaQuotes\Terminal) and add id_ed25519.pub to the server's authorized_keys. Without a key file the client logs in with InpPassword.
- Start one uploader. In the Navigator, right-click Services, choose Add service, pick SftpUploader and set the host, port, user, password or key, fingerprint and remote folder. Start a single instance.
- Produce and check reports. Attach the EA to a chart or run it in the Strategy Tester. Finished days appear in Common\Files\NativeSFTP\outbox, move to sent after upload, and every attempt is logged in upload_log.csv. To confirm a file's content on the server, compare its hash (Get-FileHash on Windows, sha256sum on Linux) with the SHA-256 column of the log.
Testing the client
In a Linux sandbox, the C++ build of the sources talked to OpenSSH 10.5p1. The host fingerprint matched ssh-keygen, 20 uploads from 1 KiB to 10 MiB matched sha256sum on the server, and a key-only login was accepted. Each of these failed with a clear message and no login: no pin, a wrong pin, a wrong password, an unauthorized key, a passphrase-protected key, a server that is down, and a server without aes128-ctr.
The MQL5 build ran in MetaTrader 5 on a Windows laptop against OpenSSH_for_Windows_10.0 Win32-OpenSSH-GitHub on localhost, with password login. Key login ran only in the C++ sandbox build, not in the MQL5 runtime. A blank pin was refused with the fingerprint that ssh-keygen reports, and a wrong password reported the methods the server allows. The benchmark in SftpSelfTest uploads four sizes five times each, every upload on a new connection, and logs times and SHA-256 hashes to bench_results.csv. The data comes from MathSrand and MathRand, so every file can be regenerated in Python.
A note on sample sizes: the table is based on one run of 20 uploads (4 sizes × 5). Two earlier runs were excluded. One was incomplete. The other used GetTickCount64, which advances in 15.625 ms steps on Windows, so its logged times cluster around multiples of that interval (15, 16, 31, 32, 46, 62... 547 ms). That run still served as an integrity check: Get-FileHash on all 20 server copies matched the regenerated data. For the timed run, the SHA-256 that the script logged for the bytes it sent matched the regenerated data in all 20 cases. The server copies of the timed run were not hashed separately, so its integrity rests on the local hash of the sent bytes, not an independent read-back from the server; the files have the same names and content as the checked run next to it. Use GetMicrosecondCount for short timings.
| File size | Handshake, median ms | Upload, median ms | Upload range, ms | MiB/s from median |
|---|---|---|---|---|
| 1 KiB | 226.7 | 5.2 | 4.9–5.7 | – |
| 100 KiB | 211.2 | 7.8 | 7.3–8.3 | 12.5 |
| 1 MiB | 223.7 | 30.6 | 29.9–48.7 | 32.7 |
| 10 MiB | 216.7 | 262.6 | 255.9–267.1 | 38.1 |
Handshake and upload time against file size

4. All 20 connections of the timed run, 5 per size, on log axes. Blue circles: upload from OPEN to RENAME. Orange squares: handshake from TCP connect to the SFTP version reply, password login included.
The handshake took a median 221.6 ms. The first connection took 379.1 ms and the other 19 ranged from 190.6 to 239.8. Our arithmetic is about 3.5 ms of that. The rest is round trips, the server starting a session and the Windows logon behind password authentication, and these measurements do not separate them.
Throughput is file size over median upload time, handshake excluded. It reached 38.1 MiB/s for 10 MiB. At the session B speeds, AES and HMAC over 10 MiB cost 10 × (12.7 + 5.3) = 180.0 ms, or 69% of the 262.6 ms median. That is a rough estimate, not a measurement, since the two were timed in separate runs and the transport MACs 32 KiB packets rather than one 1 MiB buffer. On a remote server, round trips will weigh more.
Six backtests, one upload session
The pipeline test used six backtests: XAUUSD, EURUSD and GBPUSD, each on H1 and M15, from 2026.07.01 to 2026.09.30 with real ticks (History Quality 100%), a $10,000 deposit, 1:100 leverage, a hedging account, the server's own default spread and no added commission, and default inputs apart InpTimeframe, on one demo account on the MetaQuotes-Demo server. The service then uploaded all 294 sealed files in one session. On the server, PowerShell counted the files and rows per run and summed the net column.
| Run | Ticks | Tester trades | Tester net | Files on server | Rows on server | Net on server | End-of-test rows |
|---|---|---|---|---|---|---|---|
| XAUUSD H1 | 34,283,276 | 48 | −702.32 | 41 | 48 | −702.32 | 1 |
| XAUUSD M15 | 34,283,276 | 204 | −1,844.08 | 64 | 204 | −1,844.08 | 0 |
| EURUSD H1 | 17,434,558 | 50 | −878.41 | 37 | 50 | −878.41 | 0 |
| EURUSD M15 | 17,434,558 | 192 | −203.65 | 60 | 192 | −203.65 | 0 |
| GBPUSD H1 | 28,637,289 | 48 | −89.77 | 34 | 48 | −89.77 | 1 |
| GBPUSD M15 | 28,637,289 | 181 | −1,730.37 | 58 | 181 | −1,730.37 | 0 |
| Total | – | 723 | −5,448.60 | 294 | 723 | −5,448.60 | 2 |
Tester trades is Total Trades from each run's Backtest report, and it equals the row count the EA printed in the journal. Files on server counts one file per day on which a trade closed, which is why the six runs produced 294 files rather than one per trading day. The net columns come from two paths, the tester report and a sum over the uploaded files, but both rest on the same tester deal history, so together they check delivery, not the history itself. A matching count and sum are also not proof that each trade arrived exactly once, because a missing row and a duplicate of the same amount would cancel out. The last column counts rows from the end-of-test pass, one in each run that ended with a position open.
Upload time of each file in the batch

5. All 294 uploads of the matrix in one session, in upload order. Colour marks the run: EURUSD blue, GBPUSD green, XAUUSD orange, dark for H1 and light for M15. File sizes ranged from 181 to 703 bytes.
All 294 uploads succeeded, 91,139 bytes in total, between 00:57:27 and 00:57:37 by the log, after a 542.0 ms handshake. The median upload took 26.0 ms and the times summed to 6.58 s, about 66% of the roughly 10 seconds between the first and last log line. Reading, hashing, logging and moving files took the rest. This batch tests many small files. It does not test long transfers, large reports, an unstable network or repeated errors.
Fig. 5 shows two bands. 115 uploads sit around a median of 11.9 ms and 179 around 27.6 ms, and no upload falls between 18.9 and 24.3 ms. Size does not separate them: the lower band holds files of 182 to 620 bytes and the upper 181 to 703. The gap of 15.7 ms is close to one Windows timer tick, and the read loop yields with Sleep(1) while it waits for the server, which can last up to a tick at the default timer rate. That is a correlation, not a tested cause. The benchmark's 1 KiB uploads, run from a script at another time, stayed between 4.9 and 5.7 ms, which a timer effect alone would not obviously predict. Server-side work on each new file, such as antivirus scanning, could produce bands as well. I did not test any of these in isolation, so the cause of the two bands remains open.
Summary of the matrix. Across three symbols and two timeframes, 723 trades turned into 294 daily files (one per day with a closed trade) and 723 rows on the server, with zero failed uploads. Row counts and net profit match the tester for all six runs. Two of the six needed the end-of-test pass, which shows that a trade-report EA should not rely on OnTradeTransaction alone in the tester. The strategy itself lost money in every run, and nothing here says anything about its edge.
Limitations
Where it was tested. One Windows laptop, OpenSSH for Windows on localhost, one MetaQuotes-Demo account, three months of 2026. That says nothing about network latency or packet loss, NAT or VPS setups, other SFTP servers or other server configurations, and the throughput figures will not carry over to a remote server.
One algorithm suite. No aes256-gcm, chacha20-poly1305, RSA or ECDSA host keys, no keyboard-interactive login and no passphrase-protected keys. A server that allows none of the supported options is refused.
Keys and passwords. Only unencrypted Ed25519 key files are read, so keep the key in a folder only your account can open. Passwords sit in the service inputs in plain text, which is a real risk on a VPS or a shared terminal. A key avoids that plaintext password, but key login was tested only in the C++ sandbox build, not in the MQL5 runtime, so confirm it there yourself before relying on it. Either way, give the server account write access to the upload folder only.
Randomness. The generator hashes clocks, the terminal data path, timer jitter and the server's KEXINIT. It supplies the X25519 ephemeral secret, the KEXINIT cookie and packet padding (Ed25519 signing is deterministic and does not use it). The freshness check does not show that the output is cryptographically unpredictable, and I have not shown that these sources carry enough entropy. Treat its strength as unproven.
Side channels. Whether X25519, Ed25519 and AES run in constant time in MQL5 was not measured.
Integrity and publishing. The client checks the size of the uploaded file, not its content on the server. The swap is not atomic, .part files are visible while they are written, and a failed upload starts the file again from the beginning.
One uploader per outbox. There is no lock against a second copy of the service.
Self-test scope. The 16 checks cover the primitives only. They say nothing about the SSH and SFTP state machine, re-keying, channel flow control, request pipelining, error handling or recovery. The sandbox and terminal tests exercised those only in the cases described above.
Conclusion
An SFTP client fits in two include files of plain MQL5. The parts that need the most care are not the cipher rounds, which published vectors check quickly, but the rules around them: refuse an unknown host key, check the length before trusting it, verify the MAC before reading the payload, never leave a half-written file under the real name, and in the tester, find the last trade yourself.
On localhost a session opened in about a fifth of a second and moved 10 MiB at 38.1 MiB/s, and across six backtests the row counts and net profit on the server matched the tester. That is one Windows machine and one server, not evidence about real networks or other SFTP servers. Before relying on it, try the service on a test server: pin the fingerprint, send one day of files, compare the row count with the tester and the server hashes with the log.
| File | Type | Description |
|---|---|---|
| MQL5\Include\NativeSFTP\SshCrypto.mqh | Include | SHA-512, AES-128 and CTR mode, HMAC-SHA256, X25519, Ed25519, the random generator and the known-answer self-test. |
| MQL5\Include\NativeSFTP\SftpClient.mqh | Include | SSH transport, key exchange with host key pinning, password and Ed25519 login, channel handling and the SFTP v3 client. |
| MQL5\Experts\NativeSFTP\SftpReport_EA.mq5 | Expert Advisor | Demo breakout EA that writes one CSV report for each day with a closed trade and reconciles closing deals at the end of a test. |
| MQL5\Services\NativeSFTP\SftpUploader.mq5 | Service | Uploads sealed reports from the outbox, logs each upload with its SHA-256 and backs off after failures. |
| MQL5\Scripts\NativeSFTP\SftpSelfTest.mq5 | Script | Known-answer tests, primitive timings and the upload benchmark. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.