0bps

Strategy vault / Other

Python Version Iceberg Order Buy

Teaching strategy, related article link:https://www.fmz.com/bbs-topic/5080

PythonOther
Author
发明者量化-小小梦
Complexity
Intermediate · 65 lines
Parameters
8

Teaching strategy, related article link:https://www.fmz.com/bbs-topic/5080

Parameters

NameDefaultWhat it controls
TotalBuyNet10000Total purchase amount (yuan))
AvgBuyOnce100Average quantity per purchase (CNY))
FloatPoint10Single average floating point number (percentage)
EntrustDepth0.1Order depth (percentage)
MaxBuyPrice20000Highest buy price (yuan)
Interval1000Retry on failure (milliseconds))
MinStock0.0001Minimum transaction volume
LoopIntervaltruePrice polling interval (seconds)

Source Python

import random

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

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

LastBuyPrice = 0
InitAccount = None

def dispatch():
    global InitAccount, LastBuyPrice
    account = None
    ticker = _C(exchange.GetTicker)
    LogStatus(_D(), "ticker:", ticker)
    if LastBuyPrice > 0:
        if len(_C(exchange.GetOrders)) > 0:
            if ticker["Last"] > LastBuyPrice  and ((ticker["Last"] - LastBuyPrice) / LastBuyPrice) > (2 * (EntrustDepth / 100)): 
                Log("Deviated too much, Latest transaction price:", ticker["Last"], "order price", LastBuyPrice)
                CancelPendingOrders()
            else :
                return True
        else :
            account = _C(exchange.GetAccount)
            Log("Buy order completed, Total cost:", _N(InitAccount["Balance"] - account["Balance"]), "Average buying price:", _N((InitAccount["Balance"] - account["Balance"]) / (account["Stocks"] - InitAccount["Stocks"])))
        LastBuyPrice = 0

    BuyPrice = _N(ticker["Buy"] * (1 - EntrustDepth / 100))
    if BuyPrice > MaxBuyPrice:
        return True

    if not account:
        account = _C(exchange.GetAccount)

    if (InitAccount["Balance"] - account["Balance"]) >= TotalBuyNet:
        return False

    RandomAvgBuyOnce = (AvgBuyOnce * ((100.0 - FloatPoint) / 100.0)) + (((FloatPoint * 2) / 100.0) * AvgBuyOnce * random.random())   # random number 0~1
    UsedMoney = min(account["Balance"], RandomAvgBuyOnce, TotalBuyNet - (InitAccount["Balance"] - account["Balance"]))

    BuyAmount = _N(UsedMoney / BuyPrice)
    if BuyAmount < MinStock:
        return False 
    LastBuyPrice = BuyPrice
    exchange.Buy(BuyPrice, BuyAmount, "Cost:¥", _N(UsedMoney), "Last transaction price", ticker["Last"])
    return True

def main():
    global LoopInterval, InitAccount
    CancelPendingOrders()
    InitAccount = _C(exchange.GetAccount)
    Log(InitAccount)
    if InitAccount["Balance"] < TotalBuyNet:
        raise Exception("Insufficient account balance")
    LoopInterval = max(LoopInterval, 1)
    while dispatch():
        Sleep(LoopInterval * 1000)
    Log("All commissions completed", _C(exchange.GetAccount))

Published by 发明者量化-小小梦 on the FMZ strategy square · last modified 2020-03-07. 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-Iceberg-Order-Buy.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