1. 链一财经首页
  2. 资讯

比特币搬砖对冲策略Python源码

策略复制地址:https://www.fmz.com/strategy/21023 

直接登陆FMZ发明者量化平台即可复制。

策略原理

比特币搬砖策略是入门程序化交易的基础策略。原理简单,是新手尝试程序化的好选择,在其黄金时期,比特币搬砖也带来大量的利润。掌握此策略需要有一定的基础。
长期来看,两个交易所比特币的差价应该稳定的,如果存在足够的差价,我们便可以在价格低的交易所买入币,在价格高的交易所卖出币。这样一来两个交易所持有的币总量没变,但价值却增加了。这就是搬砖的基础原理。

策略参数:

主要设置差价和操作量,其中差价设为交互模式

 

比特币搬砖对冲策略Python源码

 

策略源码:

比特币搬砖对冲策略Python源码

import timenimport jsonnndef cancelAll():n    ret = Falsen    for e in exchanges:n        while True:n            n = 0n            for order in _C(e.GetOrders):n                ret = Truen                e.CancelOrder(order.Id)n                n+=1n            if n == 0:n                breakn    return retnndef main():n    global MinSpreadA, MinSpreadBn    SetErrorFilter("canceled")n    if len(exchanges) != 2:n        raise Exception("只支持两个交易所对冲")n    n    LogReset()n    LogProfitReset()n    cancelAll()n    n    initStocks = 0.0n    initBalance = 0.0n    minAmount = 0.1n    lastTradeTime = 0n    lastTradeErrExchange = ''n    accountsCache = []n    hedgeNum = [0, 0]n    names = []n    baseCurrency = exchange.GetCurrency()n    for e in exchanges:n        if e.GetCurrency() != baseCurrency:n            raise Exception("必须是同样的货币才可以对冲 " + baseCurrency)n        names.append(e.GetName())n        account = _C(e.GetAccount)n        accountsCache.append(account)n        initStocks += account.Stocksn        initBalance += account.Balancen        Log("Switch", e.GetLabel(), "To", e.IO("websocket"))n    minAmount = 0.01 if baseCurrency == "BTC" else 0.1n    Log("总钱:", _N(initBalance), "总币", _N(initStocks), 'Python:', __import__('sys').version)n    while True:n        if not accountsCache:n            accountsCache = [_C(e.GetAccount) for e in exchanges]n        Sleep(LoopInterval)n        cmd = GetCommand()n        if cmd:n            Log("CMD", cmd)n            arr = cmd.split(':')n            if arr[0] == 'A->B':n                MinSpreadA = float(arr[1])n            elif arr[0] == 'B->A':n                MinSpreadB = float(arr[1])n                n        depthA = exchanges[0].GetDepth()n        if not depthA:n            continuen        depthB = exchanges[1].GetDepth()n        if not depthB:n            continuen        if lastTradeTime > 0 and time.time() - lastTradeTime > BalanceTime:n            needUpdate = cancelAll()n            if not needUpdate:n                for account in accountsCache:n                    if account.FrozenBalance >= 0.1 or account.FrozenStocks > 0.001:n                        needUpdate = Truen                        breakn            if needUpdate:            n                accountsCache = [_C(e.GetAccount) for e in exchanges]n            nowStocks = 0.0n            nowBalance = 0.0n            for account in accountsCache:n                nowStocks += account.Stocksn                nowBalance += account.Balancen            diff = _N(nowStocks - initStocks, 5)n            isReverse = Nonen            if abs(diff) < minAmount:n                LogProfit(_N(nowBalance-initBalance, 3), "总钱:", _N(nowBalance), "总币", _N(nowStocks), "币差:", diff)n                lastTradeTime = 0n            elif diff > minAmount:n                isReverse = depthA.Bids[0].Price < depthB.Bids[0].Pricen            elif -diff > minAmount:n                isReverse = depthA.Asks[0].Price > depthB.Asks[0].Pricen            if isReverse is not None:n                depths = [depthA, depthB]n                opAmount = Nonen                for pos in ([1, 0] if isReverse else [0, 1]):n                    if diff >= minAmount:n                        opAmount = min(diff, accountsCache[pos].Stocks, depths[pos].Bids[0].Amount + depths[pos].Bids[1].Amount)n                        diff -= opAmountn                        if opAmount >= minAmount:n                            exchanges[pos].Sell(depths[pos].Bids[1].Price, opAmount)n                    elif -diff >= minAmount:n                        opAmount = min(-diff, _N(accountsCache[pos].Balance / depths[pos].Asks[1].Price, 3), depths[pos].Asks[0].Amount + depths[pos].Asks[1].Amount)n                        diff += opAmountn                        if opAmount >= minAmount:n                            exchanges[pos].Buy(depths[pos].Asks[1].Price, opAmount)n                if opAmount is not None:n                    lastTradeTime = time.time()n                    accountsCache = []n            continuen            # end of balanceAccountnn        diffA = _N(depthA.Bids[0].Price - depthB.Asks[0].Price, 3)n        diffB = _N(depthB.Bids[0].Price - depthA.Asks[0].Price, 3)n        LogStatus('`' + json.dumps({'type': 'table', 'title': '运行信息', 'cols': ['名称', '钱', '冻结的钱', '币', '冻结的币', '买一', '卖一', '阀值', '差价', '次数'], 'rows': [[names[0], accountsCache[0].Balance, accountsCache[0].FrozenBalance, accountsCache[0].Stocks, accountsCache[0].FrozenStocks, depthA.Bids[0].Price, depthA.Asks[0].Price, MinSpreadA, diffA, hedgeNum[0]], [names[1], accountsCache[1].Balance, accountsCache[1].FrozenBalance, accountsCache[1].Stocks, accountsCache[1].FrozenStocks, depthB.Bids[0].Price, depthB.Asks[0].Price, MinSpreadB, diffB, hedgeNum[0]]]}) + '`')n        HPos = 0n        if diffA >= MinSpreadA:n            orderH = depthA.Bids[0]n            orderL = depthB.Asks[0]n            exchangeH = exchanges[0]n            exchangeL = exchanges[1]n            accountH = accountsCache[0]n            accountL = accountsCache[1]n        elif diffB >= MinSpreadB:n            HPos = 1n            orderH = depthB.Bids[0]n            orderL = depthA.Asks[0]n            exchangeH = exchanges[1]n            exchangeL = exchanges[0]n            accountH = accountsCache[1]n            accountL = accountsCache[0]n        else:n            continuenn        opPrice = _N((orderH.Price + orderL.Price) / 2.0, 2)n        opAmount = min(MaxAmount, orderH.Amount, orderL.Amount, accountH.Stocks, _N(accountL.Balance / opPrice, 3))n        if opAmount >= minAmount:n            tasks = [[exchangeH.Sell, "H"], [exchangeL.Buy, "L"]]n            if lastTradeErrExchange == "L":n                tasks.reverse()n            lastTradeErrExchange = ""n            for task in tasks:n                if task[0](opPrice, opAmount) is None:n                    lastTradeErrExchange = task[1]n                    breakn            lastTradeTime = time.time()n            accountsCache = []n            hedgeNum[HPos] += 1

比特币搬砖对冲策略Python源码

根据国家《关于防范代币发行融资风险的公告》,大家应警惕代币发行融资与交易的风险隐患。

本文来自LIANYI转载,不代表链一财经立场,转载请联系原作者。

发表评论

登录后才能评论

联系我们

微信:kkyves

邮件:kefu@lianyi.com

时间:7x24,节假日bu休息

QR code