
Hello everyone, recently I’ve received a lot of feedback about workflow usage, and the most frequently asked questions are about equity percentage ordering and take-profit/stop-loss settings. Many friends say: “I know I need to control risk, but how exactly do I calculate order quantities based on account balance? And how do I automatically set take-profit and stop-loss after opening positions to let the system manage risk for us?”
Today, we’ll address these practical needs and, using actual code from the FMZ Quant platform, explain in detail how to implement these two core functions.

Equity percentage ordering means not using a fixed number of contracts, but calculating the order quantity based on a fixed percentage of the total account balance.
Example:
Core Advantages:
// 1. Get account information
const accountInfo = exchange.GetAccount();
if (!accountInfo) {
return [{
json: {
success: false,
error: "Failed to get account information"
}
}];
}
const availBalance = accountInfo.Balance; // Available balance
Log("Account available balance:", availBalance);
Key Point: The Balance field represents the available balance, which is the foundation for calculations.
// 2. Get market information
const symbol = $vars.coin + '_USDT.swap' || 'ETH_USDT.swap';
const allMarkets = exchange.GetMarkets();
const marketsInfo = allMarkets[symbol];
if (!marketsInfo) {
return [{
json: {
success: false,
error: `Trading pair information not found: ${symbol}`
}
}];
}
Core Parameter Descriptions:
Special Note: Be sure to check whether the coin you want to trade exists on the exchange.
// 3. Get current price
const ticker = exchange.GetTicker(symbol);
if (!ticker) {
return [{
json: {
success: false,
error: "Failed to get price information"
}
}];
}
const currentPrice = ticker.Last; // Latest transaction price
Log("Current price:", currentPrice);
// 4. Calculate contract quantity
const riskRatio = $vars.riskRatio || 0.05; // Default 5% risk ratio
// Step 1: Calculate risk amount
const riskAmount = availBalance * riskRatio;
// Step 2: Calculate coin quantity
let coinQuantity = riskAmount / currentPrice;
// Step 3: Convert to contract quantity (because futures trading uses contract units)
let contractQuantity = coinQuantity / marketsInfo.CtVal;
// Step 4: Precision handling (ensure order quantity meets exchange requirements)
contractQuantity = _N(contractQuantity, marketsInfo.AmountPrecision);
Log("Calculation steps:");
Log("- Risk amount:", riskAmount);
Log("- Coin quantity:", coinQuantity);
Log("- Contract value:", marketsInfo.CtVal);
Log("- Original contract quantity:", coinQuantity / marketsInfo.CtVal);
Log("- After precision handling:", contractQuantity);
Calculation Formula Summary:
Contract Quantity = (Account Balance × Risk Ratio ÷ Current Price) ÷ Contract Value
// 5. Check limits
if (contractQuantity < marketsInfo.MinQty) {
return [{
json: {
success: false,
error: `Calculated quantity ${contractQuantity} is less than minimum requirement ${marketsInfo.MinQty}`,
calculatedQuantity: contractQuantity,
minQty: marketsInfo.MinQty
}
}];
}
if (contractQuantity > marketsInfo.MaxQty) {
Log("Quantity exceeds maximum limit, using maximum value:", marketsInfo.MaxQty);
contractQuantity = marketsInfo.MaxQty;
}
Log("Final order quantity:", contractQuantity);
Common Beginner Mistakes:
When the above settings are incorrect, order failure alerts will appear, which is something beginners need to pay special attention to.

