The research aim was to present a system for automating trading on blockchains that promotes minimized trust without losing its competitive advantage by divulging too much information.
- This paper introduces CHAINBOT which partitions algorithmic computation into on-/off-chain components to provide a measure of end-to-end integrity while preserving algorithmic parameters.
- CHAINBOT stores public parameters of parametrized trading algorithms on-chain, but keeps parameters critical to algorithm performance private by storing them off-chain.
- CHAINBOT returned up to 2.4x and, on average, 1.4x in a “buy and hold strategy.”
- Across 1000 runs, the end-to-end average execution time for the CHAINBOT system was 48.4 seconds.
- The frequency of trading did not significantly affect the rate of return, as its Sharpe ratio demonstrated. This implies that transactions do not have to take place at every block on-chain, saving significant amounts of gas.
What is a possible architectural design for a hybrid on-chain/off-chain trading algorithm that is trust minimized and transparent, yet able to execute without sacrificing its competitive advantage due to privacy loss?
Bitcoin transactions are publicly visible, yet their blockchain maintains a degree of anonymity (“pseudonymity”). This anonymity has limits.
- The original Bitcoin Whitepaper describes the concept: “Privacy can still be maintained by breaking the flow of information in another place: by keeping public keys anonymous. The public can see that someone is sending an amount to someone else, but without information linking the transaction to anyone… Some linking is still unavoidable with multi-input transactions, which necessarily reveal that their inputs were owned by the same owner. The risk is that if the owner of a key is revealed, linking could reveal other transactions that belonged to the same owner” 
This introduces the idea that all peer to peer (P2P) interactions on a non-private blockchain may be captured and used to undermine user privacy.
As per Xia, Pengcheng et al’s example of identifying tokens on Uniswap , which is a decentralized exchange (DEX), pseudonymity can be used by malicious actors to undermine blockchain ecosystems.
- Layer-2 (L2) protocol blockchains can improve scalability by carrying out transactions off-chain by either:
- submitting a smaller number of proofs than the actual number of transactions, 
- or having off-chain transactions batched in a fraud or zero-knowledge proof before submitting to chain 
- These solutions do not fully preserve privacy, because transaction data remains available to some participants or revealed in case of dispute.
- StarkEx L2 solutions keep computation and data off-chain, however this may create a “data availability problem.” Those who do not have access to transaction data cannot reconstruct the state.
- The current solution is to pass data availability verification tasks to a Data Availability Committee (DAC), which is not fully private.
Off-Chain Computation - Blockchain Privacy:
- Computational tasks can be outsourced in a privacy-preserving way, however, disputed data should be made public since “fraud proofs” are used.
- Mixing cryptography and incentivization may be a means to achieving privacy with off-chain computation.
- This still comes at the cost of losing the intrinsic trustlessness of the blockchain.
- Efforts to replace trusted entities with multi-party computation (MPC) exist but computation on encrypted data is a significantly costly task.
- Privacy-preserving payment protocols offer confidential transactions but are not viable for general computation 
- Blockchains designed with privacy considerations,such as Zerocash, Zcash, Solidus, Monero and several others [12,24,19,8,14] may enable privacy but introduce complexity during integration with existing platforms and features.
- Privacy-focused chains have been subject to deanonymization attacks in recent years and may not be able to guarantee privacy. [6,27,11,26]
Blockchain Automated Trading:
- Machine learning can be used for Bitcoin price prediction or outputting portfolio vectors, automating bitcoin trading, and executing high-frequency trading
- Another study shows high-frequency trading can occur in an adversarial form, using deterministic Automated Market Maker DEXes.
Private On-Chain Algorithmic Trading:
- Using a trading algorithm on-chain eliminates the need for trust,
- Users of on-chain bot can audit a trading algorithm
- Funds are stored in smart contract while users keep full control of their money
- Conversely, a bot will lose its competitive advantage if its algorithm is open to the public (on-chain).
- CHAINBOT makes public parameters of parametrized trading algorithm on-chain, but keeps parameters critical to algorithm performance private by storing hemt off-chain.
- Private parameters can be re parameterized off-chain to market conditions.
- Zero-knowledge proofs can be used to verify that an on-chain algorithm runs smoothly
- Trades should be executed privately.
System Components - CHAINBOT has multiple on-chain/ off-chain elements in these categories
On-Chain bot. Smart contract to obtain parameters (price, financial indicators etc.)
Off-Chain bot. Trains algorithm, stores private parameters, decides and executes trades
Proof system. On-chain verifier, off-chain proof generator
L2 privacy-enhancing DEX. E.g DeversiFi
On-Chain oracle. Uniswap or ChainLink
Conditions of user subscriptions
Subscribes to CHAINBOT by sending funds to on-chain bot
On-chain bot records amount invested
On-chain bot uses pooled user funds
Once trading epoch completed, on-chain bot pays user share of returns
(Bollinger Bands(BBs) trading algorithm), confidence interval of standard deviations of simple moving average, enveloping upper Bollinger Band and lower Bollinger Band.
Trading strategy is simple yet powerful
Suitable for parameterization
A1: Blockchain security. Ignore ramifications of blockchain forks and assume that participants are honest. 
A2: Validity of trusted setup. Verification/proving keys created during a “generation ceremony,” involving MPC, used for “trusted setup.” [4,5]
A3: Off-chain bot fund integrity. Integrity assumption does not include off-chain bot executions but assumes users can verify flow of funds via querying blockchain ledger.
A4: DEX integrity. Assumes privacy enhancing DEX enables ensuring trades correctly executed on verified financial decisions. Further assumes DEX provides full privacy or shared data are impartial and honest.
A5: DEX privacy. Assumes DEX enable trades that does not reveal trade type (e.g asset pair), sources, destinations, and amounts to blockchain observers.
A6: Oracle integrity. Assumes on-chain price oracle provides accurate data.
Threat Analysis - End to end trading integrity
- Verify correct public parameter values used in trade decisions (assume A1,A2)
- Guarantee private parameters included correctly to algorithm via zero-knowledge proof (assume A1)
- Ensures trading decisions based on correct asset pricing (assume A6)
- Ensures trades executed on trading decisions align on assumption that DEX provides verification that does not damage user privacy (assume A3,A4,A5)
Threat Analysis - Algorithmic privacy
(Designed to prevent end-to-end integrity threads to bot and theft of trading algorithm)
- CHAINBOT uses parameterized algorithms of parameters kept off-chain thus cannot be easily stolen or replicated.
- Reliance on private DEX makes reverse engineering parameters impossible.
- Uses assumption A3, A5.
- Zenbot off-chain cryptocurrency trading bot with backtesting features was used.
- Historical data ETH-USDC price from August 2020 to August 2021 from Poloniex exchange.
Grid search optimization for top-performing parameters
1 ≤ Moving average period size ≤ 40,
1 ≤ standard deviations ≤ 6,
−1 ≤ Upper Bollinger band ≤ 30,
−1 ≤ Lower Bollinger band ≤ 30
Many factors can be of varying importance in given context therefore no single method of determining trading algorithms success.
Thus “Sharpe ratio” and average return is used to score parameter configurations.
- On average 1.4x return from gridsearch top params.
- On average return only 0.6 using Sharpe ratio configurations with lower standard deviation.
- Average return configuration aims to maximize return.
- Sharpe ratio additionally takes risk in to consideration.
- All parameter configurations performed better than “buy and hold” strategy.
This paper makes the following contributions:
- Combining on-/off-chain. CHAINBOT combines on-chain integrity/ transparency and off-chain privacy execution. Off-chain integrity is maintained via zero-knowledge proofs based on Zokrates.
- Parameterized algorithms. (Public) code of bot parametrized by (confidential) parameters from training historical data
- Confidential trading. Private L2-based decentralized exchange, on-chain oracles for price data.
- Training data - ETH:USDC price historical data
- Yield 2.4x, average 1.4x with “buy and hold” strategy as a baseline.
- Latency of 48.4 seconds per end to end trade execution.
- Frequency does not affect return significantly (reduced gas fees).
- Cost analysis: able to sustain continuous trading amortized cost $0.15 per user on the user base of 1000 people (on basis where simulations were conducted across 1000 “runs”).
End-to-end Performance - Time measurements
- Performed on local machine(2-core Intel i5-5257U CPU, clocked at 2, 7GHz, with 8GB RAM, 256 GB SSD).
- Off-chain proof generation took least about of time, 0.2-0.8 seconds of 48.4 seconds total.
- Takes 22.8 average seconds to get public parameters, retrieve price from oracle and calculate the Bollinger bands.
- Verification of off-chain bots zero-knowledge proof decision averages 23 seconds
- Takes 2.3 seconds to execute actual trade on DeversiFi
End-to-end Performance - Gas costs
- 281715 steady gas for on-chain bot and retrieving price from on-chain oracle.
- Verifier contract’s calculations gas usage slightly varies among calls, average 191687 gas.
- Average gas cost of end to end execution is around 004592 ETH = ~$150 USD as of 28.08.2021.
End-to-end Performance - Frequency of execution
- Trained and tested Bollinger algorithm in 1 minute, 10 minutes, and 1 hour trading periods.
- Inverse relationship between trading period length and mean relative returns, but difference is less than 2%.
- Lower trading periods may lead to higher standard deviation.
- Trading less often might make returns with lower risk and may be used to lower gas cost
End-to-end Performance - Summary
- Average 48.4 seconds end-to-end execution
- Around 473402 gas
- Frequency of execution does not affect rate of return significantly
“An average user willing to invest $1000 with CHAINBOT would earn $105 while spending $3 on gas; this assumed a user pool of 1000 subscribers. Average execution time is 48.4 seconds end to end per trade. “
- Assets prices may change in the course of a trade and might cause a discrepancy in the trading algorithm’s expected and realized trade decisions.
- Further research is needed for a systematic understanding of these effects.
Off-Chain Integrity Concerns
- StarkEx and DeversifFi are ways of verifying transactions included in the proof batch by having access to sequencer data.
- Thus there is no direct way of verifying an off-chain bot’s trade decisions.
- A supervising committee can be appointed to observe an off-chain bot’s trade decisions/executions.
- There exists a trade-off between making confidential information available to committee members and establishing end to end integrity.
- Implementation requires use of multiple programming languages.
- This can be hard to maintain or fragile.
- Creating a programming language expressive enough that it can be compiled/transpiled to other languages to increase robustness/practicality of deployment/maintenance of bot, preventing data leaks with type checking.
The research aim was to present a system for automating trading on blockchains that promotes minimized trust without losing its competitive advantage by divulging too much information. CHAINBOT partitions the trading process using a hybrid on-/off-chain approach as well as zero-knowledge proofs to maintain end-to-end integrity and privacy-enhancing DEXs. This is to prevent trades from being mirrored and private parameters from being reverse-engineered.
Based on the performant results of CHAINBOT, it is evident that a hybrid on-chain/off-chain approach is a viable and cost-effective method of building algorithmic trading systems on the blockchain.
Nakamoto, S. (2008) Bitcoin: A Peer-to-Peer Electronic Cash System. 10. Privacy https://bitcoin.org/bitcoin.pdf
Xia, Pengcheng et al. “Demystifying Scam Tokens On Uniswap Decentralized Exchange”. Arxiv.Org, 2021, [2109.00229] Trade or Trick? Detecting and Characterizing Scam Tokens on Uniswap Decentralized Exchange.
 StarkEx: Powering scalable self-custodial transactions, StarkEx - Starkware. Accessed: 2021-09-06
