1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bitFlyer LightningのAPIを使って、TypeScript環境で24時間365日、高頻度・高収入を目指したBTC-CFD/JPYの自動売買する

Posted at

bitFlyer LightningのAPIを使って、TypeScript環境で24時間365日、高頻度・高収入を目指したBTC-CFD/JPYの自動売買を実現するには、以下のポイントを押さえる必要があります。

  1. bitFlyer APIの理解とセットアップ
    bitFlyer APIドキュメント
    APIキーの取得(取引には "trade" 権限 が必要)
    WebSocketを活用したリアルタイムデータ取得(注文板、約定履歴、価格情報など)

  2. TypeScript環境の構築
    Node.js & TypeScriptのセットアップ
    必要なライブラリのインストール

sh

npm install axios websocket dotenv
API認証処理の実装(HMAC-SHA256署名)

  1. 戦略の実装
    SuperTrendをベースにしたシグナル検出(Pine Scriptでの改良も並行して実施)
    高頻度取引(HFT) を意識し、約定速度やスプレッドを考慮
    リスク管理(ロスカット・ポジションサイズ調整)
    スリッページ・手数料の最適化

  2. 実運用に向けたチューニング
    バックテスト(過去データを利用)
    リアルタイムシミュレーション(ペーパートレード)
    耐障害性(異常時の対応)
    VPSまたはクラウド(AWS, GCP, さくらVPSなど)での常時稼働
    具体的な実装コードを求めている場合、どの部分から進めたいですか?

📌 手順一覧
Node.js & TypeScript のセットアップ
bitFlyer API の認証処理
WebSocket を使ったリアルタイムデータ取得
SuperTrend 戦略の適用
自動売買の実装
エラーハンドリング & ログ保存
Windows スタートアップで自動起動

1️⃣ Node.js & TypeScript のセットアップ
まず、Node.js をインストールし、TypeScript 環境を構築します。

✅ 必要なソフトウェア
Node.js (LTS推奨)
Git

✅ プロジェクトの作成
sh

mkdir btc-cfd-trader
cd btc-cfd-trader
npm init -y
npm install typescript ts-node @types/node axios websocket dotenv
npx tsc --init
tsconfig.json を編集し、"module": "CommonJS" に変更。

2️⃣ bitFlyer API の認証処理
src/config.ts を作成し、APIキーを .env ファイルから読み込めるようにします。

✅ .env
ini

API_KEY=your_api_key
API_SECRET=your_api_secret
✅ src/config.ts
ts

import dotenv from "dotenv";
import crypto from "crypto";

dotenv.config();

export const API_KEY = process.env.API_KEY!;
export const API_SECRET = process.env.API_SECRET!;
export const BASE_URL = "https://api.bitflyer.com";

export function createSignature(method: string, path: string, body: string = "") {
const timestamp = Date.now().toString();
const text = timestamp + method + path + body;
const sign = crypto.createHmac("sha256", API_SECRET).update(text).digest("hex");

return { timestamp, sign };
}

3️⃣ WebSocket を使ったリアルタイムデータ取得
価格情報を WebSocket で取得し、SuperTrend の計算に利用します。

✅ src/websocket.ts
ts

import WebSocket from "ws";

const ws = new WebSocket("wss://ws.lightstream.bitflyer.com/json-rpc");

ws.on("open", () => {
console.log("WebSocket 接続成功");
ws.send(JSON.stringify({
method: "subscribe",
params: { channel: "lightning_ticker_BTC_CFD" },
}));
});

ws.on("message", (data) => {
const message = JSON.parse(data.toString());
if (message.params) {
console.log("価格情報:", message.params.message.ltp);
}
});

ws.on("close", () => console.log("WebSocket 切断"));

4️⃣ SuperTrend 戦略の適用
SuperTrend インジケーターを TypeScript で実装します。

✅ src/indicators.ts
ts

export function calculateSuperTrend(prices: number[], atr: number[]): { trend: "BUY" | "SELL"; value: number } {
const lastClose = prices[prices.length - 1];
const lastATR = atr[atr.length - 1];

const upperBand = lastClose + lastATR * 1.5;
const lowerBand = lastClose - lastATR * 1.5;

return lastClose > upperBand ? { trend: "BUY", value: lowerBand } : { trend: "SELL", value: upperBand };
}

5️⃣ 自動売買の実装
bitFlyer Lightning API を使って発注を行います。

✅ src/trade.ts
ts

import axios from "axios";
import { API_KEY, BASE_URL, createSignature } from "./config";

export async function placeOrder(side: "BUY" | "SELL", size: number) {
const path = "/v1/me/sendchildorder";
const body = JSON.stringify({
product_code: "BTC_CFD_JPY",
child_order_type: "MARKET",
side,
size,
time_in_force: "GTC",
});

const { timestamp, sign } = createSignature("POST", path, body);

try {
const response = await axios.post(BASE_URL + path, body, {
headers: {
"ACCESS-KEY": API_KEY,
"ACCESS-TIMESTAMP": timestamp,
"ACCESS-SIGN": sign,
"Content-Type": "application/json",
},
});
console.log("発注成功:", response.data);
} catch (error) {
console.error("発注エラー:", error.response?.data || error.message);
}
}

6️⃣ メインのトレードループ

✅ src/main.ts
ts

import { placeOrder } from "./trade";
import { calculateSuperTrend } from "./indicators";
import { getRecentPrices, getATR } from "./data"; // 価格データ取得関数

async function startTrading() {
while (true) {
const prices = await getRecentPrices();
const atr = await getATR();

const { trend } = calculateSuperTrend(prices, atr);

if (trend === "BUY") {
  await placeOrder("BUY", 0.01);
} else if (trend === "SELL") {
  await placeOrder("SELL", 0.01);
}

await new Promise((resolve) => setTimeout(resolve, 5000)); // 5秒待機

}
}

startTrading();
7️⃣ Windows スタートアップで自動起動

✅ start_trading.bat を作成
btc-cfd-trader フォルダ内に以下の start_trading.bat を作成。

bat

@echo off
cd /d "C:\path\to\btc-cfd-trader"
start /min cmd /c "npx ts-node src/main.ts"

✅ スタートアップ登録方法

Win + R を押して shell:startup と入力し、OK をクリック
start_trading.bat のショートカットを スタートアップフォルダ にコピー

🎯 まとめ
Node.js と TypeScript で開発
bitFlyer API の認証・発注処理を実装
WebSocket でリアルタイム価格を取得
SuperTrend に基づいて売買を判断
Windows のスタートアップで自動起動
この流れで 24時間365日の自動売買システム が構築できます!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?