8
Follow
1369
Followers
균형 잡힌 질서 전략 (교수 전략)
Created 2020-09-02 17:05:25 Updated 2024-12-10 10:09:34
0
2850
균형 잡힌 질서 전략 (교수 전략)
이 기사에서 설명하는 전략은 본질적으로 동적 균형 전략으로, 코인의 가치를 항상 결제 통화의 가치와 같게 유지하는 것입니다. 하지만 이 게임은 사전 주문형으로 설계되었으며 전략적 논리는 매우 간단합니다. 이 전략을 작성하는 주된 목적은 전략 설계의 다양한 측면을 보여주는 것입니다.
-
정책 논리 캡슐화
전략 논리와 일부 런타임 데이터, 태그 변수를 함께 캡슐화합니다(객체로 캡슐화). -
전략은 초기화 코드를 처리합니다.
초기 실행 중에 초기 계정 정보는 이익 계산을 위해 기록됩니다. 초기에 데이터를 복원할지 여부는 매개변수에 따라 결정됩니다. -
정책 상호작용 처리를 위한 코드
간단한 일시 정지와 계속 상호작용 과정이 설계되었습니다. -
전략 수익률 계산을 위한 코드
통화 기준 방법을 사용하여 이익을 계산합니다. -
전략에서 핵심 데이터의 지속성을 위한 메커니즘
데이터를 복구하는 메커니즘을 설계하세요 -
정책 처리 정보를 표시하기 위한 코드
상태 표시줄에 데이터가 표시됩니다.
전략 코드
javascript
var Shannon = {
// member
e : exchanges[0],
arrPlanOrders : [],
distance : BalanceDistance,
account : null,
ticker : null,
initAccount : null,
isAskPending : false,
isBidPending : false,
// function
CancelAllOrders : function (e) {
while(true) {
var orders = _C(e.GetOrders)
if(orders.length == 0) {
return
}
Sleep(500)
for(var i = 0; i < orders.length; i++) {
e.CancelOrder(orders[i].Id, orders[i])
Sleep(500)
}
}
},
Balance : function () {
if (this.arrPlanOrders.length == 0) {
this.CancelAllOrders(this.e)
var acc = _C(this.e.GetAccount)
this.account = acc
var askPendingPrice = (this.distance + acc.Balance) / acc.Stocks
var bidPendingPrice = (acc.Balance - this.distance) / acc.Stocks
var askPendingAmount = this.distance / 2 / askPendingPrice
var bidPendingAmount = this.distance / 2 / bidPendingPrice
this.arrPlanOrders.push({tradeType : "ask", price : askPendingPrice, amount : askPendingAmount})
this.arrPlanOrders.push({tradeType : "bid", price : bidPendingPrice, amount : bidPendingAmount})
} else if(this.isAskPending == false && this.isBidPending == false) {
for(var i = 0; i < this.arrPlanOrders.length; i++) {
var tradeFun = this.arrPlanOrders[i].tradeType == "ask" ? this.e.Sell : this.e.Buy
var id = tradeFun(this.arrPlanOrders[i].price, this.arrPlanOrders[i].amount)
if(id) {
this.isAskPending = this.arrPlanOrders[i].tradeType == "ask" ? true : this.isAskPending
this.isBidPending = this.arrPlanOrders[i].tradeType == "bid" ? true : this.isBidPending
} else {
Log("挂单失败,清理!")
this.CancelAllOrders(this.e)
return
}
}
}
if(this.isBidPending || this.isAskPending) {
var orders = _C(this.e.GetOrders)
Sleep(1000)
var ticker = _C(this.e.GetTicker)
this.ticker = ticker
if(this.isAskPending) {
var isFoundAsk = false
for (var i = 0; i < orders.length; i++) {
if(orders[i].Type == ORDER_TYPE_SELL) {
isFoundAsk = true
}
}
if(!isFoundAsk) {
Log("卖单成交,撤销订单,重置")
this.CancelAllOrders(this.e)
this.arrPlanOrders = []
this.isAskPending = false
this.isBidPending = false
LogProfit(this.CalcProfit(ticker))
return
}
}
if(this.isBidPending) {
var isFoundBid = false
for(var i = 0; i < orders.length; i++) {
if(orders[i].Type == ORDER_TYPE_BUY) {
isFoundBid = true
}
}
if(!isFoundBid) {
Log("买单成交,撤销订单,重置")
this.CancelAllOrders(this.e)
this.arrPlanOrders = []
this.isAskPending = false
this.isBidPending = false
LogProfit(this.CalcProfit(ticker))
return
}
}
}
},
ShowTab : function() {
var tblPlanOrders = {
type : "table",
title : "计划挂单",
cols : ["方向", "价格", "数量"],
rows : []
}
for(var i = 0; i < this.arrPlanOrders.length; i++) {
tblPlanOrders.rows.push([this.arrPlanOrders[i].tradeType, this.arrPlanOrders[i].price, this.arrPlanOrders[i].amount])
}
var tblAcc = {
type : "table",
title : "账户信息",
cols : ["type", "Stocks", "FrozenStocks", "Balance", "FrozenBalance"],
rows : []
}
tblAcc.rows.push(["初始", this.initAccount.Stocks, this.initAccount.FrozenStocks, this.initAccount.Balance, this.initAccount.FrozenBalance])
tblAcc.rows.push(["当前", this.account.Stocks, this.account.FrozenStocks, this.account.Balance, this.account.FrozenBalance])
return "时间:" + _D() + "\n `" + JSON.stringify([tblPlanOrders, tblAcc]) + "`" + "\n" + "ticker:" + JSON.stringify(this.ticker)
},
CalcProfit : function(ticker) {
var acc = _C(this.e.GetAccount)
this.account = acc
return (this.account.Balance - this.initAccount.Balance) + (this.account.Stocks - this.initAccount.Stocks) * ticker.Last
},
Init : function() {
this.initAccount = _C(this.e.GetAccount)
if(IsReset) {
var acc = _G("account")
if(acc) {
this.initAccount = acc
} else {
Log("恢复初始账户信息失败!以初始状态运行!")
_G("account", this.initAccount)
}
} else {
_G("account", this.initAccount)
LogReset(1)
LogProfitReset()
}
},
Exit : function() {
Log("停止前,取消所有挂单...")
this.CancelAllOrders(this.e)
}
}
function main() {
// 初始化
Shannon.Init()
// 主循环
while(true) {
Shannon.Balance()
LogStatus(Shannon.ShowTab())
// 交互
var cmd = GetCommand()
if(cmd) {
if(cmd == "stop") {
while(true) {
LogStatus("暂停", Shannon.ShowTab())
cmd = GetCommand()
if(cmd) {
if(cmd == "continue") {
break
}
}
Sleep(1000)
}
}
}
Sleep(5000)
}
}
function onexit() {
Shannon.Exit()
}
백테스트 실행
확장 프로그램 최적화
- 가상 주문 메커니즘을 추가할 수 있습니다. 일부 거래소에는 주문 한도가 있으므로 실제로 주문이 이루어지지 않을 수 있습니다. 실제 주문을 하기 전에 가격이 가까워질 때까지 기다려야 합니다.
- 선물거래에 참여하세요
- 다양한 종류와 다양한 거래소로 확장
이 전략은 교육 목적으로만 사용되며 실제 거래에서는 주의해서 사용해야 합니다.
전략 주소: https://www.fmz.com/strategy/225746
Related Recommendations
Visualization module to build trading strategies - in-depthUse the KLineChart function to make strategy drawing design easierJavaScript strategy backtesting is debugged in DevTools of Chrome browserDetailed Explanation of Equilibrium & Grid StrategiesDesign a Multiple-Chart Plotting LibraryRSI2 Mean Reversion Strategy using in futuresThe futures and cryptocurrency API explanationQuickly implement a semi-automatic quantitative trading toolIntroducing the Aroon indicatorPreliminary Study on Backtesting of Digital Currency Options Strategy
Comment
All comments (0)
No data
- 1