Zcash parameter generation, Parameter Generation - Zcash. Accessed: 2021-09-06
Baumann, N., Steffen, S., Bichsel, B., Tsankov, P., Vechev, M.: zkay v0.2: Practical data privacy for smart contracts. arXiv preprint arXiv:2009.01020 (2020)
B ́eres, F., Seres, I.A., Bencz ́ur, A.A., Quintyne-Collins, M.: Blockchain is watching you: Profiling and deanonymizing ethereum users. arXiv preprint arXiv:2005.14051 (2020)
Bollinger, J.: Using bollinger bands. Stocks & Commodities (1992)
B ̈unz, B., Agrawal, S., Zamani, M., Boneh, D.: Zether: Towards privacy in a smart contract world. In: International Conference on Financial Cryptography and Data Security. Springer (2020). https://doi.org/10.1007/978-3-030-51280-4 23
Buterin, V.: An incomplete guide to rollups (May 2021), An Incomplete Guide to Rollups
Cecchetti, E., Zhang, F., Ji, Y., Kosba, A., Juels, A., Shi, E.: Solidus: Confidential distributed ledger transactions via PVORM. In: ACM SIGSAC Conference on Computer and Communications Security (2017). https://doi.org/10.1145/3133956.3134010
Chervinski, J.O.M., Kreutz, D., Yu, J.: Floodxmr: Low-cost transaction flooding attack with monero’s bulletproof protocol. IACR Cryptology ePrint Archive, (2019), https://eprint.iacr.org/2019/455.pdf
Danezis, G., Fournet, C., Kohlweiss, M., Parno, B.: Pinocchio coin: building Zerocoin from a succinct pairing-based proof system. In: The First ACM workshop on Language support for privacy-enhancing technologies (2013). https://doi.org/10.1145/2517872.2517878
 Eberhardt, J., Tai, S.: Zokrates - scalable privacy-preserving off-chain computations. In: IEEE International Conference on Internet of Things (iThings) and IEEE Green Computing and Communications (GreenCom) and IEEE Cyber, Physical and Social Computing (CPSCom) and IEEE Smart Data (SmartData). IEEE (2018). https://doi.org/10.1109/Cybermatics 2018.2018.00199
