鍵.png)
使用這些基本 REST API 最佳實踐構(gòu)建出色的 API
while(true){
//strategy content
Sleep(Interval * 1000) //Sleep
}
}
由于各種原因,機器人可能會反復(fù)重啟,如錯誤、參數(shù)更新、策略更新等,因此需要保存一些數(shù)據(jù)以便下次啟動。以下是如何保存初始凈值以計算回報的示例。_G() 函數(shù)可以存儲各種數(shù)據(jù)。_G(key, value) 可以存放 value 的值,并用 _G(key) 調(diào)用它,其中 key 是一個字符串。
let init_eq = 0 //defining initial equity
if(!_G('init_eq')){ //If there is no storage, _G('init_eq') returns null.
init_eq = total_eq
_G('init_eq', total_eq) //Since there is no storage, the initial equity is the current equity and is stored here
}else{
init_eq = _G('init_eq') //If stored, read the value of the initial equity
}
在通過 API 獲取持倉、行情等數(shù)據(jù)時,可能由于各種原因返回錯誤。直接調(diào)用數(shù)據(jù)可能導(dǎo)致策略因錯誤停止,因此需要一種容錯機制。_C() 函數(shù)將在遇到錯誤時自動重試,直到返回正確的數(shù)據(jù)?;蛘邫z查返回后的數(shù)據(jù)是否可用。
let pos = _C(exchange.GetPosition, pair)
let ticker_A = exchange.GetTicker(pair_a)
let ticker_B = exchange.GetTicker(pair_b)
if(!ticker_A || !ticker_B){
continue //If the data is not available, exit the loop.
}
GetPosition、GetTicker 和 GetRecords 等函數(shù)可以加上交易對參數(shù)來獲取相關(guān)數(shù)據(jù),無需設(shè)置交易所綁定的交易對,這大大提升了多交易對策略的兼容性。有關(guān)具體的升級內(nèi)容,請參見文章:https://www.fmz.com/bbs-topic/10456。當(dāng)然,您需要最新的 docker 來支持它。如果您的 docker 版本過舊,則需要進行升級。
如果您仍然不明白,您可以使用 FMZ 的 API 文檔、調(diào)試工具以及市面上常用的 AI 對話工具來解決您的問題。
function GetPosition(pair){
let pos = _C(exchange.GetPosition, pair)
if(pos.length == 0){ //Returns null to indicate no position
return {amount:0, price:0, profit:0}
}else if(pos.length > 1){ //The strategy should be set to unidirectional position mode
throw 'Bidirectional positions are not supported'
}else{ //For convenience, long positions are positive and short positions are negative
return {amount:pos[0].Type == 0 ? pos[0].Amount : -pos[0].Amount, price:pos[0].Price, profit:pos[0].Profit}
}
}
function GetRatio(){
let kline_A = exchange.GetRecords(Pair_A+"_"+Quote+".swap", 60*60, N) //Hourly K-line
let kline_B = exchange.GetRecords(Pair_B+"_"+Quote+".swap", 60*60, N)
let total = 0
for(let i= Math.min(kline_A.length,kline_B.length)-1; i >= 0; i--){ //Calculate in reverse to avoid the K-line being too short.
total += kline_A[i].Close / kline_B[i].Close
}
return total / Math.min(kline_A.length,kline_B.length)
}
function GetAccount(){
let account = _C(exchange.GetAccount)
let total_eq = 0
if(exchange.GetName == 'Futures_OKCoin'){ //Since the API here is not compatible, only OKX Futures Exchange obtains the total equity currently.
total_eq = account.Info.data[0].totalEq //The equity information of other exchanges is also included. You can look for it yourself in the exchange API documentation.
}else{
total_eq = account.Balance //Temporary use of available balances on other exchanges will cause errors in calculating returns, but will not affect the use of strategies.
}
let init_eq = 0
if(!_G('init_eq')){
init_eq = total_eq
_G('init_eq', total_eq)
}else{
init_eq = _G('init_eq')
}
LogProfit(total_eq - init_eq)
return total_eq
}
function main(){
var precision = exchange.GetMarkets() //Get the precision here
var last_get_ratio_time = Date.now()
var ratio = GetRatio()
var total_eq = GetAccount()
while(true){
let start_loop_time = Date.now()
if(Date.now() - last_get_ratio_time > 10*60*1000){ //Update the average price and account information every 10 minutes
ratio = GetRatio()
total_eq = GetAccount()
last_get_ratio_time = Date.now()
}
let pair_a = Pair_A+"_"+Quote+".swap" //The trading pair is set as BTC_USDT.swap
let pair_b = Pair_B+"_"+Quote+".swap"
let CtVal_a = "CtVal" in precision[pair_a] ? precision[pair_a].CtVal : 1 //Some exchanges use sheets to represent quantity, such as one sheet represents 0.01 coin, so you need to convert.
let CtVal_b = "CtVal" in precision[pair_b] ? precision[pair_b].CtVal : 1 //No need to include this field
let position_A = GetPosition(pair_a)
let position_B = GetPosition(pair_b)
let ticker_A = exchange.GetTicker(pair_a)
let ticker_B = exchange.GetTicker(pair_b)
if(!ticker_A || !ticker_B){ //If the returned data is abnormal, jump out of this loop
continue
}
let diff = (ticker_A.Last / ticker_B.Last - ratio) / ratio //Calculate the ratio of deviation
let aim_value = - Trade_Value * diff / Pct //Target holding position
let id_A = null
let id_B = null
//The following is the specific logic of opening a position
if( -aim_value + position_A.amount*CtVal_a*ticker_A.Last > Trade_Value && position_A.amount*CtVal_a*ticker_A.Last > -Max_Value){
id_A = exchange.CreateOrder(pair_a, "sell", ticker_A.Buy, _N(Ice_Value / (ticker_A.Buy * CtVal_a), precision[pair_a].AmountPrecision))
}
if( -aim_value - position_B.amount*CtVal_b*ticker_B.Last > Trade_Value && position_B.amount*CtVal_b*ticker_B.Last < Max_Value){
id_B = exchange.CreateOrder(pair_b, "buy", ticker_B.Sell, _N(Ice_Value / (ticker_B.Sell * CtVal_b), precision[pair_b].AmountPrecision))
}
if( aim_value - position_A.amount*CtVal_a*ticker_A.Last > Trade_Value && position_A.amount*CtVal_a*ticker_A.Last < Max_Value){
id_A = exchange.CreateOrder(pair_a, "buy", ticker_A.Sell, _N(Ice_Value / (ticker_A.Sell * CtVal_a), precision[pair_a].AmountPrecision))
}
if( aim_value + position_B.amount*CtVal_b*ticker_B.Last > Trade_Value && position_B.amount*CtVal_b*ticker_B.Last > -Max_Value){
id_B = exchange.CreateOrder(pair_b, "sell", ticker_B.Buy, _N(Ice_Value / (ticker_B.Buy * CtVal_b), precision[pair_b].AmountPrecision))
}
if(id_A){
exchange.CancelOrder(id_A) //Cancel directly here
}
if(id_B){
exchange.CancelOrder(id_B)
}
let table = {
type: "table",
title: "trading Information",
cols: ["initial equity", "current equity", Pair_A+"position", Pair_B+"position", Pair_A+"holding price", Pair_B+"holding price", Pair_A+"profits", Pair_B+"profits", Pair_A+"price", Pair_B+"price", "current price comparison", "average price comparison", "deviation from average price", "loop delay"],
rows: [[_N(_G('init_eq'),2), _N(total_eq,2), _N(position_A.amount*CtVal_a*ticker_A.Last, 1), _N(position_B.amount*CtVal_b*ticker_B.Last,1),
_N(position_A.price, precision[pair_a].PircePrecision), _N(position_B.price, precision[pair_b].PircePrecision),
_N(position_A.profit, 1), _N(position_B.profit, 1), ticker_A.Last, ticker_B.Last,
_N(ticker_A.Last / ticker_B.Last,6), _N(ratio, 6), _N(diff, 4), (Date.now() - start_loop_time)+"ms"
]]
}
LogStatus("" + JSON.stringify(table) + "
") //This function will display a table containing the above information on the robot page.
Sleep(Interval * 1000) //Sleep time in ms
}
}
冪簡集成是國內(nèi)領(lǐng)先的API集成管理平臺,專注于為開發(fā)者提供全面、高效、易用的API集成解決方案。冪簡API平臺可以通過以下兩種方式找到所需API:通過關(guān)鍵詞搜索API、或者從API Hub分類頁進入尋找。