Skip to content

Latest commit

 

History

History
207 lines (169 loc) · 8.1 KB

子辰量化香农网格交易策略.md

File metadata and controls

207 lines (169 loc) · 8.1 KB

Name

子辰量化香农网格交易策略

Author

子辰量化

Strategy Arguments

Argument Default Description
totalInvestment 10000 总投资额
buyRatio 0.02 下跌多少买入
sellRatio 0.02 上涨多少卖出

Source (python)

##
# 香农网格交易策略(公开版)
# Author: 子辰量化
# Last Modified: 2024-1-4
##

import time

assetRatio = 0.5 # 资产投资比例

originalTotalMoney = totalInvestment # 基准投资额,总投资额+盈亏后的全部权益
originalAssetMoney = totalInvestment * assetRatio # 基准资产价值
originalCashMoney = totalInvestment * (1 - assetRatio) # 基准现金

remainCashMoney = originalCashMoney # 当前剩余现金
investAssetMoney = 0 # 当前资产价值
inverstAssetAmount = 0 # 当前资产数量

boolInited = False # 是否完成了首次建仓

i = 0 # tick计算

def num_cut(num, c):
    str_num = str(num)
    return float(str_num[:str_num.index('.') + 1 + c])

def onTick():
    global assetRatio
    global originalTotalMoney
    global originalAssetMoney
    global originalCashMoney
    global remainCashMoney
    global investAssetMoney
    global inverstAssetAmount
    global boolInited
    global i

    ticker = exchange.GetTicker()
    # Log(ticker)
    openTime = time.localtime(ticker.Time / 1000) # ticker time
    openTimeStr = time.strftime("%Y-%m-%dT%H:%M:%S", openTime) 
    price = ticker.Last

    # 初始建仓
    if not boolInited:
        money = originalAssetMoney
        id = exchange.Buy(-1, money) # 市价单
        # Log("order id:", id)
        order = exchange.GetOrder(id)
        Log("buy money:", money)
        Log("order id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:", order["DealAmount"], "AvgPrice:", order["AvgPrice"], "Status:", order["Status"], "Type:", order["Type"])
        money = order["Amount"] # 成交的money
        dealAmount = order["DealAmount"] # 已扣除手续费的资产数量
        price = order["AvgPrice"] # 成交均价
        investAssetMoney = originalAssetMoney
        remainCashMoney = originalCashMoney
        inverstAssetAmount = dealAmount       
        boolInited = True
        Log(f"use ${investAssetMoney} buy {inverstAssetAmount} asset at price ${price} at time {openTimeStr}")

        Log(f"{i} summary:")
        originalTotalMoney = originalAssetMoney + originalCashMoney
        investAssetMoney = inverstAssetAmount * price
        currentTotalMoney = investAssetMoney + remainCashMoney
        Log(f"originalAssetMoney: ${originalAssetMoney}")
        Log(f"originalCashMoney: ${originalCashMoney}")
        Log(f"originalTotalMoney: ${originalTotalMoney}")
        Log(f"inverstAssetAmount: ${inverstAssetAmount}")
        Log(f"investAssetMoney: ${investAssetMoney}")
        Log(f"remainCashMoney: ${remainCashMoney}")
        Log(f"currentTotalMoney: ${currentTotalMoney}")
        # account = exchange.GetAccount()
        # Log("Balance:", account["Balance"], "FrozenBalance:", account["FrozenBalance"], "Stocks:", account["Stocks"], "FrozenStocks:", account["FrozenStocks"])

    # 买入
    money = inverstAssetAmount * price # pirce
    if money < originalAssetMoney * (1 - buyRatio):
        money = originalAssetMoney * buyRatio / 2 # 买入金额
        account = exchange.GetAccount()
        if remainCashMoney > money and account["Balance"] > money: # 判断是否还有足够的现金,双重检查
            # amount = money / price
            id = exchange.Buy(-1, money) # 市价单
            # Log("order id:", id)
            order = exchange.GetOrder(id)
            Log("buy money:", money)
            Log("order id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:", order["DealAmount"], "AvgPrice:", order["AvgPrice"], "Status:", order["Status"], "Type:", order["Type"])
            money = order["Amount"] # 成交的money
            dealAmount = order["DealAmount"] # 已扣除手续费的资产数量
            price = order["AvgPrice"] # 成交均价  
            originalAssetMoney -= money #
            originalCashMoney -= money #
            remainCashMoney -= money
            inverstAssetAmount = inverstAssetAmount + dealAmount
            Log(f"bull/bear buy {dealAmount} asset at ${price} at time {openTimeStr}")

            Log(f"{i} summary:")
            originalTotalMoney = originalAssetMoney + originalCashMoney
            investAssetMoney = inverstAssetAmount * price
            currentTotalMoney = investAssetMoney + remainCashMoney
            Log(f"originalAssetMoney: ${originalAssetMoney}")
            Log(f"originalCashMoney: ${originalCashMoney}")
            Log(f"originalTotalMoney: ${originalTotalMoney}")
            Log(f"inverstAssetAmount: ${inverstAssetAmount}")
            Log(f"investAssetMoney: ${investAssetMoney}")
            Log(f"remainCashMoney: ${remainCashMoney}")
            Log(f"currentTotalMoney: ${currentTotalMoney}")
            # account = exchange.GetAccount()
            #Log("Balance:", account["Balance"], "FrozenBalance:", account["FrozenBalance"], "Stocks:", account["Stocks"], "FrozenStocks:", account["FrozenStocks"])

    # 卖出
    money = inverstAssetAmount * price # pirce
    if money > (originalAssetMoney * (1 + sellRatio)):
        money = originalAssetMoney * sellRatio / 2 # 卖出金额
        amount = money / price
        id = exchange.Sell(-1, amount) # 市价单
        # Log("order id:", id)
        order = exchange.GetOrder(id)
        Log("sell money:", money)
        Log("sell amount:", amount)
        Log("order id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:", order["DealAmount"], "AvgPrice:", order["AvgPrice"], "Status:", order["Status"], "Type:", order["Type"])
        amount = order["Amount"] # 计划卖出资产数量
        dealAmount = order["DealAmount"] # 成交资产数量,这里好像是从balance扣除的手续费吗?
        # 从日志来看amount == dealAmount,所以手续费是从balance扣除的
        price = order["AvgPrice"] # 成交均价
        dealMoney = dealAmount * price # 未扣除手续费
        remainCashMoney += dealMoney # 这里需要减去手续费
        originalAssetMoney += money #
        originalCashMoney += money #
        inverstAssetAmount = inverstAssetAmount - dealAmount
        Log(f"bull/bear sell {amount} asset at ${price} at time {openTimeStr}")

        Log(f"{i} summary:")
        originalTotalMoney = originalAssetMoney + originalCashMoney
        investAssetMoney = inverstAssetAmount * price
        currentTotalMoney = investAssetMoney + remainCashMoney
        Log(f"originalAssetMoney: ${originalAssetMoney}")
        Log(f"originalCashMoney: ${originalCashMoney}")
        Log(f"originalTotalMoney: ${originalTotalMoney}")
        Log(f"inverstAssetAmount: ${inverstAssetAmount}")
        Log(f"investAssetMoney: ${investAssetMoney}")
        Log(f"remainCashMoney: ${remainCashMoney}")
        Log(f"currentTotalMoney: ${currentTotalMoney}")
        # account = exchange.GetAccount()
        # Log("Balance:", account["Balance"], "FrozenBalance:", account["FrozenBalance"], "Stocks:", account["Stocks"], "FrozenStocks:", account["FrozenStocks"])

    # tick计数
    i = i + 1

def main():
    Log(totalInvestment, buyRatio, sellRatio)

    while True:
        onTick()
        Sleep(1000) # 1秒

def onexit():
    global inverstAssetAmount

    # 清仓
    Log("清仓")
    if inverstAssetAmount > 0:
        amount = num_cut(inverstAssetAmount * (1-0.0001), 8) # 留0.01%一丢丢,小数位控制
        id = exchange.Sell(-1, amount) # 市价单
        Log("order id:", id)
        order = exchange.GetOrder(id)
        Log("order id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:", order["DealAmount"], "AvgPrice:", order["AvgPrice"], "Status:", order["Status"], "Type:", order["Type"])        
    # 倒计时
    beginTime = time.time() * 1000
    while True:
        ts = time.time() * 1000
        Log("程序停止倒计时...,已经过去:", (ts - beginTime) / 1000, "秒!")
        Sleep(1000) # 1秒

Detail

https://www.fmz.com/strategy/425193

Last Modified

2024-01-04 13:48:44