资源加载中... loading...

Futures

exchange.GetPositions

The exchange.GetPositions() function is used to get the position information; The GetPositions() function is a member function of the exchange object {@var/EXCHANGE exchange}. The GetPositions() function gets the position information of the exchange account bound to the exchange object exchange. The purpose of the member functions (methods) of the exchange object is only related to exchange and will not be repeated here.

The exchange.GetPositions() function returns an array of {@struct/Position Position} structures if the request for data succeeds, and it returns null value if the request for data fails. {@struct/Position Position} arrays, null values

exchange.GetPositions() exchange.GetPositions(symbol)

The parameter symbol is used to set the trading symbol or trading symbol range to be queried. If the symbol parameter is not passed, the default is to request the position data of all symbols in the dimension range of the current trading pair and contract code.

symbol false string

/*backtest
start: 2024-05-21 00:00:00
end: 2024-09-05 00:00:00
period: 5m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

function main() {
    var arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"]

    for (var symbol of arrSymbol) {
        exchange.CreateOrder(symbol, "buy", -1, 1)
        exchange.CreateOrder(symbol, "sell", -1, 1)
    }

    var defaultPositions = exchange.GetPositions()
    var swapPositions = exchange.GetPositions("USDT.swap")
    var futuresPositions = exchange.GetPositions("USDT.futures")
    var btcUsdtSwapPositions = exchange.GetPositions("BTC_USDT.swap")

    var tbls = []
    var arr = [defaultPositions, swapPositions, futuresPositions, btcUsdtSwapPositions]
    var tblDesc = ["defaultPositions", "swapPositions", "futuresPositions", "btcUsdtSwapPositions"]
    for (var index in arr) {
        var positions = arr[index]
        var tbl = {type: "table", title: tblDesc[index], cols: ["Symbol", "MarginLevel", "Amount", "FrozenAmount", "Price", "Profit", "Type", "ContractType", "Margin"], rows: [] }
        for (var pos of positions) {
            tbl.rows.push([pos.Symbol, pos.MarginLevel, pos.Amount, pos.FrozenAmount, pos.Price, pos.Profit, pos.Type, pos.ContractType, pos.Margin])
        }
        tbls.push(tbl)
    }

    LogStatus("`" + JSON.stringify(tbls) + "`")

    // Print out the information once and then return to prevent the order from being executed during the subsequent backtest and affecting data observation
    return
}
'''backtest
start: 2024-05-21 00:00:00
end: 2024-09-05 00:00:00
period: 5m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
'''

import json

def main():
    arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"]

    for symbol in arrSymbol:
        exchange.CreateOrder(symbol, "buy", -1, 1)
        exchange.CreateOrder(symbol, "sell", -1, 1)

    defaultPositions = exchange.GetPositions()
    swapPositions = exchange.GetPositions("USDT.swap")
    futuresPositions = exchange.GetPositions("USDT.futures")
    btcUsdtSwapPositions = exchange.GetPositions("BTC_USDT.swap")

    tbls = []
    arr = [defaultPositions, swapPositions, futuresPositions, btcUsdtSwapPositions]
    tblDesc = ["defaultPositions", "swapPositions", "futuresPositions", "btcUsdtSwapPositions"]
    for index in range(len(arr)):
        positions = arr[index]
        tbl = {"type": "table", "title": tblDesc[index], "cols": ["Symbol", "MarginLevel", "Amount", "FrozenAmount", "Price", "Profit", "Type", "ContractType", "Margin"], "rows": []}
        for pos in positions:
            tbl["rows"].append([pos["Symbol"], pos["MarginLevel"], pos["Amount"], pos["FrozenAmount"], pos["Price"], pos["Profit"], pos["Type"], pos["ContractType"], pos["Margin"]])

        tbls.append(tbl)

    LogStatus("`" + json.dumps(tbls) + "`")

    return
/*backtest
start: 2024-05-21 00:00:00
end: 2024-09-05 00:00:00
period: 5m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

void main() {
    auto arrSymbol = {"BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"};
    
    for (const auto& symbol : arrSymbol) {
        exchange.CreateOrder(symbol, "buy", -1, 1);
        exchange.CreateOrder(symbol, "sell", -1, 1);
    }
    
    auto defaultPositions = exchange.GetPositions();
    auto swapPositions = exchange.GetPositions("USDT.swap");
    auto futuresPositions = exchange.GetPositions("USDT.futures");
    auto btcUsdtSwapPositions = exchange.GetPositions("BTC_USDT.swap");
    
    json tbls = R"([])"_json;
    std::vector<std::vector<Position>> arr = {defaultPositions, swapPositions, futuresPositions, btcUsdtSwapPositions};
    std::string tblDesc[] = {"defaultPositions", "swapPositions", "futuresPositions", "btcUsdtSwapPositions"};
    for (int index = 0; index < arr.size(); index++) {
        auto positions = arr[index];
        json tbl = R"({
            "type": "table", 
            "cols": ["Symbol", "MarginLevel", "Amount", "FrozenAmount", "Price", "Profit", "Type", "ContractType", "Margin"],
            "rows": []
        })"_json;
        tbl["title"] = tblDesc[index];
    
        for (const auto& pos : positions) {
            json arrJson = R"([])"_json;
    
            arrJson.push_back(pos.Symbol);
            arrJson.push_back(pos.MarginLevel);
            arrJson.push_back(pos.Amount);
            arrJson.push_back(pos.FrozenAmount);
            arrJson.push_back(pos.Price);
            arrJson.push_back(pos.Profit);
            arrJson.push_back(pos.Type);
            arrJson.push_back(pos.ContractType);
            arrJson.push_back(pos.Margin);
    
            tbl["rows"].push_back(arrJson);
        }
    
        tbls.push_back(tbl);
    }
    
    LogStatus(_D(), "\n", "`" + tbls.dump() + "`");
    
    return; 
}

Use futures exchange objects to place market orders for multiple different trading pairs and contract codes. Query positions in multiple ways.

Cryptocurrency futures contracts are different from cryptocurrency spot, which has only the logical concept of a position. In the system of FMZ Quant Trading platform, the specific types of cryptocurrency futures contracts are identified by trading pairs, contract code together. Please refer to {@fun/Account/exchange.SetCurrency exchange.SetCurrency}, {@fun/Futures/exchange.SetContractType exchange.SetContractType} functions. In the GetPositions function, the usage scenarios of the symbol parameter are summarized as follows:

Exchange Object Classification symbol Parameters Query Scope Remark
Futures Do not pass symbol parameter Query all trading products within the current trading pair and contract code dimension range If the current trading pair is BTC_USDT and the contract code is swap, all USDT-based perpetual contracts will be queried. This is equivalent to calling GetPositions("USDT.swap")
Futures Specify the trading product, the symbol parameter is: “BTC_USDT.swap” Query the USDT-based perpetual contract of a specified BTC For futures exchange objects, the format of parameter symbol is: a combination of trading pair and contract code defined by the FMZ platform, separated by the characters "..
Futures Specify the range of trading products, the symbol parameter is: “USDT.swap” Query all USDT-based perpetual contracts -
Futures exchanges that support options Do not pass symbol parameter Query all option contracts within the current trading pair dimension range If the current trading pair is BTC_USDT, the contract is set to an option contract, for example, Binance option contract: BTC-240108-40000-C
Futures exchanges that support options Specify specific trading product Query the specified option contract For example, for Binance Futures Exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C
Futures exchanges that support options Specify the range of trading products, the symbol parameter is: “USDT.option” Query all USDT-based options contracts -

In the GetPositions function, the futures exchange object query dimension range is summarized as follows:

symbol Parameters Request Scope Definition Remark
USDT.swap USDT-based perpetual contract range. For

dimensions that are not supported by the exchange API interface, an error will be reported and a null value will be returned when calling. |

| USDT.futures | USDT-based delivery contract range. | - |

| USD.swap | Scope of currency-based perpetual contracts. | - |

| USD.futures | Scope of currency-based delivery contracts. | - |

| USDT.option | USDT-based options contract range. | - |

| USD.option | Currency-based options contract range. |

  • |

| USDT.futures_combo | Range of CFD combinations. | Futures_Deribit Exchange |

| USD.futures_ff | Scope of mixed margin delivery contracts. | Futures_Kraken Exchange |

| USD.swap_pf | Mixed margin perpetual contract range. | Futures_Kraken Exchange |

Compatible with exchange.GetPosition() call, GetPosition is exactly the same as GetPositions.

When the account represented by the exchange object exchange has no positions in the query range or specified trading instruments, the exchange.GetPositions() function returns an empty array, for example: [].

{@struct/Position Position}, {@fun/Account/exchange.SetCurrency exchange.SetCurrency}, {@fun/Futures/exchange.SetContractType exchange.SetContractType}

exchange.SetMarginLevel

The exchange.SetMarginLevel() function is used to set the leverage value of the trading pair or contract specified by the symbol parameter. Compatible with only passing in the parameter marginLevel to set the leverage value of the current trading pair or contract of the {@var/EXCHANGE exchange} exchange object.

exchange.SetMarginLevel(symbol, marginLevel) exchange.SetMarginLevel(marginLevel)

The symbol parameter is used to specify the trading pair or contract for which the leverage value needs to be adjusted. The format of the symbol parameter of the SetMarginLevel() function is consistent with the format of the symbol parameter of the GetTicker() function. symbol false string The marginLevel parameter is used to set the leverage value, which is usually an integer for exchanges and it also supports floating point leverage value settings for some exchanges. marginLevel true number

function main() {
    exchange.SetMarginLevel(10)
    // Set the leverage of BTC’s USDT-margined perpetual contract to 15
    exchange.SetMarginLevel("BTC_USDT.swap", 15)
}
def main():
    exchange.SetMarginLevel(10)
    exchange.SetMarginLevel("BTC_USDT.swap", 15)
void main() {
    exchange.SetMarginLevel(10);
    exchange.SetMarginLevel("BTC_USDT.swap", 15); 
}

The exchange.SetMarginLevel() function supports cryptocurrency futures contract exchange objects only. The backtesting system supports calling the exchange.SetMarginLevel() function to set the leverage value. For cryptocurrency futures contracts, the leverage mechanism is not uniform due to the cryptocurrency futures contract exchanges. In some exchanges, the leverage value of the futures contract is a parameter in the order placement interface, when calling the exchange.SetMarginLevel() function does not generate a network request, but only sets the leverage variable in the underlying FMZ system (used for passing parameters in the order placement interface). The leverage value of some exchange futures contracts is a setting of the exchange, which needs to be set on the exchange website page or using the API interface. In this case calling the exchange.SetMarginLevel() function will generate a network request and may fail to set leverage. There can be many reasons for this, for example: there is a current position or pending order, which makes it impossible to set a new leverage value for this trading pair or contract. Exchanges that do not support the exchange.SetMarginLevel() function:

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
SetMarginLevel Futures_dYdX / Futures_Deribit

{@var/EXCHANGE exchange}

exchange.SetDirection

The exchange.SetDirection() function is used to set the order direction of the {@fun/Trade/exchange.Buy exchange.Buy} function, {@fun/Trade/exchange.Sell exchange.Sell} function when placing orders for futures contracts.

exchange.SetDirection(direction)

The direction parameter is used to set the direction of the futures contract when the order is placed. The optional values are: "buy", "closesell", "sell", "closebuy". direction true string

function main(){
    // For example, set to OKX futures contract of this week
    exchange.SetContractType("this_week")    
    // Set leverage to 5 times
    exchange.SetMarginLevel(5)
    // Set the order type to long
    exchange.SetDirection("buy")
    // Place an order for 2 contracts at 10,000
    exchange.Buy(10000, 2)              
    exchange.SetMarginLevel(5)
    exchange.SetDirection("closebuy")
    exchange.Sell(1000, 2)
}
def main():
    exchange.SetContractType("this_week")
    exchange.SetMarginLevel(5)
    exchange.SetDirection("buy")
    exchange.Buy(10000, 2)
    exchange.SetMarginLevel(5)
    exchange.SetDirection("closebuy")
    exchange.Sell(1000, 2)
void main() {
    exchange.SetContractType("this_week");
    exchange.SetMarginLevel(5);
    exchange.SetDirection("buy");
    exchange.Buy(10000, 2);
    exchange.SetMarginLevel(5);
    exchange.SetDirection("closebuy");
    exchange.Sell(1000, 2);
}

The exchange.SetDirection() function sets the correspondence between the direction of the futures contract transaction and the order placement function:

Order placement functions The direction set by the parameters of the SetDirection function Remarks
exchange.Buy “buy” Buy and open long positions
exchange.Buy “closesell” Buy and close short positions
exchange.Sell “sell” Sell and open short positions
exchange.Sell “closebuy” Sell and close long positions

{@fun/Trade/exchange.Buy exchange.Buy}, {@fun/Trade/exchange.Sell exchange.Sell}

exchange.SetContractType

The exchange.SetContractType() function is used to set the current contract code of the {@var/EXCHANGE exchange} exchange object.

The exchange.SetContractType() function returns a structure that contains the exchange contract code corresponding to the current contract code. For example, for the Binance Futures contract exchange, the current contract code is quarter, and the return value structure of this function is: {"InstrumentID": "BTCUSD_230630", "instrument": "BTCUSD_230630"}. object

exchange.SetContractType(symbol)

The symbol parameter is used to set the contract code, the optional values are: "this_week", "next_week", "quarter", "next_quarter", "swap", etc. Cryptocurrency futures contracts delivery contract codes, if not specified, generally have:

  • this_week: the current week’s contract.
  • next_week: the next week’s contract.
  • quarter: quarterly contract.
  • next_quarter: the next quarterly contract. Permanent contracts codes in cryptocurrency futures contracts, if not specified, generally have:
  • swap: perpetual contract.

symbol true string

function main() {
    // Set to this week contract
    exchange.SetContractType("this_week") 
}
def main():
    exchange.SetContractType("this_week")
void main() {
    exchange.SetContractType("this_week");
}

Set the current contract as the current week’s contract:

function main() {
    // The default trading pair is BTC_USD, set the contract for this week, and the contract is a currency standard contract
    exchange.SetContractType("this_week")
    Log("ticker:", exchange.GetTicker())
    
    // Switching trading pairs, then setting up contracts, switching to USDT as margin contracts, as opposed to currency standard contracts
    exchange.IO("currency", "BTC_USDT")   
    exchange.SetContractType("swap")
    Log("ticker:", exchange.GetTicker())
}
def main():
    exchange.SetContractType("this_week")
    Log("ticker:", exchange.GetTicker())
    exchange.IO("currency", "BTC_USDT")
    exchange.SetContractType("swap")
    Log("ticker:", exchange.GetTicker())
void main() {
    exchange.SetContractType("this_week");
    Log("ticker:", exchange.GetTicker());
    exchange.IO("currency", "BTC_USDT");
    exchange.SetContractType("swap");
    Log("ticker:", exchange.GetTicker());
}

When setting up a contract with USDT as margin, you need to switch the trading pair in the code (you can also set the trading pair directly when adding the exchange object):

function main(){
    // Set the contract for this week
    var ret = exchange.SetContractType("this_week")     
    // Return information about the current week's contracts
    Log(ret)
}
def main():
    ret = exchange.SetContractType("this_week")
    Log(ret)
void main() {
    auto ret = exchange.SetContractType("this_week");
    Log(ret);
}

Print the return value of the exchange.SetContractType() function:

In the cryptocurrency futures contract strategy, take an example of switching to the BTC_USDT trading pair: When switching trading pairs using the exchange.SetCurrency("BTC_USDT") or exchange.IO("currency", "BTC_USDT") functions, after switching, you need to use the exchange.SetContractType() function to reset the contract in order to determine the current contract to be operated under the new trading pair. The system determines whether it is a currency standard contract or a USDT standard contract based on the trading pair. For example, if a trading pair is set to BTC_USDT, use the exchange.SetContractType("swap") function to set the contract code to swap. At this point, it is set to BTC for the USDT standard perpetual contract. If the trading pair is BTC_USD, use the exchange.SetContractType("swap") function to set the contract code to swap. At this point, it is set to BTC's currency standard perpetual contract. Details of the supported cryptocurrency futures contract exchanges, with contract names for each exchange as follows:

  • Futures_OKCoin (OKX) Set to perpetual contracts: exchange.SetContractType("swap") Set to the contract of this week: exchange.SetContractType("this_week") Set to next week’s contract: exchange.SetContractType("next_week") Set to monthly contract: exchange.SetContractType("month") Set to next month contract: exchange.SetContractType("next_month") Set to quarterly contracts: exchange.SetContractType("quarter") Set to next quarter contract: exchange.SetContractType("next_quarter")

    OKX has pre-market trading contracts: the contract delivery date is a fixed time. The contract code defined by the exchange is, for example: HMSTR-USDT-250207. Set the trading pair to HMSTR_USDT on the FMZ platform, and then use exchange.SetContractType("HMSTR-USDT-250207") to set the contract. For functions that support the symbol parameter, such as: exchange.GetTicker(), exchange.CreateOrder(), etc. You can specify the symbol parameter as: HMSTR_USDT.HMSTR-USDT-250207 to obtain the market data of this contract or place an order.

  • Futures_HuobiDM (Huobi futures) Set to the contract of this week: exchange.SetContractType("this_week"). Set to next week’s contract: exchange.SetContractType("next_week"). Set to quarterly contracts: exchange.SetContractType("quarter"). Set to next quarter contract: exchange.SetContractType("next_quarter"). Set to perpetual contracts: exchange.SetContractType("swap"). It supports contracts with USDT as margin, take BTC contract as an example: use exchange.IO("currency", "BTC_USDT") to switch to a contract that uses USDT as margin. Or set the current trading pair to BTC_USDT directly when configuring live trading parameters and adding exchange objects. After switching trading pairs, you need to call exchange.SetContractType() function again to set the contract.

  • Futures_BitMEX (BitMEX) Set to perpetual contracts: exchange.SetContractType("swap"). Futures_BitMEX exchange delivery contracts are monthly contracts with the following contract codes (from January to December):

    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    

    Setting up delivery contracts: exchange.SetContractType("December"). For example, when the trading pair is set to XBT_USDT, the exchange.SetContractType("December") function is called to set the contract for December delivery in the USDT based of BTC (corresponding to the actual contract code of XBTUSDTZ23).

    Futures_BitMEX Contract Information Summary

    Contract code defined by Futures_BitMEX The corresponding trading pair in FMZ The corresponding contract code in FMZ Remark
    DOGEUSD DOGE_USD swap USD denominated, XBT settled. XBT is BTC.
    DOGEUSDT DOGE_USDT swap USDT denominated, USDT settled.
    XBTETH XBT_ETH swap ETH denominated, XBT settled.
    XBTEUR XBT_EUR swap EUR-denominated, XBT settled.
    USDTUSDC USDT_USDC swap USDC denominated, XBT settled.
    ETHUSD_ETH ETH_USD_ETH swap USD denominated, ETH settled.
    XBTH24 XBT_USD March Expiration date: March 24, month code is: H; USD denominated, XBT settled.
    ETHUSDZ23 ETH_USD December Expiration date: Dec 23, month code is: Z; USD denominated, XBT settled.
    XBTUSDTZ23 XBT_USDT December Expiration date: December 23, month code is: Z ; USDT denominated, USDT settled.
    ADAZ23 ADA_XBT December Expiration date: December 23, month code is: Z ; XBT billing, XBT settled.
    P_XBTETFX23 USDT_XXX P_XBTETFX23 Expiration: 11/23/23; denominated as a percentage and settled in USDT.
  • Futures_GateIO Set to the contract of this week: exchange.SetContractType("this_week"). Set to next week’s contract: exchange.SetContractType("next_week"). Set to quarterly contracts: exchange.SetContractType("quarter"). Set to next quarter contract: exchange.SetContractType("next_quarter"). Set to perpetual contracts: exchange.SetContractType("swap"). It supports contracts with USDT as margin, take BTC contract as an example: use exchange.IO("currency", "BTC_USDT") to switch to a contract that uses USDT as margin. Or set the current trading pair to BTC_USDT directly when configuring live trading parameters and adding exchange objects. After switching trading pairs, you need to call exchange.SetContractType() function again to set the contract.

  • Futures_Deribit Set to perpetual contracts: exchange.SetContractType("swap"). It supports Deribit’s USDC contract. The delivery contracts are: "this_week", "next_week", "month", "quarter", "next_quarter", "third_quarter", "fourth_quarter". CFD (future_combo): "this_week,swap", "next_week,swap", "next_quarter,this_week", "third_quarter,this_week", "month,next_week", there are many combinations. For option contracts you need to pass in the specific option contract code defined by the exchange, see the Deribit website for details.

  • Futures_KuCoin For example, if the trading pair is set to BTC_USD and the contract code is set, it is a currency-based contract: Set to perpetual contracts: exchange.SetContractType("swap"). Set to quarterly contracts: exchange.SetContractType("quarter"). Set to next quarter contract: exchange.SetContractType("next_quarter").

    USDT as margin contract: For example, if the trading pair is set to BTC_USDT, and then set the contract code, it is a contract with USDT as margin. Set to perpetual contracts: exchange.SetContractType("swap").

  • Futures_Binance Binance Futures Exchange defaults to the perpetual contract of the current trading pair, contract code: swap. Set to perpetual contracts: exchange.SetContractType("swap"), the perpetual contracts of Binance have contracts that use USDT as margin. For example, USDT standard perpetual contract of BTC can be used as a margin contract, and the trading pair is set to BTC_USDT. Binance also supports perpetual contracts that use coins as margin, for example, BTC's Binance standard perpetual contract, with the trading pair set to BTC_USD. Set to quarterly contracts: exchange.SetContractType("quarter"), the delivery contract has a currency standard contract (i.e., using currencies as margin), for example, BTC's quarterly contract, the trading pair is set to: BTC_USD and then set the contract exchange.SetContractType("quarter"), it is set to BTC quarterly contract with a currency standard contract. Set to next quarter contract: exchange.SetContractType("next_quarter"), for example, BTC of the currency standard quarterly contract, the trading pair set to: BTC_USD, and then set the contract exchange.SetContractType("next_quarter"). Binance supports partial USDT as margin delivery contract, take BTC as an example, set trading pair to BTC_USDT, then set the contract code.

    Support for Binance Options contracts: The format of the option contract code is based on the option contract code defined by the exchange: BTC-241227-15000-C, XRP-240112-0.5-C, BTC-241227-15000-P. Take the Binance option contract code BTC-241227-15000-P as an example: BTC is the option currency code, 241227 is the exercise date, 15000 is the exercise price, P represents a put option, and C represents a call option. For details on the option type, whether it is European option or American option, please refer to the relevant information of the exchange’s option contract. The exchange may restrict option sellers and require them to apply for qualifications separately. Binance options require seller qualifications.

  • Futures_Bibox Contract code for Bibox perpetual contracts: swap. Set to perpetual contracts: exchange.SetContractType("swap").

  • Futures_Bybit The default is the perpetual contract for the current trading pair, contract code: swap. This week contract code: this_week. Next week contract code: next_week. Third week contract code: third_week. Monthly contract code: month. Next month contract code: next_month. Quarterly contract code: quarter. Next quarter contract code: next_quarter. Third quarter contract code: third_quarter.

  • Futures_Kraken The default is the perpetual contract of the current trading pair, contract code: swap. swap: perpetual contract. month: current month contract. quarter: quarterly contract. next_quarter: next quarter contract. swap_pf: Mixed margin perpetual contract. quarter_ff: Mixed margin quarterly contract. month_ff: Mixed margin current month contract. next_quarter_ff: Mixed margin next quarter contract.

  • Futures_Bitfinex Default is the perpetual contract for the current trading pair, contract code: swap.

  • Futures_Bitget Default is the perpetual contract for the current trading pair, contract code: swap. The trading pair is set to BTC_USD for currency standard contracts, and the trading pair is set to BTC_USDT for contracts settled by USDT. Demo contracts can be set up with trading pairs as SBTC_USD, BTC_SUSDT.

  • Futures_dYdX Contract code for dYdX perpetual contracts: swap. Set to perpetual contracts: exchange.SetContractType("swap"), dYdX has USDT standard contracts only.

  • Futures_MEXC Contract code for MEXC perpetual contracts: swap. Set to perpetual contracts: exchange.SetContractType("swap"). Set trading pair to BTC_USD, which is currency standard contract, and set trading pair to BTC_USDT, which is USDT-settled contract.

  • Futures_Crypto Tokens in an account on the crypto.com exchange can be converted into USD-denominated credits to be used as margin for contract trading. Set to perpetual contract: exchange.SetContractType("swap"). Example of calling the exchange.SetContractType("swap") function to set a perpetual contract for BTC when the trading pair is set to BTC_USD. The crypto.com exchange delivery contracts are monthly contracts with the following contract codes (from January to December):

    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    

    Set the delivery contract: exchange.SetContractType("October"). For example, when the trading pair is set to BTC_USD, call the function exchange.SetContractType("October") to set the October delivery contract for BTC. The corresponding contract code at the current moment is: BTCUSD-231027.

  • Futures_WOO Futures_WOO exchange supports USDT based contracts with a perpetual contract code of swap. For example, when the trading pair is set to BTC_USDT, the function exchange.SetContractType("swap") is called to set the current contract to be a USDT based perpetual contract for BTC.

{@fun/Futures/exchange.GetContractType exchange.GetContractType}, {@fun/Account/exchange.SetCurrency exchange.SetCurrency}

exchange.GetContractType

The exchange.GetContractType() function is used to get the contract code for the current setting of the {@var/EXCHANGE exchange} exchange object.

The exchange.GetContractType() function returns the contract code defined by the FMZ platform, for example: this_week, swap, etc. string

exchange.GetContractType()

function main () {
    Log(exchange.SetContractType("this_week")) 
    Log(exchange.GetContractType())
}
def main():
    Log(exchange.SetContractType("this_week"))
    Log(exchange.GetContractType())
void main() {
    Log(exchange.SetContractType("this_week"));
    Log(exchange.GetContractType());
}

{@fun/Futures/exchange.SetContractType exchange.SetContractType}

exchange.GetFundings

The exchange.GetFundings() function is used to obtain the funding rate data for the current period.

The exchange.GetFundings() function returns an array of {@struct/Funding Funding} structures when the data request is successful, and returns a null value when the data request fails. {@struct/Funding Funding} array, null value

exchange.GetFundings() exchange.GetFundings(symbol)

The parameter symbol is used to set the transaction symbol or transaction symbol range to be queried. When the symbol parameter is not passed, the current funding rate data of all instruments will be requested by default in the dimension range of the current trading pair and contract code.

symbol false string

/*backtest
start: 2024-10-01 00:00:00
end: 2024-10-23 00:05:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDC"}]
*/

