Futures
exchange.GetPositions
exchange.GetPositions() function is used to get position information; the GetPositions() function is a member function of the exchange object exchange.
GetPositions() function is used to get 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, which will not be repeated in the rest of this document.
exchange.GetPositions()
exchange.GetPositions(symbol)Examples
Using the futures exchange object, place market orders on multiple symbols with different trading pairs and contract codes, and query position information through various methods.
javascript
/*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) + "`")
// After printing the information once, return to prevent subsequent order fills during backtesting from affecting data observation
return
}
python
'''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
rust
/*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"}]
*/
fn main() {
let 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);
}
let defaultPositions = exchange.GetPositions(None).unwrap();
let swapPositions = exchange.GetPositions("USDT.swap").unwrap();
let futuresPositions = exchange.GetPositions("USDT.futures").unwrap();
let btcUsdtSwapPositions = exchange.GetPositions("BTC_USDT.swap").unwrap();
// The Rust SDK has no JSON serialization; use format! to concatenate the table's JSON text
let mut tbls: Vec<String> = Vec::new();
let arr = [defaultPositions, swapPositions, futuresPositions, btcUsdtSwapPositions];
let tblDesc = ["defaultPositions", "swapPositions", "futuresPositions", "btcUsdtSwapPositions"];
for (index, positions) in arr.iter().enumerate() {
let mut rows: Vec<String> = Vec::new();
for pos in positions {
rows.push(format!(r#"["{}", {}, {}, {}, {}, {}, {}, "{}", {}]"#, pos.Symbol, pos.MarginLevel, pos.Amount, pos.FrozenAmount, pos.Price, pos.Profit, pos.Type, pos.ContractType, pos.Margin));
}
let tbl = format!(r#"{{"type": "table", "title": "{}", "cols": ["Symbol", "MarginLevel", "Amount", "FrozenAmount", "Price", "Profit", "Type", "ContractType", "Margin"], "rows": [{}]}}"#, tblDesc[index], rows.join(","));
tbls.push(tbl);
}
LogStatus!(format!("`[{}]`", tbls.join(",")));
// After printing the information once, return to prevent subsequent order fills during backtesting from affecting data observation
return;
}
c++
/*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;
}Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The When the |
See Also
Remarks
Cryptocurrency futures contracts are different from cryptocurrency spot; spot only has a logical concept of position. In the FMZ Quant Trading Platform system, the specific instrument of a cryptocurrency futures contract is jointly identified by the **trading pair** and the **contract code**. Refer to the exchange.SetCurrency and exchange.SetContractType functions.
In the GetPositions function, the usage scenarios of the symbol parameter are summarized as follows:
| Exchange Object Category | symbol Parameter | Query Scope | Remarks |
|---|---|---|---|
| Futures | symbol parameter not passed | Query all trading instruments within the dimension range of the current trading pair and contract code | If the current trading pair is BTC_USDT and the contract code is swap, it queries all USDT-margined perpetual contracts. Equivalent to calling GetPositions("USDT.swap") |
| Futures | Specify a trading instrument, symbol parameter is: "BTC_USDT.swap" | Query the specified BTC USDT-margined perpetual contract | For a futures exchange object, the format of the symbol parameter is: the combination of the trading pair and contract code defined by the FMZ platform, separated by the character ".". |
| Futures | Specify a range of trading instruments, symbol parameter is: "USDT.swap" | Query all USDT-margined perpetual contracts | - |
| Futures exchange supporting options | symbol parameter not passed | Query all option contracts within the dimension range of the current trading pair | If the current trading pair is BTC_USDT and the contract is set to an option contract, for example, a Binance option contract: BTC-240108-40000-C |
| Futures exchange supporting options | Specify a specific trading instrument | Query the specified option contract | For example, for the Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C |
| Futures exchange supporting options | Specify a range of trading instruments, symbol parameter is: "USDT.option" | Query all USDT-margined option contracts | - |
In the GetPositions function, the query dimension ranges of the futures exchange object are summarized as follows:
| symbol Parameter | Request Scope Definition | Remarks |
|---|---|---|
| USDT.swap | Scope of USDT-margined perpetual contracts. | For dimensions not supported by the exchange API interface, calling it will report an error and return a null value. |
| USDT.futures | Scope of USDT-margined delivery contracts. | - |
| USD.swap | Scope of coin-margined perpetual contracts. | - |
| USD.futures | Scope of coin-margined delivery contracts. | - |
| USDT.option | Scope of USDT-margined option contracts. | - |
| USD.option | Scope of coin-margined option contracts. | - |
| USDT.futures_combo | Scope of spread combo contracts. | Futures_Deribit exchange |
| USD.futures_ff | Scope of mixed-margin delivery contracts. | Futures_Kraken exchange |
| USD.swap_pf | Scope of mixed-margin perpetual contracts. | Futures_Kraken exchange |
Compatible with the exchange.GetPosition() call; GetPosition and GetPositions are used in exactly the same way.
When the account represented by the exchange object exchange has no positions within the query scope or on the specified trading instrument, the exchange.GetPositions() function returns an empty array, for example: [].
exchange.SetMarginLevel
The exchange.SetMarginLevel() function is used to set the leverage value for the trading pair or contract specified by the symbol parameter. It is also compatible with a calling method that passes only the marginLevel parameter, which is used to set the leverage value of the current trading pair or contract of the exchange exchange object.
exchange.SetMarginLevel(symbol, marginLevel)
exchange.SetMarginLevel(marginLevel)Examples
javascript
function main() {
exchange.SetMarginLevel(10)
// Set the leverage of BTC's USDT-margined perpetual contract to 15
exchange.SetMarginLevel("BTC_USDT.swap", 15)
}
python
def main():
exchange.SetMarginLevel(10)
exchange.SetMarginLevel("BTC_USDT.swap", 15)
rust
fn main() {
exchange.SetMarginLevel(10);
// In the Rust SDK, the SetMarginLevel function does not support the symbol parameter; it only sets the leverage value of the current trading pair or contract
// To set the leverage of the BTC_USDT.swap instrument to 15, you need to switch to that trading pair or contract first and then call exchange.SetMarginLevel(15)
}
c++
void main() {
exchange.SetMarginLevel(10);
exchange.SetMarginLevel("BTC_USDT.swap", 15);
}Arguments
| Name | Type | Required | Description |
symbol | string | No | The |
marginLevel | number | Yes | The |
See Also
Remarks
The exchange.SetMarginLevel() function only supports cryptocurrency futures contract exchange objects. The backtesting system supports calling the exchange.SetMarginLevel() function to set the leverage value.
For cryptocurrency futures contracts, the leverage mechanisms of different cryptocurrency futures contract exchanges are not unified.
On some exchanges, the leverage value of a futures contract is a parameter in the order-placing interface. In this case, calling the exchange.SetMarginLevel() function does not generate a network request; it merely sets the underlying leverage variable in the FMZ system (used for passing parameters to the order-placing interface).
On other exchanges, the leverage value of a futures contract is an independent setting of the exchange, which needs to be set through the exchange's website page or API interface. In this case, calling the exchange.SetMarginLevel() function will generate a network request and may fail to set the value. There can be various reasons for failure, for example: there are currently open positions or pending orders, which prevents a new leverage value from being set for that 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 / Futures_edgeX |
exchange.SetDirection
The exchange.SetDirection() function is used to set the order direction when calling the exchange.Buy function or exchange.Sell function to place futures contract orders.
exchange.SetDirection(direction)Examples
javascript
function main(){
// For example, set to OKX futures this-week contract
exchange.SetContractType("this_week")
// Set leverage to 5x
exchange.SetMarginLevel(5)
// Set the order direction to long
exchange.SetDirection("buy")
// Place an order at a price of 10000 with a quantity of 2 contracts
exchange.Buy(10000, 2)
exchange.SetMarginLevel(5)
exchange.SetDirection("closebuy")
exchange.Sell(1000, 2)
}
python
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)
rust
fn main() {
// Note: In the Rust SDK, using the SetDirection, Buy, and Sell functions is not recommended. It is advisable to prefer the CreateOrder function,
// CreateOrder can directly specify the side parameter ("buy", "sell", "closebuy", "closesell"), without needing to call SetDirection first
// For example, set to OKX futures this-week contract
exchange.SetContractType("this_week").unwrap();
// Set leverage to 5x
exchange.SetMarginLevel(5);
// Set the order direction to long
exchange.SetDirection("buy").unwrap();
// Place an order at a price of 10000 with a quantity of 2 contracts
exchange.Buy(10000, 2).unwrap();
exchange.SetMarginLevel(5);
exchange.SetDirection("closebuy").unwrap();
exchange.Sell(1000, 2).unwrap();
}
c++
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);
}Arguments
| Name | Type | Required | Description |
direction | string | Yes | The |
See Also
Remarks
The exchange.SetDirection() function is used to set the correspondence between the futures contract trading direction and the order-placing functions:
| Order Function | Direction Set by SetDirection | Remarks |
|---|---|---|
| exchange.Buy | "buy" | Buy to open long position |
| exchange.Buy | "closesell" | Buy to close short position |
| exchange.Sell | "sell" | Sell to open short position |
| exchange.Sell | "closebuy" | Sell to close long position |
exchange.SetContractType
The exchange.SetContractType() function is used to set the current contract code of the exchange exchange object.
exchange.SetContractType(symbol)Examples
-
Set the current contract to the current-week contract:
javascriptfunction main() { // Set to the current-week contract exchange.SetContractType("this_week") }pythondef main(): exchange.SetContractType("this_week")rustfn main() { // Set to the current-week contract exchange.SetContractType("this_week").unwrap(); }c++void main() { exchange.SetContractType("this_week"); } -
When setting a contract that uses
USDTas margin, you need to switch the trading pair in the code (you can also set the trading pair directly when adding the exchange object):javascriptfunction main() { // The default trading pair is BTC_USD; set the contract to current-week, which is a coin-margined contract exchange.SetContractType("this_week") Log("ticker:", exchange.GetTicker()) // Switch the trading pair, then set the contract, switching to a USDT-margined contract, as distinct from a coin-margined contract exchange.IO("currency", "BTC_USDT") exchange.SetContractType("swap") Log("ticker:", exchange.GetTicker()) }pythondef main(): exchange.SetContractType("this_week") Log("ticker:", exchange.GetTicker()) exchange.IO("currency", "BTC_USDT") exchange.SetContractType("swap") Log("ticker:", exchange.GetTicker())rustfn main() { // The default trading pair is BTC_USD; set the contract to current-week, which is a coin-margined contract exchange.SetContractType("this_week").unwrap(); Log!("ticker:", exchange.GetTicker(None)); // Switch the trading pair, then set the contract, switching to a USDT-margined contract, as distinct from a coin-margined contract exchange.IO(("currency", "BTC_USDT")).unwrap(); exchange.SetContractType("swap").unwrap(); Log!("ticker:", exchange.GetTicker(None)); }c++void main() { exchange.SetContractType("this_week"); Log("ticker:", exchange.GetTicker()); exchange.IO("currency", "BTC_USDT"); exchange.SetContractType("swap"); Log("ticker:", exchange.GetTicker()); } -
Print the return value of the
exchange.SetContractType()function:javascriptfunction main(){ // Set the contract to current-week var ret = exchange.SetContractType("this_week") // Returns the information of the current-week contract Log(ret) }pythondef main(): ret = exchange.SetContractType("this_week") Log(ret)rustfn main() { // Set the contract to current-week let ret = exchange.SetContractType("this_week").unwrap(); // Returns the information of the current-week contract Log!(ret); }c++void main() { auto ret = exchange.SetContractType("this_week"); Log(ret); }
Returns
| Type | Description |
object | The |
Arguments
| Name | Type | Required | Description |
symbol | string | Yes | The Unless otherwise specified, the codes for delivery contracts in cryptocurrency futures contracts generally include:
Unless otherwise specified, the codes for perpetual contracts in cryptocurrency futures contracts generally include:
|
See Also
Remarks
In cryptocurrency futures contract strategies, take switching to the BTC_USDT trading pair as an example:
After switching the trading pair using the exchange.SetCurrency("BTC_USDT") or exchange.IO("currency", "BTC_USDT") function, you need to call the exchange.SetContractType() function again to reset the contract, so as to determine the specific contract to operate on under the new trading pair. The system determines whether the contract is a coin-margined contract or a USDT-margined contract based on the trading pair.
For example: when the trading pair is set to BTC_USDT, using the exchange.SetContractType("swap") function to set the contract code to swap sets it to the BTC USDT-margined perpetual contract. If the trading pair is BTC_USD, using the exchange.SetContractType("swap") function to set the contract code to swap sets it to the BTC coin-margined perpetual contract.
Detailed introduction to the cryptocurrency futures contract exchanges supported by the platform. The contract naming conventions for each exchange are as follows:
-
Futures_OKCoin(OKX)
Set to perpetual contract:exchange.SetContractType("swap")
Set to current-week contract:exchange.SetContractType("this_week")
Set to next-week contract:exchange.SetContractType("next_week")
Set to monthly contract:exchange.SetContractType("month")
Set to next-month contract:exchange.SetContractType("next_month")
Set to quarterly contract:exchange.SetContractType("quarter")
Set to next-quarter contract:exchange.SetContractType("next_quarter")OKX offers pre-market trading contracts, whose delivery dates are fixed. Taking the exchange-defined contract code
HMSTR-USDT-250207as an example, first set the trading pair toHMSTR_USDTon the FMZ platform, then useexchange.SetContractType("HMSTR-USDT-250207")to set this contract.
For functions that support thesymbolparameter (such asexchange.GetTicker(),exchange.CreateOrder(), etc.), you can specify thesymbolparameter asHMSTR_USDT.HMSTR-USDT-250207to obtain market data for this contract or to place orders and perform other operations. -
Futures_HuobiDM (Huobi Futures)
Set to current-week contract:exchange.SetContractType("this_week").
Set to next-week contract:exchange.SetContractType("next_week").
Set to quarterly contract:exchange.SetContractType("quarter").
Set to next-quarter contract:exchange.SetContractType("next_quarter").
Set to perpetual contract:exchange.SetContractType("swap").
Supports contracts usingUSDTas margin. Taking theBTCcontract as an example: callexchange.IO("currency", "BTC_USDT")to switch to a contract usingUSDTas margin,
or directly set the current trading pair toBTC_USDTwhen configuring live trading parameters and adding the exchange object. After switching the trading pair, you must call theexchange.SetContractType()function again to set the contract. -
Futures_BitMEX (BitMEX)
Set to perpetual contract:exchange.SetContractType("swap").
The delivery contracts on the Futures_BitMEX exchange are monthly contracts, with the following contract codes (January through December):code"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"Set a delivery contract:
exchange.SetContractType("December"). For example, when the trading pair is set toXBT_USDT, calling theexchange.SetContractType("December")function sets the USDT-margined December delivery contract for BTC (the corresponding actual contract code isXBTUSDTZ23).Summary of Futures_BitMEX contract information
Contract code defined by Futures_BitMEX Corresponding trading pair on FMZ Corresponding contract code on FMZ Remarks 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 (EUR), XBT-settled. USDTUSDC USDT_USDC swap USDC-denominated, XBT-settled. ETHUSD_ETH ETH_USD_ETH swap USD-denominated, ETH-settled. XBTH24 XBT_USD March Expiry: March 2024, month code H; USD-denominated, XBT-settled. ETHUSDZ23 ETH_USD December Expiry: December 2023, month code Z; USD-denominated, XBT-settled. XBTUSDTZ23 XBT_USDT December Expiry: December 2023, month code Z; USDT-denominated, USDT-settled. ADAZ23 ADA_XBT December Expiry: December 2023, month code Z; XBT-denominated, XBT-settled. P_XBTETFX23 USDT_XXX P_XBTETFX23 Expiry: November 2023; denominated in percentage, USDT-settled. -
Futures_GateIO
Set to current-week contract:exchange.SetContractType("this_week").
Set to next-week contract:exchange.SetContractType("next_week").
Set to quarterly contract:exchange.SetContractType("quarter").
Set to next-quarter contract:exchange.SetContractType("next_quarter").
Set to perpetual contract:exchange.SetContractType("swap").
Supports contracts usingUSDTas margin. Taking theBTCcontract as an example, callexchange.IO("currency", "BTC_USDT")to switch to a contract usingUSDTas margin,
or directly set the current trading pair toBTC_USDTwhen configuring live trading parameters and adding the exchange object. After switching the trading pair, you must call theexchange.SetContractType()function again to set the contract. -
Futures_Deribit
Set to perpetual contract:exchange.SetContractType("swap").
Supports Deribit'sUSDCcontracts.
Delivery contracts include:"this_week","next_week","month","quarter","next_quarter","third_quarter","fourth_quarter".
Spread contracts (future_combo):"this_week,swap","next_week,swap","next_quarter,this_week","third_quarter,this_week","month,next_week"and various other combinations.
For options contracts, you need to pass in the specific options contract code defined by the exchange; for details, please refer to the Deribit official website. -
Futures_KuCoin
Coin-margined contracts: for example, set the trading pair toBTC_USD, then set the contract code, which yields a coin-margined contract.
Set to perpetual contract:exchange.SetContractType("swap").
Set to current-quarter contract:exchange.SetContractType("quarter").
Set to next-quarter contract:exchange.SetContractType("next_quarter").Contracts using USDT as margin:
For example, set the trading pair toBTC_USDT, then set the contract code, which yields a contract using USDT as margin.
Set to perpetual contract:exchange.SetContractType("swap"). -
Futures_Binance
The Binance Futures exchange defaults to the perpetual contract of the current trading pair, with contract code:swap.
Set to perpetual contract:exchange.SetContractType("swap"). Binance's perpetual contracts support usingUSDTas margin; for example, for theUSDT-margined perpetual contract ofBTC, set the trading pair toBTC_USDT; Binance also supports coin-margined perpetual contracts, for example the coin-margined perpetual contract ofBTC, for which you set the trading pair toBTC_USD.
Set to quarterly contract:exchange.SetContractType("quarter"). Delivery contracts include coin-margined contracts (i.e., using the coin as margin); for example, to set the quarterly contract ofBTC, set the trading pair toBTC_USD, then callexchange.SetContractType("quarter")to set the coin-margined quarterly contract ofBTC.
Set to next-quarter contract:exchange.SetContractType("next_quarter"). For example, to set the coin-margined next-quarter contract ofBTC, set the trading pair toBTC_USD, then callexchange.SetContractType("next_quarter").
Binance supports someUSDT-margined delivery contracts. TakingBTCas an example, set the trading pair toBTC_USDT, then set the contract code.Supports Binance options contracts:
The options contract code format follows the exchange definition, for exampleBTC-241227-15000-C,XRP-240112-0.5-C,BTC-241227-15000-P. Taking the Binance options contract codeBTC-241227-15000-Pas an example: BTC is the option's underlying coin code, 241227 is the exercise date, 15000 is the strike price, P indicates a put option, and C indicates a call option.
For the specific type of option (European or American), please refer to the relevant documentation on the exchange's options contracts.
The exchange may impose restrictions on option sellers, requiring a separate application for eligibility. Binance options, for instance, require applying for seller eligibility. -
Futures_Bibox
Bibox perpetual contract code:swap.
Set to perpetual contract:exchange.SetContractType("swap"). -
Futures_Bybit
Defaults to the perpetual contract of the current trading pair, with contract code:swap.
Current-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.
Directly use the exchange's contract naming: for exampleETHUSDT-04APR25. Since some contract instruments on the Bybit exchange have no clear periodicity, the exchange-defined contract code is used directly for naming. -
Futures_Kraken
Defaults to the perpetual contract of the current trading pair, with contract code:swap.
swap: perpetual contract.
month: current-month contract.
quarter: quarterly contract.
next_quarter: next-quarter contract.
third_quarter: third-quarter contract.
swap_pf: multi-collateral perpetual contract.
quarter_ff: multi-collateral quarterly contract.
month_ff: multi-collateral current-month contract.
next_quarter_ff: multi-collateral next-quarter contract.
third_quarter_ff: multi-collateral third-quarter contract.
Directly use the exchange's contract naming: for exampleFF_ETHUSD_250307. Since some contract instruments on the Kraken exchange have no clear periodicity, the exchange-defined contract code is used directly for naming. -
Futures_Bitfinex
Defaults to the perpetual contract of the current trading pair, with contract code:swap. -
Futures_Bitget
Defaults to the perpetual contract of the current trading pair, with contract code:swap.
Setting the trading pair toBTC_USDyields a coin-margined contract, and setting the trading pair toBTC_USDTyields aUSDT-settled contract. For simulation contracts, you can set the trading pair toSBTC_USDorBTC_SUSDT. -
Futures_dYdX (v4)
dYdX perpetual contract code:swap.
Set to perpetual contract:exchange.SetContractType("swap"). dYdX has only theUSD.swapinstrument dimension, and the margin used is USDC. -
Futures_MEXC
MEXC perpetual contract code:swap.
Set to perpetual contract:exchange.SetContractType("swap"). Setting the trading pair toBTC_USDyields a coin-margined contract, and setting the trading pair toBTC_USDTyields aUSDT-settled contract. -
Futures_Crypto
Tokens in the crypto.com exchange account can be converted into a USD-denominated allowance to be used as margin for contract trading.
Set to perpetual contract:exchange.SetContractType("swap"). For example, when the trading pair is set toBTC_USD, calling theexchange.SetContractType("swap")function sets the perpetual contract of BTC.
The delivery contracts on the crypto.com exchange are monthly contracts, with the following contract codes (January through December):code"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"Set a delivery contract:
exchange.SetContractType("October"). For example, when the trading pair is set toBTC_USD, calling theexchange.SetContractType("October")function sets the October delivery contract of BTC.
The contract code corresponding to the current moment isBTCUSD-231027. -
Futures_WOO
The Futures_WOO exchange supportsUSDT-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toBTC_USDT, calling theexchange.SetContractType("swap")function sets the current contract to the USDT-margined perpetual contract of BTC. -
Futures_Hyperliquid
The Futures_Hyperliquid exchange supportsUSDC-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toETH_USD, calling theexchange.SetContractType("swap")function sets the current contract to the USDC-margined perpetual contract of ETH.
Futures_Hyperliquid has only theUSD.swapinstrument dimension, and the margin used is USDC.
Futures_Hyperliquid supports HIP-3 instruments. -
Futures_Lighter
The Futures_Lighter exchange supportsUSDC-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toBTC_USDC, calling theexchange.SetContractType("swap")function sets the current contract to the USDC-margined perpetual contract of BTC.
Futures_Lighter supports perpetual contracts only. -
Futures_Backpack
The Futures_Backpack exchange supportsUSDC-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toETH_USDC, calling theexchange.SetContractType("swap")function sets the current contract to the USDC-margined perpetual contract of ETH. -
Futures_edgeX
The Futures_edgeX exchange supportsUSDT-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toBTC_USDT, calling theexchange.SetContractType("swap")function sets the current contract to the USDT-margined perpetual contract of BTC. -
Futures_WOOFI
The Futures_WOOFI exchange supportsUSDC-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toETH_USDC, calling theexchange.SetContractType("swap")function sets the current contract to the USDC-margined perpetual contract of ETH. -
Futures_Coinw
The Futures_Coinw exchange supportsUSDT-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toETH_USDT, calling theexchange.SetContractType("swap")function sets the current contract to the USDT-margined perpetual contract of ETH. -
Futures_Aster
The Futures_Aster exchange supportsUSDT-margined contracts, with perpetual contract codeswap. For example, when the trading pair is set toETH_USDT, calling theexchange.SetContractType("swap")function sets the current contract to the USDT-margined perpetual contract of ETH. -
Futures_DeepCoin
Coin-margined contracts: for example, set the trading pair toBTC_USD, then set the contract code, which yields a coin-margined contract.
Set to perpetual contract:exchange.SetContractType("swap").Contracts using USDT as margin:
For example, set the trading pair toBTC_USDT, then set the contract code, which yields a contract using USDT as margin.
Set to perpetual contract:exchange.SetContractType("swap").
exchange.GetContractType
The exchange.GetContractType() function is used to get the contract code currently set for the exchange exchange object.
exchange.GetContractType()Examples
javascript
function main () {
Log(exchange.SetContractType("this_week"))
Log(exchange.GetContractType())
}
python
def main():
Log(exchange.SetContractType("this_week"))
Log(exchange.GetContractType())
rust
fn main() {
Log!(exchange.SetContractType("this_week"));
Log!(exchange.GetContractType());
}
c++
void main() {
Log(exchange.SetContractType("this_week"));
Log(exchange.GetContractType());
}Returns
| Type | Description |
string | The |
See Also
exchange.GetFundings
The exchange.GetFundings() function is used to obtain the funding rate data for the current period.
exchange.GetFundings()
exchange.GetFundings(symbol)Examples
Using the futures exchange object, call the exchange.GetFundings() function in the backtesting system. Before any market data function is called, GetFundings returns only the Funding data of the current default trading pair; after a market data function is called, it returns the Funding data of all symbols that have been requested. Refer to the following test example:
javascript
/*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 interval
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 (var 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 symbols:", symbols, "\n`" + JSON.stringify(tbls) + "`")
}
python
'''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 interval
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 symbols:", symbols, "\n`" + json.dumps(tbls) + "`")
rust
/*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"}]
*/
fn main() {
// LPT_USDT.swap 4-hour interval
let 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);
}
let mut arr: Vec<Vec<Funding>> = Vec::new();
let 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.push(exchange.GetFundings(None).unwrap());
} else {
arr.push(exchange.GetFundings(p).unwrap());
}
}
// The Rust SDK has no JSON serialization; use format! to concatenate the table's JSON text
let mut tbls: Vec<String> = Vec::new();
for (index, fundings) in arr.iter().enumerate() {
let mut rows: Vec<String> = Vec::new();
for f in fundings {
rows.push(format!(r#"["{}", {}, "{}", "{} %"]"#, f.Symbol, f.Interval as f64 / 3600000.0, _D(f.Time), f.Rate * 100.0));
}
let tbl = format!(r#"{{"type": "table", "title": "{}", "cols": ["Symbol", "Interval", "Time", "Rate"], "rows": [{}]}}"#, arrParams[index], rows.join(","));
tbls.push(tbl);
}
LogStatus!(_D(None), "\n Requested symbols:", format!("{:?}", symbols), format!("\n`[{}]`", tbls.join(",")));
}
c++
/*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 interval
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 symbols:", arrSymbol.dump(), "\n`" + tbls.dump() + "`");
}Returns
| Type | Description |
| When the |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The |
See Also
Remarks
For futures exchanges that do not support batch querying of funding rate data, if the symbol parameter is specified as a query range (for example USDT.swap) or is not passed in, the interface will report an error. When calling the GetFundings() function on such futures exchange objects, the symbol parameter must be specified as a specific perpetual contract in order to query the current-period funding rate data for that trading pair.
The exchange.GetFundings() function supports both live trading and the backtesting system.
Exchanges that do not support batch retrieval of funding rate data: Futures_Bitget, Futures_OKX, Futures_MEXC, Futures_Deribit, Futures_Crypto. When calling, you need to pass in the symbol parameter to specify the concrete trading pair 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 |