質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

2667閲覧

Swaggerを用いたAPI構築時のファイル構成とそれぞれの役割について

masayoshi555

総合スコア9

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2019/11/08 01:01

編集2019/11/08 05:46

背景

 BitMEXというサービスのAPI(https://github.com/BitMEX/api-connectors)を使ってiPhoneアプリを作ろうと考えております。

構築環境

macbbookpro(mid17) OS10.15.1(Catalina)

現状

 こちらのサイトを参考にswaggerを用いたRESTfulAPI環境構築を実施し、githubのswagger-apiサンプルコードの実行まで出来ました。
(URLの末尾を変更することで、"hello, {name}!"の{name}が変わることをターミナル上で確認)

出来ないこと

 BitMEXでの応用にいたりません。
その原因としてサンプルファイル群のそれぞれの機能を理解していないことにあると考えています。

現時点で理解していること

 先ほどのサイトを参考に以下の部分までは理解出来ました。
現状これ以上の理解がありません。
イメージ説明
イメージ説明
イメージ説明

知りたいこと(質問のピントがずれているかも)

 - それぞれのファイルの役割
- BitMEXでやる場合、どのファイルがどう置き換わるのか
イメージ説明
- API keyやAPI secret~~ kye~~はどこに入力するのか
・・・などなど恐らく知らなければいけないことに対して、全て質問が出来ていないと思われます。
「まずはここを見なさい」でも構いませんので、情報頂けると大変助かります。

やったこと

 - 本屋さんで参考になりそうな本を探した → ない。orもしくわわからない
- ネットで参考になりそうなファイル構成を説明してそうなサイトを探した → 断片的
参考サイト:https://qiita.com/ta1nakamura/items/9ce151835d5b131fddf4
API関連、特にswaggerは情報が少なく苦労しています。(そもそもAPI関連も少ない)

追記

その後、BitMEX側にある程度の文書があることがわかりました。(一般的だと後ほどわかりました)
https://www.bitmex.com/app/apiKeysUsage
その中にAPI keyとAPI secret(secret keyとは言わないんですね)の入力場所があるのですが、それがどのファイルかはわかりませんでした。
イメージ説明

追記2

正しいかどうかはわかっていないのですが、その後のアクションを追記します。
swaggerのsampleコードとbitmexのサンプルコードで対応するものを探しました。
これに対して不足や指摘があればお願いしたいです。

  1. app.jsに該当するものを見つけ、ルート直下へ

イメージ説明
0. apiファイルを作成し、定義ファイルを移動&node_modulesフォルダのコピー
イメージ説明
0. swaggerClient.jsの「接続できません:TypeError:未定義のプロパティ ‘add’を読み取れません」
web上に解決策あったので、これに基づき解決(https://codeday.me/jp/qa/20190426/709259.html

before

1'use strict'; 2var SwaggerClient = require("swagger-client"); 3var _ = require('lodash'); 4var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization'); 5 6require('dotenv').config(); 7 8new SwaggerClient({ 9 // Switch this to `www.bitmex.com` when you're ready to try it out for real. 10 // Don't forget the `www`! 11 url: 'https://testnet.bitmex.com/api/explorer/swagger.json', 12 usePromise: true 13}) 14.then(function(client) { 15 //console.log(client); 16 // Comment out if you're not requesting any user data. 17 client.clientAuthorizations.add("apiKey", new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET)); 18 19 // Print client capabilities 20 // 21 22}) 23.catch(function(e) { 24 console.error("Unable to connect:", e); 25})

after

1new SwaggerClient({ 2 // Switch this to `www.bitmex.com` when you're ready to try it out for real. 3 // Don't forget the `www`! 4 url: 'https://testnet.bitmex.com/api/explorer/swagger.json', 5 usePromise: true, 6 authorizations: { 7 apiKey: new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET) 8 } 9}) 10.then(client => { 11 // Do whatever with client 12}) 13.catch(function(e) { 14console.error("Unable to connect:", e); 15})

結果(現在)

フォルダ構成は以下の通り、
イメージ説明
この状態でのターミナルからの実行結果

terminal

1**:bitmex admin$ swagger project start 2Starting: /Users/admin/swagger/bitmex/swaggerClient.js... 3 project started here: http://undefined/api/v1 4 project will restart on changes. 5 to restart at any time, enter `rs` 6/Users/admin/swagger/bitmex/swaggerClient.js:11 7 authorizations: { 8 ^^^^^^^^^^^^^^ 9 10SyntaxError: Unexpected identifier 11 at wrapSafe (internal/modules/cjs/loader.js:891:16) 12 at Module._compile (internal/modules/cjs/loader.js:941:27) 13 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1011:10) 14 at Module.load (internal/modules/cjs/loader.js:822:32) 15 at Function.Module._load (internal/modules/cjs/loader.js:730:14) 16 at Function.Module.runMain (internal/modules/cjs/loader.js:1051:12) 17 at internal/main/run_main_module.js:16:11

swaggerClient

1'use strict'; 2var SwaggerClient = require("swagger-client"); 3var _ = require('lodash'); 4var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization'); 5 6new SwaggerClient({ 7 // Switch this to `www.bitmex.com` when you're ready to try it out for real. 8 // Don't forget the `www`! 9 url: 'https://testnet.bitmex.com/api/explorer/swagger.json', 10 usePromise: true, 11 authorizations: { 12 apiKey: new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET) 13 } 14}) 15.then(client => { 16 // Comment out if you're not requesting any user data. 17 // client.clientAuthorizations.add("apiKey", new BitMEXAPIKeyAuthorization('api-key', 'api-secret')); 18 19 // Print client capabilities 20 inspect(client.apis); 21 22 // Get a trade 23 client.Trade.Trade_get({symbol: 'XBTUSD', count: 40}) 24 .then(function(response) { 25 var trades = JSON.parse(response.data.toString()); 26 // Print the max price traded in the last `count` trades. 27 console.log('\nMax Trade:\n----\n', JSON.stringify(_.max(trades, 'price'), undefined, 2)); 28 }) 29 .catch(function(e) { 30 // Error handling... 31 console.log('Error:', e.statusText); 32 }) 33 34 client.User.User_getMargin() 35 .then(function(response) { 36 var margin = JSON.parse(response.data.toString()); 37 var marginBalance = (margin.marginBalance / 1e8).toFixed(4); 38 console.log('\nMargin Balance:', marginBalance, 'XBT'); 39 }) 40 .catch(function(e) { 41 // Error handling... 42 console.log('Error:', e.statusText); 43 }) 44 45 // Example: Placing an order - commented for your safety 46 // .then(function() { 47 // return client.Order.Order_new({symbol: 'XBTUSD', price: 1000, orderQty: 1}) 48 // }) 49 // .then(function (response) { 50 // console.log(response.data.toString()); 51 // }); 52 53 // Example: sending a bulk order 54 // Note: due to a bug in the Swagger client, you must stringify the Array, otherwise 55 // we will be sent `["[object Object]","[object Object]"]` 56 // client.Order.Order_newBulk({ 57 // "orders": JSON.stringify([ 58 // {"symbol":"XBTUSD","price":2433.5,"orderQty":147,"side":"Sell"}, 59 // {"symbol":"XBTUSD","price":2431.1,"orderQty":190,"side":"Sell"} 60 // ]) 61 // }) 62 // .then(function (response) { 63 // console.log(response.data.toString()); 64 // }); 65}) 66.catch(function(e) { 67 console.error("Unable to connect:", e); 68}) 69 70function inspect(client) { 71 console.log("Inspecting BitMEX API..."); 72 Object.keys(client).forEach(function(model) { 73 if (!client[model].operations) return; 74 console.log("Available methods for %s: %s", model, Object.keys(client[model].operations).join(', ')); 75 }); 76 console.log("------------------------\n"); 77}

追記3

"authorizations:{エラー"は以下の変更でなくなりましたが、次のエラーが出ました。引き続き検証します。
(参考URL:https://github.com/swagger-api/swagger-js/blob/903569948d5a5c718d7b87d6832a672de4e76afc/docs/MIGRATION_2_X.md#authorizations

swaggerClient

1'use strict'; 2var SwaggerClient = require("swagger-client"); 3var _ = require('lodash'); 4var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization'); 5 6new SwaggerClient({ 7 // Switch this to `www.bitmex.com` when you're ready to try it out for real. 8 // Don't forget the `www`! 9 url: 'https://testnet.bitmex.com/api/explorer/swagger.json', 10 usePromise: true, 11 authorizations: { 12 apiKey: new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET) 13 } 14}) 15.then(client => { 16(以下変更なし)

swaggerClient

1'use strict'; 2var SwaggerClient = require("swagger-client"); 3var _ = require('lodash'); 4var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization'); 5 6var client = new SwaggerClient('http://petstore.swagger.io/v2/swagger.json',{ 7 // Switch this to `www.bitmex.com` when you're ready to try it out for real. 8 // Don't forget the `www`! 9 url: 'https://testnet.bitmex.com/api/explorer/swagger.json', 10 usePromise: true, 11 authorizations: { 12 apiKey: new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET) 13 } 14}) 15.then(client => { 16(以下省略)

terminalerror

1:bitmex admin$ swagger project start 2Starting: /Users/admin/swagger/bitmex/swaggerClient.js... 3 project started here: http://undefined/api/v1 4 project will restart on changes. 5 to restart at any time, enter `rs` 6Inspecting BitMEX API... 7------------------------ 8 9Unable to connect: TypeError: Cannot read property 'Trade_get' of undefined 10 at /Users/admin/swagger/bitmex/swaggerClient.js:23:16 11 at processTicksAndRejections (internal/process/task_queues.js:93:5)

js:23:16は "client.Trade.Trade_get({symbol: 'XBTUSD', count: 40})"です。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

最終的にauthorizationエラーが治らず解決しませんでした。

色々調べているうちにこちらのサイトに辿り着き、
あっという間にAPIテストが完了しました。

BitMEXのサンプルコードよりもシンプルで、ファイルも一つなので、一見してわかりやすい内容です。
https://note.mu/take_bits/n/n36db57e2f70f

Node.js

1var request = require('request'); 2var crypto = require('crypto'); 3 4var key = '自分のAPIキー'; 5var secret = 'シークレットキー'; 6 7//かこの時間だとエラーになるので余裕に足すと良い 8var timestamp = parseInt(Date.now() / 1000 + 60); 9 10//5555ドルで100枚買う 11order_simple('Buy', 100, 5555); 12//order_simple('Sell', 100, 9999); 13 14function order_simple (_side, _size, _price) { 15 var path = '/api/v1/order'; 16 var body = JSON.stringify({ 17 symbol: 'XBTUSD', 18 side: _side, 19 orderQty: _size, 20 price: _price, 21 ordType: "Limit", 22 //clOrdID: "clOrdID" 23 }); 24 var url = "https://www.bitmex.com" + path; 25 var mathod = "POST"; 26 var text = mathod + path + timestamp + body; 27 var sign = crypto.createHmac('sha256', secret).update(text).digest('hex'); 28 var options = { 29 url: url, 30 method: mathod, 31 body: body, 32 headers: { 33 'Content-Type': 'application/json', 34 'Accept': 'application/json', 35 'X-Requested-With': 'XMLHttpRequest', 36 'api-expires': timestamp, 37 'api-key': key, 38 'api-signature': sign, 39 } 40 }; 41 42 43 44 //リクエスト開始 45 request(options, function (err, response, payload) { 46 if (!payload) {return;} 47 var getData = JSON.parse(payload); 48 49 if (getData.error) { 50 console.log("message:", getData.error.message); 51 console.log("name:", getData.error.name); 52 return 53 } 54 55 console.log("orderID:", getData.orderID); 56 console.log("clOrdID:", getData.clOrdID); 57 console.log("clOrdLinkID:", getData.clOrdLinkID); 58 console.log("account:", getData.account); 59 console.log("symbol:", getData.symbol); 60 console.log("side:", getData.side); 61 console.log("simpleOrderQty:", getData.simpleOrderQty); 62 console.log("orderQty:", getData.orderQty); 63 console.log("price:", getData.price); 64 console.log("displayQty:", getData.displayQty); 65 console.log("stopPx:", getData.stopPx); 66 console.log("pegOffsetValue:", getData.pegOffsetValue); 67 console.log("pegPriceType:", getData.pegPriceType); 68 console.log("currency:", getData.currency); 69 console.log("settlCurrency:", getData.osettlCurrency); 70 console.log("ordType:", getData.ordType); 71 console.log("timeInForce:", getData.timeInForce); 72 console.log("execInst:", getData.execInst); 73 console.log("contingencyType:", getData.contingencyType); 74 console.log("exDestination:", getData.exDestination); 75 console.log("ordStatus:", getData.ordStatus); 76 console.log("triggered:", getData.triggered); 77 console.log("workingIndicator:", getData.workingIndicator); 78 console.log("ordRejReason:", getData.ordRejReason); 79 console.log("simpleLeavesQty:", getData.simpleLeavesQty); 80 console.log("leavesQty:", getData.leavesQty); 81 console.log("simpleCumQty:", getData.simpleCumQty); 82 console.log("cumQty:", getData.cumQty); 83 console.log("avgPx:", getData.avgPx); 84 console.log("multiLegReportingType:", getData.multiLegReportingType); 85 console.log("text:", getData.text); 86 console.log("transactTime:", getData.transactTime); 87 console.log("timestamp:", getData.timestamp); 88 }); 89 90}

投稿2019/11/14 17:45

masayoshi555

総合スコア9

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問