Many friends easily get confused about the direction of take-profit and stop-loss orders. Let’s clarify:
| Position Type | Take-Profit Operation | Stop-Loss Operation |
|---|---|---|
| Long Position | Sell to close when price rises | Sell to close when price falls |
| Short Position | Buy to close when price falls | Buy to close when price rises |
Key Point: Both take-profit and stop-loss are closing operations, and the direction must be opposite to the position direction.
On the FMZ platform, use the CreateConditionOrder function to set take-profit and stop-loss:
Currently, the FMZ platform’s live trading supports CreateConditionOrder conditional orders, but backtesting does not yet support them.
exchange.CreateConditionOrder(
symbol, // Trading pair
closeDirection, // Close direction: closebuy or closesell
positionSize, // Close quantity
{
"ConditionType": ORDER_CONDITION_TYPE_SL, // Stop-loss type
"SlTriggerPrice": stopLossPrice, // Trigger price
"SlOrderPrice": executionPrice // Execution price
},
"Stop-loss order" // Order note
);
Parameter Descriptions:
Operation Type (closeDirection):
ConditionType:
TriggerPrice (Trigger Price): Order is activated when this price is reached
OrderPrice (Execution Price): Order is executed at this price after activation
Note: Currently only live trading supports conditional orders, and the docker needs to be updated.
In the code, we dynamically calculate based on the opening direction:
const stopLossPercent = 0.02; // 2% stop-loss
const takeProfitPercent = 0.04; // 4% take-profit
if (openSide == 'openShort') {
// Short position: stop-loss price rises, take-profit price falls
stopLossPrice = _N(entryPrice * (1 + stopLossPercent), pricePrecision);
takeProfitPrice = _N(entryPrice * (1 - takeProfitPercent), pricePrecision);
} else {
// Long position: stop-loss price falls, take-profit price rises
stopLossPrice = _N(entryPrice * (1 - stopLossPercent), pricePrecision);
takeProfitPrice = _N(entryPrice * (1 + takeProfitPercent), pricePrecision);
}
Log("Entry price:", entryPrice);
Log("Stop-loss price:", stopLossPrice);
Log("Take-profit price:", takeProfitPrice);
After setting up conditional orders, we still need to manage and monitor them:
// Query conditional order status
const slOrder = exchange.GetConditionOrder(stopLossOrderId);
const tpOrder = exchange.GetConditionOrder(takeProfitOrderId);
Log("Stop-loss order status:", slOrder.Status);
Log("Take-profit order status:", tpOrder.Status);
Log("Status description: 0=Active, 1=Triggered, -1=Does not exist");
Status Handling Logic:
if (slStatus == 1 && tpStatus == 0) {
// Stop-loss triggered, cancel take-profit order
Log("🛑 Stop-loss order triggered, canceling take-profit order");
exchange.CancelConditionOrder(takeProfitOrderId);
_G('status', 'finished');
} else if (tpStatus == 1 && slStatus == 0) {
// Take-profit triggered, cancel stop-loss order
Log("🎯 Take-profit order triggered, canceling stop-loss order");
exchange.CancelConditionOrder(stopLossOrderId);
_G('status', 'finished');
} else if (slStatus == 0 && tpStatus == 0) {
// Both orders still active, continue monitoring
Log("⏳ Both take-profit and stop-loss orders active, continue monitoring");
}
Key Functions:
Important Notes:
In the demonstration workflow, we use a state machine to manage the complete trading cycle:
const savestatus = _G('status');
// Initialize status
if (!savestatus) {
_G('status', 'unfinished');
}
Three States:
By integrating equity percentage ordering with take-profit and stop-loss, we have a complete trading workflow:
Flowchart:
Calculate Order Quantity → Execute Opening → Set Take-Profit/Stop-Loss → Monitor Position → Trade Completed
Code Implementation:
// State 1: Execute opening
if (positionData.status == 'unfinished') {
// 1. Open position order
const openOrder = exchange.CreateOrder(symbol, dir, -1, positionSize);
// 2. Wait for order execution
Sleep(3000);
const openOrderInfo = exchange.GetOrder(openOrder);
// 3. Set take-profit and stop-loss after order execution
if (openOrderInfo.Status == ORDER_STATE_CLOSED) {
const stopLossOrderId = exchange.CreateConditionOrder(...);
const takeProfitOrderId = exchange.CreateConditionOrder(...);
// 4. Save order IDs and switch to monitoring state
_G('stopLossOrderId', stopLossOrderId);
_G('takeProfitOrderId', takeProfitOrderId);
_G('status', 'monitor');
}
}
// State 2: Monitor take-profit and stop-loss
if (positionData.status == 'monitor') {
// Check conditional order status, handle trigger situations
// ...
}
// State 3: Trade completed
if (positionData.status == 'finished') {
_G('status', 'unfinished'); // Reset status, prepare for next trade
}
Advantages of the Entire Process:
Risk Ratio: - Beginners recommended: 2-3% - Experienced traders: 5-10% - Don’t be greedy and set it too high; set it according to your own risk tolerance
Take-Profit and Stop-Loss Ratios: - Stop-loss: 1-3% (adjust based on coin volatility) - Take-profit: 2-6% (usually 1.5-2 times the stop-loss) - Need to set reasonably based on different coin characteristics
Complete Testing Checklist:
Testing Process:
Remember: Test thoroughly before going live - this is a fundamental principle of quantitative trading.
Alright, that’s all for today’s discussion on equity percentage ordering and take-profit/stop-loss settings. This workflow combines risk control with automated execution, making our trading more standardized. However, everyone’s trading style and risk tolerance are different, so remember to adjust the parameters according to your actual situation when using it. If you encounter any problems during use, or have other questions about quantitative trading, feel free to come and consult. Let’s discuss together and improve together.
Source Code Reference: https://www.fmz.com/strategy/517040