【问题标题】:Google Cloud Functions - How to set up a function (trading bot)Google Cloud Functions - 如何设置功能(交易机器人)
【发布时间】:2020-09-24 19:15:43
【问题描述】:

我想通过 Google Cloud 设置一个交易机器人来全天候运行。

在 Google Cloud Functions 中,我使用运行时 Python 3.7 的内联编辑器。

我有两个问题:

1) Main.py 部分: 这里我复制了我的 Python 脚本(Trading Bot)的完整代码 - 请参阅下面的代码以供参考(在我的 IDE Spyder 中作为脚本运行时效果很好)。 然而,谷歌下面要求提供一个函数来执行。但是,我的代码只是一个没有主要功能的脚本。我可以把代码放在顶部,例如:“def trading_bot(self):”,然后缩进下面的剩余部分吗? 虽然下面复制的代码作为脚本运行良好,但如果我在我的 IDE(Spyder)的顶部添加“def trading_bot(self):”,代码似乎无法正常工作......我怎样才能确保代码当我从 Google Cloud(或我的 IDE)调用该函数时,该函数内的函数运行正常。

2)Requirements.txt 部分:您能否提供指导,我需要在那里放置什么,即我可以在某处查找我的代码中使用的依赖项吗?我使用 Anaconda 进行分发,为脚本导入的类位于下面提供的脚本的顶部。

感谢您的帮助。如果您认为 Google Cloud Functions 不是运行交易机器人的最佳方法,但在我看来它似乎是最简单的解决方案,也很高兴收到您的建议。

import bitmex
import json
from time import sleep

from bitmex_websocket import BitMEXWebsocket
import logging, time, requests

import numpy as np
import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt


import warnings
warnings.filterwarnings("ignore")

from datetime import datetime
import math
from statistics import mean

#-------------------------

#variable
symbol = "XBTUSD"

#standard API connection
api_key = "XXX"
api_secret = "XXX"
#True for testnet
client = bitmex.bitmex(test=False, api_key=api_key, api_secret=api_secret)

#------------------
# Trading algorithm

symbol = "XBTUSD"
ordType = 'Stop'
#starting order quantity
orderQty = 1

leftBars = 6
rightBars = 2

#round to 0.5
def round_to_BTC(n):
    result = round(n*2)/2
    return result

