mcpField
O
orderly-trading-orders

orderly-trading-orders

github.com/orderlynetworkその他276 回インストール1 日前に更新
リポジトリ

orderly-trading-orders について

orderly-trading-ordersは、Orderly Networkの注文をREST APIとReact SDKで管理する開発者向けスキルです。注文の発注、変更、キャンセルに加え、検証、一括処理、リアルタイム監視を扱います。

主な機能

  1. 01複数の注文タイプを解説
  2. 02REST APIで注文を発注・編集
  3. 03React SDKで注文を管理
  4. 04注文を一括作成・キャンセル
  5. 05注文状況をリアルタイム監視

活用シーン

  1. 01取引インターフェースの注文フォームを構築
  2. 02取引ボットの注文ロジックを実装
  3. 03銘柄ルールに基づいて注文パラメーターを検証
  4. 04注文状況を追跡して未約定注文をキャンセル

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/orderlynetwork/skills --skill orderly-trading-orders

インストール後、Claude Code で/orderly-trading-ordersを入力して読み込まれたか確認します。

詳細

Orderly Network:取引注文

このスキルでは、REST API と React SDK を通じた注文の管理(注文の発注、変更、キャンセル)について、すべての側面を扱います。

使用する場面

  • 取引インターフェースを構築する
  • 注文発注ロジックを実装する
  • 注文のライフサイクルを管理する
  • 自動取引ボットを作成する

前提条件

  • Orderly アカウントが登録済みであること
  • trading スコープを持つ Ed25519 API キー
  • アカウントに十分な担保があること

注文タイプ

タイプ説明ユースケース
LIMIT指定した価格での注文正確なエントリー/決済
MARKET利用可能な最良価格で執行即時執行
IOC即時約定またはキャンセル部分約定を許容
FOK全量約定またはキャンセル全量約定のみ
POST_ONLYメイカー専用注文メイカーリベートを獲得
ASK最良売値が保証される素早く売却する
BID最良買値が保証される素早く購入する

REST API:注文の発注

エンドポイント
POST /v1/order
リクエストボディ
interface OrderRequest {
  symbol: string; // e.g., "PERP_ETH_USDC"
  side: 'BUY' | 'SELL';
  order_type: 'LIMIT' | 'MARKET' | 'IOC' | 'FOK' | 'POST_ONLY' | 'ASK' | 'BID';
  order_price?: number; // Required for LIMIT orders
  order_quantity: number; // Base asset quantity
  visible_quantity?: number; // For hidden orders (0 = hidden)
  client_order_id?: string; // Your custom ID
  trigger_price?: string; // For stop orders
}
例
import { signAsync } from '@noble/ed25519';

async function placeOrder(order: OrderRequest) {
  const timestamp = Date.now();
  const body = JSON.stringify(order);
  const message = `${timestamp}POST/v1/order${body}`;

  const signature = await signAsync(new TextEncoder().encode(message), privateKey);

  // Encode as base64url (browser & Node.js compatible)
  const base64 = btoa(String.fromCharCode(...signature));
  const base64url = base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

  const response = await fetch('https://api.orderly.org/v1/order', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'orderly-timestamp': String(timestamp),
      'orderly-account-id': accountId,
      'orderly-key': `ed25519:${publicKeyBase58}`,
      'orderly-signature': base64url,
    },
    body,
  });

  return response.json();
}

// Place a limit buy order
const order = await placeOrder({
  symbol: 'PERP_ETH_USDC',
  side: 'BUY',
  order_type: 'LIMIT',
  order_price: 3000,
  order_quantity: 0.1,
});

React SDK:useOrderEntry

SDK には、注文入力に便利なフックが用意されています。

import { useOrderEntry, OrderSide, OrderType } from '@orderly.network/hooks';

