0bps

Strategy vault / Tools & templates

Classic Moving Average Strategy

"Talk is cheap. Show me the code" For teaching purposes, use with caution in real trading. Note: Strategy uses a trading template library I hope that novices can get started with this strategy, learn to write…

Author
Zero
Complexity
Intermediate · 57 lines
Parameters
9
Backtest bar
1d · swing
Tested on
BTC/USD · spot

"Talk is cheap. Show me the code"

For teaching purposes, use with caution in real trading.

Note: Strategy uses a trading template library

I hope that novices can get started with this strategy, learn to write strategies step by step, and experience the impact of simulation and real environments on the trading system.

https://dn-filebox.qbox.me/fb4d0c7d773ca83e9d0230927705d419dc0bbeaa.png

Parameters

NameDefaultWhat it controls
FastPeriod5Market Entry Express Cycle
SlowPeriod15Slow market entry cycle
EnterPeriod2Market Entry Observation Period
ExitFastPeriod7Exit express cycle
ExitSlowPeriod15Exit slow cycle
ExitPeriodtrueMarket Exit Observation Period
PositionRatio0.8Position ratio
StopLossRatio0.05Stop loss ratio
Interval10Polling interval (seconds))

Source JavaScript

/*backtest
start: 2019-01-01 00:00:00
end: 2019-07-01 00:00:00
period: 1d
exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}]
*/

function main() {
    var STATE_IDLE  = -1;
    var state = STATE_IDLE;
    var entryPrice = 0;
    var initAccount = _C(exchange.GetAccount);
    Log(initAccount);
    while (true) {
        if (state === STATE_IDLE) {
            var n = $.Cross(FastPeriod, SlowPeriod);
            if (Math.abs(n) >= EnterPeriod) {
                var account = _C(exchange.GetAccount);
                var ticker = _C(exchange.GetTicker);
                var obj = n > 0 ? $.Buy(_N(account.Balance * PositionRatio / ticker.Sell, 3)) : $.Sell(_N(account.Stocks * PositionRatio, 3));
                if (obj) {
                    opAmount = obj.amount;
                    entryPrice = obj.price;
                    state = n > 0 ? PD_LONG : PD_SHORT;
                    Log("Open position details", obj, "Cross period", n);
                }
            }
        } else {
            var n = $.Cross(ExitFastPeriod, ExitSlowPeriod);
            var needCover = Math.abs(n) >= ExitPeriod && ((state === PD_LONG && n < 0) || (state === PD_SHORT && n > 0));
            if (needCover) {
                Log("Close the position after exiting the market");
            } else {
                var ticker = _C(exchange.GetTicker);
                if (state === PD_LONG) {
                    if (ticker.Buy < entryPrice*(1-StopLossRatio)) {
                        needCover = true;
                        Log("Stop loss and close position");
                    }
                } else {
                    if (ticker.Sell > entryPrice*(1+StopLossRatio)) {
                        needCover = true;
                        Log("Stop loss and close position");
                    }
                }
            }
            if (needCover) {
                var nowAccount = _C(exchange.GetAccount);
                var obj = state === PD_LONG ? $.Sell(_N(nowAccount.Stocks - initAccount.Stocks, 3)) : $.Buy(_N(initAccount.Stocks - nowAccount.Stocks, 3));
                state = STATE_IDLE;
                nowAccount = _C(exchange.GetAccount);
                LogProfit(nowAccount.Balance - initAccount.Balance, 'Money:', nowAccount.Balance, 'Coins:', nowAccount.Stocks, 'Close details:', obj, "Cross cycle", n);
            }
        }
        Sleep(Interval*1000);
    }
}

Published by Zero on the FMZ strategy square · last modified 2019-10-08. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a tested, production-ready module from strategies/Classic-Moving-Average-Strategy.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open