Fauzi, P., Meiklejohn, S., Mercer, R., Orlandi, C.: Quisquis: A new design for anonymous cryptocurrencies. In: International Conference on the Theory and Application of Cryptology and Information Security (2019). https://doi.org/10.1007/978-3-030-34578-5 23
Gervais, A., Karame, G.O., W ̈ust, K., Glykantzis, V., Ritzdorf, H., Capkun, S.: On the security and performance of proof of work blockchains. In: Proceedings of the 2016 ACM SIGSAC conference on computer and communications security. pp. 3–16 (2016)
Gudgeon, L., Moreno-Sanchez, P., Roos, S., McCorry, P., Gervais, A.: Sok: Layer-two blockchain protocols. In: International Conference on Financial Cryptography and Data Security. Springer (2020). https://doi.org/10.1007/978-3-030-51280-4 12
Hopwood, D., Bowe, S., Hornby, T., Wilcox, N.: Zcash protocol specification. GitHub: San Francisco, CA, USA (2016), https://zips.z.cash/protocol/protocol.pdf
jiang, Z., Liang, J.: Cryptocurrency portfolio management with deep reinforcement learning. In: IEEE Intelligent Systems Conference (IntelliSys) (2017). Cryptocurrency portfolio management with deep reinforcement learning | IEEE Conference Publication | IEEE Xplore
Jivanyan, A.: Lelantus: Towards confidentiality and anonymity of blockchain transactions from standard assumptions. IACR Cryptology ePrint Archive (2019), Cryptology ePrint Archive: Report 2019/373 - Lelantus: Towards Confidentiality and Anonymity of Blockchain Transactions from Standard Assumptions
Noether, S.: Ring signature confidential transactions for Monero. IACR Cryptology ePrint Archive (2015), Cryptology ePrint Archive: Report 2015/1098 - Ring Signature Confidential Transactions for Monero
Sasson, E.B., Chiesa, A., Garman, C., Green, M., Miers, I., Tromer, E., Virza, M.: Zerocash: Decentralized anonymous payments from Bitcoin. In: IEEE Symposium on Security and Privacy (SP) (2014). Zerocash: Decentralized Anonymous Payments from Bitcoin | IEEE Conference Publication | IEEE Xplore
Shah, D., Zhang, K.: Bayesian regression and bitcoin. In: 52nd Annual Allerton Conference on Communication, Control, and Computing (Allerton) (2014). Bayesian regression and Bitcoin | IEEE Conference Publication | IEEE Xplore
 Teutsch, J., Reitwießner, C.: A scalable verification solution for blockchains. arXiv preprint arXiv:1908.04756 (2019)
