Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a Grid Strategy in Python

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to implement a grid strategy in Python. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Policy code''backteststart: 2019-07-01 00:00:00end: 2020-01-03 00:00:00period: 1mexchanges: [{"eid": "OKEX" "currency": "BTC_USDT"}]''import json# parameter beginPrice = 5000 # Grid interval start price endPrice = 8000 # Grid interval end price distance = 20 # Price distance of each grid node pointProfit = 50 # profit difference of each grid node minBalance = 300 # minimum balance of accounts Uh (time of purchase) # Global variable arrNet = [] arrMsg = [] acc = Nonedef findOrder (orderId NumOfTimes, ordersList = []: for j in range (NumOfTimes): orders = None if len (ordersList) = = 0: orders = _ C (exchange.GetOrders) else: orders = ordersList for i in range (len (orders)): if orderId = orders [I] ["Id"]: return True Sleep (1000) return Falsedef cancelOrder (price OrderType): orders = _ C (exchange.GetOrders) for i in range (len (orders)): if price = = orders [I] ["Price"] and orderType = = orders [I] ["Type"]: exchange.CancelOrder (orders [I] ["Id"]) Sleep (500) def checkOpenOrders (orders, ticker): global arrNet ArrMsg for i in range (len (arrNet)): if not findOrder (arrNet [I] ["id"], 1, orders) and arrNet [I] ["state"] = "pending": orderId = exchange.Sell (arrNet [I] ["coverPrice"], arrNet [I] ["amount"], arrNet [I] Ticker) if orderId: arrNet [I] ["state"] = "cover" arrNet [I] ["id"] = orderId else: # Undo cancelOrder (arrNet [I] ["coverPrice"] ORDER_TYPE_SELL) arrMsg.append ("failed to order!" + json.dumps (arrnet [I]) + ", time:" + _ D () def checkCoverOrders (orders, ticker): global arrNet, arrMsg for i in range (len (arrNet)): if not findOrder (arrnet [I] ["id"], 1 Orders) and arrNet [I] ["state"] = = "cover": arrNet [I] ["id"] =-1 arrNet [I] ["state"] = "idle" Log (arrNet [I], "Node closing" Reset to idle state. " , "# FF0000") def onTick (): global arrNet, arrMsg, acc ticker = _ C (exchange.GetTicker) # every time you get the latest quotation for i in range (len (arrNet)): # iterate through all the grid nodes, find out the location where you need to hang the order according to the current market, and pay for it. If I! = len (arrNet)-1 and arrNet [I] ["state"] = = "idle" and ticker.Sell > arrNet [I] ["price"] and ticker.Sell

< arrNet[i + 1]["price"]: acc = _C(exchange.GetAccount) if acc.Balance < minBalance : # 如果钱不够了,只能跳出,什么都不做了。 arrMsg.append("资金不足" + json.dumps(acc) + "!" + ", time:" + _D()) break orderId = exchange.Buy(arrNet[i]["price"], arrNet[i]["amount"], arrNet[i], ticker) # 挂买单 if orderId : arrNet[i]["state"] = "pending" # 如果买单挂单成功,更新网格节点状态等信息 arrNet[i]["id"] = orderId else : # 撤单 cancelOrder(arrNet[i]["price"], ORDER_TYPE_BUY) # 使用撤单函数撤单 arrMsg.append("挂单失败!" + json.dumps(arrNet[i]) + ", time:" + _D()) Sleep(1000) orders = _C(exchange.GetOrders) checkOpenOrders(orders, ticker) # 检测所有买单的状态,根据变化做出处理。 Sleep(1000) orders = _C(exchange.GetOrders) checkCoverOrders(orders, ticker) # 检测所有卖单的状态,根据变化做出处理。 # 以下为构造状态栏信息,可以查看FMZ API 文档。 tbl = { "type" : "table", "title" : "网格状态", "cols" : ["节点索引", "详细信息"], "rows" : [], } for i in range(len(arrNet)) : tbl["rows"].append([i, json.dumps(arrNet[i])]) errTbl = { "type" : "table", "title" : "记录", "cols" : ["节点索引", "详细信息"], "rows" : [], } orderTbl = { "type" : "table", "title" : "orders", "cols" : ["节点索引", "详细信息"], "rows" : [], } while len(arrMsg) >

ArrMsg.pop (0) for i in range (len (arrMsg)): errTbl ["rows"]. Append ([I, json.dumps (arrMsg [I])) for i in range (len (orders)): orderTbl ["rows"] .append ([I, json.dumps (orders[ I])) LogStatus (_ D (), "\ n", acc, "\ n", "arrMsg length:", len (arrMsg)) "\ n", "`" + json.dumps ([tbl, errTbl, orderTbl]) + "`" def main (): # Policy execution starts here global arrNet for i in range ((endPrice-beginPrice) / distance): # for this cycle constructs the data structure of the grid based on the parameters Is a list that stores each grid node The information for each grid node is as follows: arrNet.append ({"price": beginPrice + I * distance, # amount of this node "amount": amount, # order quantity "state": "idle" # pending / cover / idle # Node status "coverPrice": beginPrice + I * distance + pointProfit, # Node closing Price "id":-1, # Node current related order ID}) while True: # after the grid data structure is constructed Enter the policy main cycle onTick () # the processing function on the main loop, the main processing logic Sleep (500) # controls the polling frequency

The main design idea of the strategy is to compare the current hanging list returned by the GetOrders interface according to the grid data structure maintained by ourselves. Analyze the change of the hanging order (whether it is closed or not), update the grid data structure, and make the follow-up operation. And the hanging order will not be cancelled until the transaction, even if the price deviation will not be cancelled, because there are often pins in the digital money market, and these hanging orders may also receive the order of the pin (if the exchange has a limit on the number of hanging orders, then it has to be adjusted).

Policy data visualization, using the LogStatus function to display the data in real time on the status bar.

Tbl = {"type": "table", "title": "Grid status", "cols": ["Node Index", "details"], "rows": [],} for i in range (len (arrNet)): tbl ["rows"] .append ([I) Json.dumps (arrNet [I]) errTbl = {"type": "table", "title": "record", "cols": ["Node Index", "details"], "rows": [],} orderTbl = {"type": "table", "title": "orders" "cols": ["Node Index", "details"], "rows": [],}

Three tables are constructed, the first table displays the information of each node in the current grid data structure, the second table shows the abnormal information, and the third table shows the actual order information of the exchange.

Back test

After reading the above, do you have any further understanding of how to implement a grid strategy in Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report