function main() {
    // LPT_USDT.swap 4-hour period
    var symbols = ["SOL_USDT.swap", "ETH_USDT.swap", "LTC_USDT.swap", "SOL_USDC.swap", "ETH_USDC.swap", "BTC_USD.swap", "BTC_USDT.quarter", "LPT_USDT.swap"]
    for (var symbol of symbols) {
        exchange.GetTicker(symbol)
    }
    
    var arr = []
    var arrParams = ["no param", "LTC_USDT.swap", "USDT.swap", "USD.swap", "USDC.swap", "USDT.futures", "BTC_USDT.quarter"]
    for (p of arrParams) {
        if (p == "no param") {
            arr.push(exchange.GetFundings())
        } else {
            arr.push(exchange.GetFundings(p))
        }
    }
    
    var tbls = []
    var index = 0
    for (var fundings of arr) {
        var tbl = {
            "type": "table",
            "title": arrParams[index],
            "cols": ["Symbol", "Interval", "Time", "Rate"],
            "rows": [],
        }
    
        for (var f of fundings) {
            tbl["rows"].push([f.Symbol, f.Interval / 3600000, _D(f.Time), f.Rate * 100 + " %"])
        }
        tbls.push(tbl)
        index++
    }
    
    LogStatus(_D(), "\n Requested market types:", symbols, "\n`" + JSON.stringify(tbls) + "`")
}
'''backtest
start: 2024-10-01 00:00:00
end: 2024-10-23 00:05:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDC"}]
'''
    