t=1
while t < 1000000:

    time_now = (time.strftime('%H:%M:%S', time.localtime(int(time.time()))))

    t_now = time_now[6:8]
    t1 = "00"
    t2 = "59"    
    FMT = '%S'

    def days_hours_minutes_seconds(td):
        return td.days, td.seconds//3600, (td.seconds//60)%60, td.seconds      

    if t_now == str('00'):
        #give 1 second to candlestick to properly close
        sleep(1)
    elif t_now > str('00') and t_now <= str('59'):
        s1 = datetime.strptime(t2, FMT) - datetime.strptime(t_now, FMT)
        s1_seconds = days_hours_minutes_seconds(s1)[3]+2
        sleep(s1_seconds)
    else:
        pass

    time_now = (time.strftime('%H:%M:%S', time.localtime(int(time.time()))))
    print("The time is now: " + time_now)


    #most recent swing candles, get highs and lows / #binsizes = {"1m": 1, "5m": 5, "1h": 60, "1d": 1440}
    #+1 is the middle bar
    totalBars = leftBars + rightBars + 1
    swing_candles = client.Trade.Trade_getBucketed(symbol=symbol, binSize="1m", count=totalBars, reverse=True).result()[0]

    last_highs = []
    last_lows = []

    i=0
    while i <= (len(swing_candles)-1):
        last_highs.append(swing_candles[i]["high"])
        last_lows.append(swing_candles[i]["low"])
        i += 1

    #get the highest high and the lowest low
    highest_high = max(last_highs)
    lowest_low = min(last_lows)

    #check if there are existing positions & orders
    if client.Position.Position_get().result()[0] != []:
        positions_quantity = client.Position.Position_get().result()[0][0]["currentQty"]
    else:
        positions_quantity = 0

    #check existing orders
    buy_orders_quantity = []
    sell_orders_quantity = []
    orders_quantity = client.Order.Order_getOrders(filter=json.dumps({"open": True})).result()[0]   

    h=0
    while h <= len(orders_quantity)-1:
        if orders_quantity[h]["side"] == "Sell":
            sell_orders_quantity.append(orders_quantity[h])
        elif orders_quantity[h]["side"] == "Buy":
            buy_orders_quantity.append(orders_quantity[h])            
        h += 1 


    if highest_high == last_highs[rightBars] and positions_quantity == 0:
        if buy_orders_quantity == []:

            client.Order.Order_new(symbol = symbol, orderQty = orderQty*1, side = "Buy", ordType = 'Stop', stopPx = (highest_high+0.5), execInst ='LastPrice' ).result()

        elif buy_orders_quantity != []:
            orderID = buy_orders_quantity[0]["orderID"]
            client.Order.Order_amend(orderID=orderID, orderQty=orderQty*1, stopPx = (highest_high+0.5)).result()
        else:
            pass

    elif highest_high == last_highs[rightBars] and positions_quantity > 0:
            #dont place any additional long
            pass

    elif highest_high == last_highs[rightBars] and positions_quantity < 0:
        if buy_orders_quantity != []:
            orderID = buy_orders_quantity[0]["orderID"]
            client.Order.Order_amend(orderID=orderID, orderQty=orderQty*2, stopPx = (highest_high+0.5)).result()    
        else: 
            client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*2, side = "Buy", ordType = 'Stop', stopPx = (highest_high+0.5), execInst ='LastPrice' ).result()


    elif lowest_low == last_lows[rightBars] and positions_quantity == 0:
        if sell_orders_quantity == []:

            client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*-1, side = "Sell", ordType = 'Stop', stopPx = (lowest_low-0.5), execInst ='LastPrice' ).result()

        elif sell_orders_quantity != []:
            orderID = sell_orders_quantity[0]["orderID"]
            client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-1, stopPx = (lowest_low-0.5)).result()
        else:
            pass        

    elif lowest_low == last_lows[rightBars] and positions_quantity < 0:
            #dont place any additional shorts
            pass       

    elif lowest_low == last_lows[rightBars] and positions_quantity > 0:
        if sell_orders_quantity != []:
            orderID = sell_orders_quantity[0]["orderID"]
            client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-2, stopPx = (lowest_low-0.5)).result()    
        else:  
            client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*-2, side = "Sell", ordType = 'Stop', stopPx = (lowest_low-0.5), execInst ='LastPrice' ).result()


    positions_quantity = client.Position.Position_get().result()[0][0]["currentQty"]

    buy_orders_quantity = []
    sell_orders_quantity = []
    orders_quantity = client.Order.Order_getOrders(filter=json.dumps({"open": True})).result()[0]   

    h=0
    while h <= len(orders_quantity)-1:
        if orders_quantity[h]["side"] == "Sell":
            sell_orders_quantity.append(orders_quantity[h])
        elif orders_quantity[h]["side"] == "Buy":
            buy_orders_quantity.append(orders_quantity[h])            
        h += 1

    if positions_quantity > 0:
        if sell_orders_quantity != []:
            orderID = sell_orders_quantity[0]["orderID"]
            client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-2).result()
    elif positions_quantity < 0:
        if buy_orders_quantity != []:
            orderID = buy_orders_quantity[0]["orderID"]
            client.Order.Order_amend(orderID=orderID, orderQty=orderQty*2).result()


    print("Your current position is " + str(positions_quantity))
    print("This is iteration: " + str(t))
    t += 1

【问题讨论】:

    标签: google-cloud-functions


    【解决方案1】:

    关于我的第二个问题,我通过以下方式解决了它: 在命令终端中,输入:pip freeze > requirements.txt 该文件包含所有依赖项。

    关于问题 1,我仍然不明白究竟需要在 main.py 部分中放入什么代码。

    谢谢!

    【讨论】:

      【解决方案2】:

      Cloud Functions 不适合您的用例。它们主要用于轻量级计算或不高资源消耗的方法。

      CF 的魔力在于,只要您点击属于它的 URL,它们就会执行您的代码。对于您的问题 1,了解这一点很重要。如果您希望您的函数正常工作,您需要始终创建一个接受“请求”参数的方法。因为它是来自命中 URL 时发出的 HTTP 请求的信息。

      您可以查看this document 以供参考。

      你的函数应该总是这样开始

       from flask #import your dependencies
      
       def my_awesome_function(request):
              #Your logic
      

      在这种情况下,您应该在 Function to Execute 文本框上写上“my_awesome_function”。

      您还必须小心您的资源,因为 CF 有 5 个演示文稿。它们在 CPU 和内存方面有所不同,您可以阅读更多关于此的信息 here.

      这有很多原因,您不应该将 Cloud Functions 用于您的机器人。我可以建议您使用虚拟机,但未经 Google 事先书面批准而使用服务进行加密货币挖掘相关的活动是不受欢迎的,并且可能会导致您的产品被停用,如 terms of service.

      中所述

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-18
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-30
        • 2020-03-11
        相关资源
        最近更新 更多