0bps

Strategy vault / Other

Python Version Single Platform Balanced Strategy Tutorial

Quoted from the single-platform balanced strategy in JavaScript version This requires opening a position. For example, the account has 5,000 yuan and 1 coin. If the value of the coin is greater than the account…

PythonOther
Author
发明者量化-小小梦
Complexity
Starter · 56 lines
Parameters
6

Quoted from the single-platform balanced strategy in JavaScript version

This requires opening a position. For example, the account has 5,000 yuan and 1 coin. If the value of the coin is greater than the account balance of 5,000 and the price difference exceeds the threshold, for example, the currency is now worth 6,000 yuan, sell it (600 0-5000)/6000/2 coins, it means the currency has appreciated, exchange the money back. If the currency has depreciated, for example, 4000 yuan, buy (5000-4000)/4000/2 coins, When the currency falls, buy some back, and if it rises again, sell it again. It's like a balance, with different hedging on both sides, so I named it a balanced strategy.

Article address: https://www.fmz.com/bbs-topic/4986

Parameters

NameDefaultWhat it controls
threshold0.05Threshold
Interval2000Error retry interval (milliseconds)
LoopInterval60Polling interval (seconds)
MinStock0.001Minimum transaction volume
XPrecision4quantity precision
ZPrecision8Price Precision

Source Python

'''backtest
start: 2019-12-01 00:00:00
end: 2020-02-01 11:00:00
period: 1m
exchanges: [{"eid":"OKEX","currency":"BTC_USDT","stocks":1}]
'''

InitAccount = None

def CancelPendingOrders():
    ret = False
    while True:
        orders = _C(exchange.GetOrders)
        if len(orders) == 0 :
            return ret

        for j in range(len(orders)):
            exchange.CancelOrder(orders[j].Id)
            ret = True
            if j < len(orders) - 1:
                Sleep(Interval)
    return ret 

def onTick():
    acc = _C(exchange.GetAccount)
    ticker = _C(exchange.GetTicker)
    spread = ticker.Sell - ticker.Buy
    diffAsset = (acc.Balance - (acc.Stocks * ticker.Sell)) / 2
    ratio = diffAsset / acc.Balance
    LogStatus("ratio:", ratio, _D())
    if abs(ratio) < threshold:
        return False
    if ratio > 0 :
        buyPrice = _N(ticker.Sell + spread, ZPrecision)
        buyAmount = _N(diffAsset / buyPrice, XPrecision)
        if buyAmount < MinStock:
            return False
        exchange.Buy(buyPrice, buyAmount, diffAsset, ratio)
    else :
        sellPrice = _N(ticker.Buy - spread, ZPrecision)
        sellAmount = _N(-diffAsset / sellPrice, XPrecision)
        if sellAmount < MinStock:
            return False 
        exchange.Sell(sellPrice, sellAmount, diffAsset, ratio)
    return True

def main():
    global InitAccount, LoopInterval
    InitAccount = _C(exchange.GetAccount)
    LoopInterval = max(LoopInterval, 1)
    while True:
        if onTick():
            Sleep(1000)
            CancelPendingOrders()
            Log(_C(exchange.GetAccount))
        Sleep(LoopInterval * 1000)

Published by 发明者量化-小小梦 on the FMZ strategy square · last modified 2020-02-05. 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 production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/Python-Version-Single-Platform-Balanced-Strategy-Tutorial.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