import json
    
def main():
    # LPT_USDT.swap 4-hour period
    symbols = ["SOL_USDT.swap", "ETH_USDT.swap", "LTC_USDT.swap", "SOL_USDC.swap", "ETH_USDC.swap", "BTC_USD.swap", "BTC_USDT.quarter", "LPT_USDT.swap"]
    for symbol in symbols:
        exchange.GetTicker(symbol)
    
    arr = []
    arrParams = ["no param", "LTC_USDT.swap", "USDT.swap", "USD.swap", "USDC.swap", "USDT.futures", "BTC_USDT.quarter"]
    for p in arrParams:
        if p == "no param":
            arr.append(exchange.GetFundings())
        else:
            arr.append(exchange.GetFundings(p))
    
    tbls = []
    index = 0
    for fundings in arr:
        tbl = {
            "type": "table",
            "title": arrParams[index],
            "cols": ["Symbol", "Interval", "Time", "Rate"],
            "rows": [],
        }
    
        for f in fundings:
            tbl["rows"].append([f["Symbol"], f["Interval"] / 3600000, _D(f["Time"]), str(f["Rate"] * 100) + " %"])
    
        tbls.append(tbl)
        index += 1
    
    LogStatus(_D(), "\n Requested market types:", symbols, "\n`" + json.dumps(tbls) + "`")