Van Saberhagen, N.: Cryptonote v 2.0 (2013), https://www.getmonero.org/ru/resources/research-lab/pubs/whitepaper_annotated.pdf
Vo, A., Yost-Bremm, C.: A high-frequency algorithmic trading strategy for cryptocurrency. Journal of Computer Information Systems (2020). https://doi.org/10.1080/08874417.2018.1552090
Wijaya, D.A., Liu, J., Steinfeld, R., Liu, D.: Monero ring attack: Recreating zero mixin transaction effect. In: 17th IEEE International Conference On Trust, Security And Privacy In Computing And Communications/ 12th IEEE International Conference On Big Data Science And Engineering (TrustCom/BigDataSE) (2018). Monero Ring Attack: Recreating Zero Mixin Transaction Effect | IEEE Conference Publication | IEEE Xplore
Yousaf, H., Kappos, G., Meiklejohn, S.: Tracing transactions across cryptocurrency ledgers. In: 28th USENIX Conference on Security Symposium (2019). https://doi.org/10.5555/3361338.3361396
Zhou, L., Qin, K., Torres, C.F., Le, D.V., Gervais, A.: High-frequency trading on decentralized on-chain exchanges. In: IEEE Symposium on Security and Privacy (SP) (2021), https://arxiv.org/pdf/2009.14021.pdf
This section describes implementation details of the system outlined in the “SUMMARY” section, A.1, A.2, A.3.
A.1 Algorithmic Training
- Search function looking for top-performing parameter configurations from past training period and tested for ex-post performances.
- Grid search for space of minimum, maximum and mean values of parameters results in a set C ← all parameter configurations obtained by the product of the sets of possible values.
A.2 Zokrates Interactions
-  Zokrates is a programming language which specifies knowledge to be proven and acts as originator for verifier smart contract as well as proof generator.
- CHAINBOT Zokrates program takes five parameters:
- X(current price)
- Upper BB(Bollinger Band)
- Lower BB(Bollinger Band)s
- Flag to signal buy or sell decision
- “L” or “U” baked decision type
- Proof from root program confirms prover made undisclosed trading decisions from hidden parameters where public parameters were obtained from on-chain bot.
Verifying public parameters.
- It is possible to produce verifiable proof from parameters different than on-chain bot or algorithmic trainers.
- It is necessary to implement a mechanism to ensure correct parameters used for proof generation.
- Inputs to Zokrates program can be public or private.
- Enables off-chain bot to feed public trading params into proof (as public parameters)
- Enables on-chain bot to check that values included in proof are provided on-chain
- If off-chain bot uses incorrect public parameters this will be visible in proof and proof-verification will fail.
Preventing information leaks
- Single proof generator and verifier contract for all possible conditions for trade decision.
- Trade decision needs be specified as private input in root Zokrates code.
- Prevents being openly included in proof
Validating the verifier contract
- Zokrates verification system based on Arithmetic Circuits and Rank 1 Constraint Systems (RICS)
- Verifier contract validation can be enabled by having root Zokrates code publicly accessible.
- E.g. storing smart contract, compare to Solidity code with deployed smart contract
A.3 DiversiFi Interactions
Hiding CHAINBOT trade decisions is essential to protecting privacy of trading strategy.
- To trade privately, a self-custodial order book exchange that uses L2 protocol for enhancing transaction privacy and speed, DeversiFi is used
Validium and transaction privacy
- DeversiFi powered by Validium-based StarkEx scalability engine
- Validium is an L2 solution where multiple transactions are batched off-chain in single zero-knowledge proof and then verified on-chain.
- Validium differs from ZK-rollups in storing entire data related to transactions off-chain.
- Validium tries to solve data availability problem via “Data Availability Committee” (DAC)
- Decentralized members hold copy of all off chain transaction data and sign commitments to every new state
Private trading on DeversiFi
- Leverages Validium to hide trades from public
- User funds stored in “token accounts” (vaults)
- Each have unique ID
- Hold single type of asset
- Can be assigned to single user at given time
- Merkle tree formed from token accounts, updated every time token accounts balance changes
- Funds need be deposited to StarkEx smart contract before starting trading on DeversiFi
- Deposited funds automatically recorded to user’s token account
-Trading happens entirely off-chain, maker-taker model
Maker signs order, including token types, amounts being traded, and maker’s account IDs for tokens
Taker executes trade, signing order along IDs of 2 corresponding token accounts
Amount subtracted from token account balance then added to their “on-chain withdrawal balance”
Enables direct withdrawal from StarkEx smart contract when user wants to withdraw funds from DeversiFi
- DeversiFi does not provide a trustless trading platform.
- Keeping trades private from other traders comes with cost of sharing with DAC
- Users have to trust DeversiFi to include their transaction in proof and submit it onto the chain since DeversiFi operates the “sequencers”
- If DeversiFi attempts to censor a user’s withdrawal request, users can retrieve their funds from StarkEx smart contract if they manage to acquire necessary data from DAC members