function OrderForm({ symbol }: { symbol: string }) {
  const {
    submit,
    setValue,
    getValue,
    helper,
    reset,
    isSubmitting
  } = useOrderEntry(symbol, {
    initialOrder: {
      side: OrderSide.BUY,
      order_type: OrderType.LIMIT,
      price: '',
      order_quantity: '',
    },
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validate before submission
    const validationResult = await helper.validate();
    if (!validationResult) {
      console.error('Validation failed');
      return;
    }

    try {
      await submit();
      reset();
      console.log('Order placed successfully');
    } catch (error) {
      console.error('Order failed:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <select
        onChange={(e) => setValue('side', e.target.value as OrderSide)}
        value={getValue('side')}
      >
        <option value={OrderSide.BUY}>Buy</option>
        <option value={OrderSide.SELL}>Sell</option>
      </select>

      <select
        onChange={(e) => setValue('order_type', e.target.value as OrderType)}
        value={getValue('order_type')}
      >
        <option value={OrderType.LIMIT}>Limit</option>
        <option value={OrderType.MARKET}>Market</option>
      </select>

      <input
        type="text"
        placeholder="Price"
        value={getValue('price') || ''}
        onChange={(e) => setValue('price', e.target.value)}
      />

      <input
        type="text"
        placeholder="Quantity"
        value={getValue('order_quantity') || ''}
        onChange={(e) => setValue('order_quantity', e.target.value)}
      />

      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Placing...' : 'Place Order'}
      </button>
    </form>
  );
}

注文の検証

送信前に、注文パラメーターを検証します。

// Get order rules for a symbol
const rulesResponse = await fetch('https://api.orderly.org/v1/public/info/PERP_ETH_USDC');
const rules = await rulesResponse.json();

/*
Rules include:
- base_min: Minimum order size
- base_max: Maximum order size
- base_tick: Size increment
- quote_min: Minimum price
- quote_max: Maximum price
- quote_tick: Price increment
- min_notional: Minimum order value
*/

function validateOrder(order: OrderRequest, rules: OrderRules): boolean {
  // Price filter
  if (order.order_price) {
    const price = parseFloat(order.order_price);
    if (price < rules.quote_min || price > rules.quote_max) {
      throw new Error('Price out of range');
    }
    if ((price - rules.quote_min) % rules.quote_tick !== 0) {
      throw new Error('Invalid price tick');
    }
  }

  // Size filter
  const quantity = parseFloat(order.order_quantity);
  if (quantity < rules.base_min || quantity > rules.base_max) {
    throw new Error('Quantity out of range');
  }
  if ((quantity - rules.base_min) % rules.base_tick !== 0) {
    throw new Error('Invalid quantity tick');
  }

  // Min notional
  const notional = (parseFloat(order.order_price) || 0) * quantity;
  if (notional < rules.min_notional) {
    throw new Error(`Minimum order value is ${rules.min_notional}`);
  }

  return true;
}

注文のキャンセル

単一注文のキャンセル
// REST API
DELETE /v1/order?order_id={order_id}&symbol={symbol}

// React SDK
import { useOrderStream } from '@orderly.network/hooks';

function OrderList() {
  const [orders, { cancelOrder }] = useOrderStream({
    status: OrderStatus.INCOMPLETE,
  });

  return orders.map((order) => (
    <div key={order.order_id}>
      {order.symbol} - {order.side} - {order.order_qty}
      <button onClick={() => cancelOrder(order.order_id)}>
        Cancel
      </button>
    </div>
  ));
}
すべての注文をキャンセル
// REST API - Cancel all open orders
DELETE /v1/orders?symbol={symbol}  // Optional symbol filter

// React SDK
const [orders, { cancelAllOrders }] = useOrderStream();

await cancelAllOrders(); // Cancel all
await cancelAllOrders({ symbol: 'PERP_ETH_USDC' }); // Cancel for specific symbol
クライアント注文 ID によるキャンセル
DELETE /v1/client/order?client_order_id={client_order_id}&symbol={symbol}

一括注文

1 回のリクエストで複数の注文を発注またはキャンセルします。

// Batch create (max 10 orders)
POST /v1/batch-order
Body: {
  orders: [
    { symbol: 'PERP_ETH_USDC', side: 'BUY', order_type: 'LIMIT', order_price: 3000, order_quantity: 0.1 },
    { symbol: 'PERP_BTC_USDC', side: 'BUY', order_type: 'LIMIT', order_price: 50000, order_quantity: 0.01 }
  ]
}

// Batch cancel (max 10 orders)
DELETE /v1/batch-order?order_ids={id1},{id2},...

// Example
const batchResponse = await fetch('https://api.orderly.org/v1/batch-order', {
  method: 'POST',
  headers: { /* auth headers */ },
  body: JSON.stringify({
    orders: [
      { symbol: 'PERP_ETH_USDC', side: 'BUY', order_type: 'LIMIT', order_price: 3000, order_quantity: 0.1 },
      { symbol: 'PERP_BTC_USDC', side: 'BUY', order_type: 'LIMIT', order_price: 50000, order_quantity: 0.01 }
    ]
  }),
});

注文の編集

既存の注文の価格または数量を変更します。

// REST API
PUT /v1/order
Body: {
  order_id: '123456',
  order_price: '3100',      // New price
  order_quantity: '0.2',    // New quantity
}

注文ストリーム(リアルタイム)

注文をリアルタイムで監視します。

import { useOrderStream, OrderStatus } from '@orderly.network/hooks';

function OrderMonitor() {
  const [orders, { cancelOrder }] = useOrderStream({
    status: OrderStatus.INCOMPLETE,
  });

  return (
    <table>
      <thead>
        <tr>
          <th>Symbol</th>
          <th>Side</th>
          <th>Price</th>
          <th>Quantity</th>
          <th>Filled</th>
          <th>Status</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        {orders.map((order) => (
          <tr key={order.order_id}>
            <td>{order.symbol}</td>
            <td>{order.side}</td>
            <td>{order.price}</td>
            <td>{order.order_qty}</td>
            <td>{order.filled_qty}</td>
            <td>{order.status}</td>
            <td>
              <button onClick={() => cancelOrder(order.order_id)}>
                Cancel
              </button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

アルゴ注文(ストップ、TP/SL)

利食い注文と損切り注文については、orderly-positions-tpsl スキルを参照してください。

// Basic algo order structure
POST /v1/algo/order
Body: {
  symbol: 'PERP_ETH_USDC',
  type: 'CLOSE_POSITION',
  algoType: 'TAKE_PROFIT',
  trigger_price: '3500',
  quantity: '0.1',
}

レート制限

エンドポイントレート制限
POST /v1/order10 req/sec
DELETE /v1/order10 req/sec
PUT /v1/order10 req/sec
POST /v1/batch-order1 req/sec
DELETE /v1/batch-order10 req/sec

注文ステータスのフロー

NEW → PARTIAL_FILLED → FILLED
                    ↘ CANCELLED
         ↘ REJECTED (invalid orders)
         ↘ EXPIRED (GTD orders)

よくある問題

「Insufficient margin」エラー
  • 利用可能な担保を確認します:GET /v1/client/holding
  • 注文サイズを減らすか、担保を追加します
「Price out of range」エラー
  • 注文価格はマーク価格の price_range 以内である必要があります
  • BUY の場合:価格 ≤ mark_price × (1 + price_range)
  • SELL の場合:価格 ≥ mark_price × (1 - price_range)
「Invalid tick size」エラー
  • 価格は quote_tick の倍数である必要があります
  • 数量は base_tick の倍数である必要があります
注文が直ちに拒否される
  • 注文ルールを GET /v1/public/info/{symbol} で確認します
  • min_notional、価格範囲、サイズ制限を確認します

関連スキル

  • orderly-api-authentication - リクエストの署名方法
  • orderly-positions-tpsl - ポジションと TP/SL の管理
  • orderly-websocket-streaming - リアルタイムの注文更新
  • orderly-sdk-react-hooks - SDK の完全なリファレンス

コメント