Skip to main content
Glama

place_order_with_trailing_stop

Execute cryptocurrency trades on Bybit with trailing stop loss protection to automatically adjust stop levels as market prices move, managing risk while capturing profit potential.

Instructions

Place order with trailing stop loss

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryYesCategory (linear, inverse)
symbolYesSymbol (e.g., ETHUSDT)
sideYesOrder side (Buy, Sell)
orderTypeYesOrder type (Market, Limit)
qtyYesOrder quantity
priceNoOrder price (for limit orders)
trailingStopYesTrailing stop distance
activePriceNoPrice at which trailing stop activates (optional)
positionIdxNoPosition index (optional, auto-detected if not provided)
timeInForceNoTime in force (GTC, IOC, FOK)
orderLinkIdNoOrder link ID (optional)

Implementation Reference

  • The core handler function that executes the place_order_with_trailing_stop tool. It auto-detects position mode for futures, builds the order request with trailing stop parameters, and calls the Bybit API.
    async placeOrderWithTrailingStop(
      category: string,
      symbol: string,
      side: 'Buy' | 'Sell',
      orderType: 'Market' | 'Limit',
      qty: string,
      price?: string,
      trailingStop?: string,
      activePrice?: string,
      positionIdx?: string,
      timeInForce?: string,
      orderLinkId?: string
    ): Promise<BybitResponse<OrderResponse> | { error: string }> {
      // Auto-detect position mode for futures trading if positionIdx not provided
      if (['linear', 'inverse'].includes(category) && !positionIdx) {
        console.log('Auto-detecting position mode for futures trading...');
        
        // Check current positions to determine position mode
        const currentPositions = await this.getPositions(category, symbol);
        
        let detectedPositionIdx = '0'; // Default to one-way mode
        
        if ('result' in currentPositions && currentPositions.result.list.length > 0) {
          // Check if we have separate long/short positions (hedge mode)
          const positions = currentPositions.result.list;
          const hasLongPosition = positions.some(p => p.side === 'Buy');
          const hasShortPosition = positions.some(p => p.side === 'Sell');
          
          if (hasLongPosition || hasShortPosition) {
            // Hedge mode detected - use appropriate position index
            detectedPositionIdx = side === 'Buy' ? '1' : '2';
            console.log(`Hedge mode detected, using positionIdx: ${detectedPositionIdx}`);
          } else {
            console.log('One-way mode detected, using positionIdx: 0');
          }
        } else {
          console.log('No existing positions, defaulting to one-way mode (positionIdx: 0)');
        }
        
        positionIdx = detectedPositionIdx;
      }
    
      // Validate positionIdx for futures trading (after auto-detection)
      if (['linear', 'inverse'].includes(category)) {
        if (!positionIdx || !['0', '1', '2'].includes(positionIdx)) {
          return { error: 'Invalid positionIdx. Use 0 for one-way mode, 1 for long position, or 2 for short position in hedge mode' };
        }
      }
    
      // Build order request with trailing stop
      const orderRequest: any = {
        category,
        symbol,
        side,
        orderType,
        qty,
        timeInForce: timeInForce || (orderType === 'Market' ? 'IOC' : 'GTC'),
        orderFilter: 'Order',
        isLeverage: 0
      };
    
      // Add price for limit orders
      if (orderType === 'Limit' && price) {
        orderRequest.price = price;
      }
    
      // Add trailing stop parameters
      if (trailingStop) {
        orderRequest.trailingStop = trailingStop;
        
        // Add active price if provided (price at which trailing stop activates)
        if (activePrice) {
          orderRequest.activePrice = activePrice;
        }
      }
    
      // Add position index for futures
      if (['linear', 'inverse'].includes(category)) {
        orderRequest.positionIdx = positionIdx;
      }
    
      // Add order link ID if provided
      if (orderLinkId) {
        orderRequest.orderLinkId = orderLinkId;
      }
    
      return this.makeBybitRequest('/v5/order/create', 'POST', orderRequest);
    }
  • The input schema defining parameters and validation for the place_order_with_trailing_stop tool in the MCP server.
      name: 'place_order_with_trailing_stop',
      description: 'Place order with trailing stop loss',
      inputSchema: {
        type: 'object',
        properties: {
          category: {
            type: 'string',
            description: 'Category (linear, inverse)',
          },
          symbol: {
            type: 'string',
            description: 'Symbol (e.g., ETHUSDT)',
          },
          side: {
            type: 'string',
            description: 'Order side (Buy, Sell)',
          },
          orderType: {
            type: 'string',
            description: 'Order type (Market, Limit)',
          },
          qty: {
            type: 'string',
            description: 'Order quantity',
          },
          price: {
            type: 'string',
            description: 'Order price (for limit orders)',
          },
          trailingStop: {
            type: 'string',
            description: 'Trailing stop distance',
          },
          activePrice: {
            type: 'string',
            description: 'Price at which trailing stop activates (optional)',
          },
          positionIdx: {
            type: 'string',
            description: 'Position index (optional, auto-detected if not provided)',
          },
          timeInForce: {
            type: 'string',
            description: 'Time in force (GTC, IOC, FOK)',
          },
          orderLinkId: {
            type: 'string',
            description: 'Order link ID (optional)',
          },
        },
        required: ['category', 'symbol', 'side', 'orderType', 'qty', 'trailingStop'],
      },
    },
  • src/index.ts:1046-1068 (registration)
    The switch case registration that handles incoming calls to place_order_with_trailing_stop by invoking the BybitService handler.
    case 'place_order_with_trailing_stop': {
      const result = await this.bybitService.placeOrderWithTrailingStop(
        typedArgs.category,
        typedArgs.symbol,
        typedArgs.side,
        typedArgs.orderType,
        typedArgs.qty,
        typedArgs.price,
        typedArgs.trailingStop,
        typedArgs.activePrice,
        typedArgs.positionIdx,
        typedArgs.timeInForce,
        typedArgs.orderLinkId
      );
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'place order' which implies a write/mutation operation, but fails to disclose critical traits like authentication needs, rate limits, potential for financial loss, or what happens on execution (e.g., order confirmation). This is a significant gap for a trading tool with financial implications.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that gets straight to the point with no wasted words. It's front-loaded with the core action, though it could be slightly more structured by hinting at the tool's complexity given the many parameters.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex trading tool with 11 parameters, no annotations, and no output schema, the description is inadequate. It doesn't cover behavioral aspects (e.g., risks, auth), output expectations, or how it differs from siblings. The agent lacks sufficient context to use this tool safely and effectively in a financial trading environment.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 11 parameters thoroughly. The description adds no additional meaning beyond implying that 'trailingStop' is a key feature, but it doesn't explain parameter interactions (e.g., how 'activePrice' relates to 'trailingStop') or provide usage examples. Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Place order with trailing stop loss' clearly states the action (place order) and key feature (trailing stop loss), but it's vague about what type of order is being placed and doesn't distinguish from sibling tools like 'place_order' or 'set_trading_stop'. It specifies the trailing stop mechanism but lacks detail on the broader order context.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives such as 'place_order' (without trailing stop) or 'set_trading_stop' (which might modify existing orders). The description implies usage for orders with trailing stops but offers no context, prerequisites, or exclusions, leaving the agent to infer based on parameter names alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kondisettyravi/mcp-bybit-node'

If you have feedback or need assistance with the MCP directory API, please join our Discord server