/*backtest
start: 2024-10-01 00:00:00
end: 2024-10-23 00:05:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDC"}]
*/
    
void main() {
    // LPT_USDT.swap 4-hour period
    json arrSymbol = R"([])"_json;
    std::string symbols[] = {"SOL_USDT.swap", "ETH_USDT.swap", "LTC_USDT.swap", "SOL_USDC.swap", "ETH_USDC.swap", "BTC_USD.swap", "BTC_USDT.quarter", "LPT_USDT.swap"};
    for (const std::string& symbol : symbols) {
        exchange.GetTicker(symbol);
        arrSymbol.push_back(symbol);
    }
    
    std::vector<std::vector<Funding>> arr = {};
    std::string arrParams[] = {"no param", "LTC_USDT.swap", "USDT.swap", "USD.swap", "USDC.swap", "USDT.futures", "BTC_USDT.quarter"};
    for (const std::string& p : arrParams) {
        if (p == "no param") {
            arr.push_back(exchange.GetFundings());
        } else {
            arr.push_back(exchange.GetFundings(p));
        }
    }
    
    json tbls = R"([])"_json;
    int index = 0;
    for (int i = 0; i < arr.size(); i++) {
        auto fundings = arr[i];
    
        json tbl = R"({
            "type": "table", 
            "cols": ["Symbol", "Interval", "Time", "Rate"],
            "rows": []
        })"_json;
        tbl["title"] = arrParams[index];
    
        for (int j = 0; j < fundings.size(); j++) {
            auto f = fundings[j];
            // json arrJson = {f.Symbol, f.Interval / 3600000, _D(f.Time), string(f.Rate * 100) + " %"};
            json arrJson = {f.Symbol, f.Interval / 3600000, _D(f.Time), f.Rate};
            tbl["rows"].push_back(arrJson);
        }
        tbls.push_back(tbl);
        index++;
    }
    
    LogStatus(_D(), "\n Requested market types:", arrSymbol.dump(), "\n`" + tbls.dump() + "`");
}

Use the futures exchange object to call the exchange.GetFundings() function in the backtesting system. Before calling any market function, GetFundings only returns the Funding data of the current default trading pair. After calling the market function, it returns the Funding data of all requested varieties. You can refer to the following test example:

For futures exchanges that do not support batch query of funding rate data, if the symbol parameter is specified as the query range, for example: USDT.swap or the symbol parameter is not passed, the interface will report an error. When calling the GetFundings() function using this type of futures exchange object, you must specify the symbol parameter as a specific perpetual contract type in order to query the current funding rate data of the type. The exchange.GetFundings() function supports real trading and backtesting systems. Exchanges that do not support batch acquisition of funding rate data: Futures_Bitget, Futures_OKX, Futures_MEXC, Futures_Deribit, Futures_Crypto. Need to pass in the symbol parameter with the specific symbol code, for example: ETH_USDT.swap.

Exchanges that do not support the exchange.GetFundings() function:

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
GetFundings Futures_DigiFinex

{@struct/Funding Funding}

Account NetSettings